Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - smguyk

Pages: 1 [2] 3
16
Graphics / Why is drawing my sf::VertexArray so CPU-extensive?
« on: October 20, 2014, 06:41:58 pm »
I am using the code from the tutorial for my game's tilemap.

The tilemap of the test level of my game only has 17 * 20 tiles each 32x32 pixels (and I'm planning to add a whole lot more tiles) but the CPU usage goes to 25% when drawing the vertex array.

I call drawTiles(*window); to draw it which is just a member function of the tilemap class. The function is

void TileMap::drawTiles(sf::RenderTarget &target) {
  sf::RenderStates states = sf::RenderStates::Default;
  states.transform *= getTransform();
  states.texture = &tilesTexture_;
  target.draw(tilesVertexArray_, states);
}

I used the Visual Studio Performance Wizard to see what's causing the heavy CPU usage, and it says it's the vertex array draw call.

Indeed, when I comment out the drawTiles(*window); to no longer draw the tilemap, the CPU goes down to 0%, even with no framerate limit.

What am I doing wrong, please??

17
In my 2D platformer I am passing the player's current view to the entity manager, so I only draw the entities that are currently in view.

I pass the following sf::FloatRect (currentView_ is just an sf::View):
sf::FloatRect(
  currentView_.getCenter().x - currentView_.getSize().x / 2,
  currentView_.getCenter().y - currentView_.getSize().y / 2,
  currentView_.getSize().x,
  currentView_.getSize().y
)

When I then use sf::FloatRect.intersects it doesn't draw the entities, but when I use sf::FloatRect.contains it draws them just fine.

void EntityManager::drawEntities(sf::RenderTarget &renderTarget, sf::FloatRect &rect) {
  // Doesn't work:
  for (std::vector<Entity>::iterator i = entities_.begin(); i != entities_.end(); ++i) {
    if (rect.intersects(i->getRect()) {
      renderTarget.draw(*i);
    }
  }

  // Works:
  for (std::vector<Entity>::iterator i = entities_.begin(); i != entities_.end(); ++i) {
    if (rect.contains(i->getRect().left + i->getRect().width / 2, i->getRect().top + i->getRect().height / 2)) {
      renderTarget.draw(*i);
    }
  }
}

In case it's needed, the function getRect() returns the entity's float rect:

sf::FloatRect Entity::getRect() {
  return sf::FloatRect(position_.x, position_.y, dimensions_.x, dimensions_.y);
}

The problem with it not working is that I don't want to check if only the entity's center is within the current view, but rather if ANY POINT of the entity's rect is.

Could someone please help me?

18
Graphics / Card flipping animation
« on: August 26, 2014, 08:48:36 am »
I'm making a memory game and I'd like to animate flipping over a card. A card is just an sf::Sprite.

The card (or: sprite) should revolve around its own axis, maybe something like this http://davidwalsh.name/demo/css-flip.php but I haven't found any code that could help me.

sf::Sprite::rotate exists and it rotates the sprite, but I need a rotation around the sprite's y-axis.

Can someone please help me?

19
Graphics / sf::VertexArray: Draw only vertices within certain bounds
« on: July 06, 2014, 06:25:42 am »
I am using the code from the tutorial to draw a tile map and it works just fine.

Now, my level vertex array is getting pretty big and I only want to render tiles within certain bounds (those tiles that are currently in the view) instead of drawing all of them. The tutorial code has the following lines to draw the whole vertex array:

states.transform *= getTransform();
states.texture = &m_tileset;
target.draw(m_vertices, states);

How would I modify that code to draw only vertices that are, say, in an sf::IntRect(x, y, w, h) which I'd pass as a parameter?

I seriously have no idea. Could you please help me / start me off?

Thanks!

20
General / Mobile development (iOS etc.)
« on: June 25, 2014, 03:56:17 am »
Hi!

I haven't found any info on whether it's possible to port to mobile devices, for example iOS. I only found this thread and some posts scattered throughout the SFML forum.

Is it possible yet to compile for iOS and the like, and if so, can anyone direct me to some resources how one would go about that? Google wasn't really helpful...

Thanks

Edit:
It says on the main page "and soon Android & iOS". No idea how I could overlook that.
Does anyone know how the development is going for those platforms / the estimated release date?

21
Is it possible to compile for Mac/Linux using MS Visual Studio or any other compiler on Windows?

I don't have Mac or Linux but want my game for those platforms too

22
Hey,

I have this resource class that holds my resources (just fonts) for me. I call initialise() to load the resources, then I do the normal program flow and before I exit the program I call cleanUp(). This is all working perfectly.

This is the code for the class. resources.h:

#ifndef __RESOURCES_H__
#define __RESOURCES_H__

#include <SFML\Graphics.hpp>

class Resources {
 public:
  Resources();
  bool initialise();
  void cleanUp();
  bool loadAllFonts();
  bool loadFont(std::string filename);
  sf::Font &getFont(std::string filename);

  const std::string myFont_;
  const std::string myOtherFont_;

 private:
  const std::string fontPath_;
  std::map<std::string, sf::Font*> fonts_;

};

#endif

resources.cpp

#include "resources.h"

Resources::Resources() :
  myFont_("./data/myFont.ttf"),
  myOtherFont_("./data/myOtherFont.ttf")
{
}

bool Resources::initialise() {
  if (loadAllFonts()) { return true; }
  return false;
}

void Resources::cleanUp() {
  std::map<std::string, sf::Font*>::iterator font_it;
  for (font_it = fonts_.begin(); font_it != fonts_.end(); font_it++) {
    delete font_it->second;
    font_it->second = NULL;
  }
  fonts_.clear();
}

bool Resources::loadAllFonts() {
  if (!loadFont(myFont_)) { return false; }
  if (!loadFont(myOtherFont_)) { return false; }
  return true;
}

bool Resources::loadFont(std::string filename) {
  if (fonts_.find(filename) != fonts_.end()) {
    return false;
  }
  sf::Font *font = new sf::Font();
  sf::err().rdbuf(NULL);
  if (!font->loadFromFile(filename)) {
    delete font;
    font = NULL;
    return false;
  }
  const_cast<sf::Texture&>(font->getTexture(8)).setSmooth(false);
  const_cast<sf::Texture&>(font->getTexture(12)).setSmooth(false);
  const_cast<sf::Texture&>(font->getTexture(16)).setSmooth(false);
  const_cast<sf::Texture&>(font->getTexture(24)).setSmooth(false);
  fonts_.insert(std::pair<std::string, sf::Font*>(filename, font));
  return true;
}

sf::Font &Resources::getFont(std::string filename) {
  return *(fonts_.find(filename)->second);
}

This was simple enough and went without problems. I just use the class like this:

int main() {
  //...

  Resources resources_;
  resources_.initialise();

  sf::Text testText("test text", resources_.getFont(resources_.myFont_), 25);

  // ... (program loop)

  resources_.cleanUp();

  return 0;
}

Now, what I want to do is the following:

In Resources::loadFont(), instead of loading a font from a file with loadFromFile(filename), I want to load it from memory.

I know how loading a font from memory works. I simply convert a font file and fill an unsigned char array with the font data:

unsigned char myFontChar[] = {0x00,0x01,0x00, .......... ,0x00,0x30,0x00,0x03,0x00,0xc0,0x4f,0x53,0x2f};

Then I load the font like this:

sf::Font font;
if (!font.loadFromMemory(myFontChar, sizeof(myFontChar))) { return -1; }

This is working when I do it as demonstrated above, but I have no idea how I would go about adjusting the Resources::loadFont() function so that instead of loading the specified font from a file it loads it from memory (the unsigned char array).

Could you please help me and point me in the right direction?

I am not a pro, so this is hard for me, but I have some vague idea how to do it (in theory). I would apply the same principle that I currently have: Use an "identifier", so the std::map could be used.

Instead of std::map<std::string, sf::Font*> I would have to use something that replaces the second parameter sf::Font*, but I don't know what that would be and how the Resources::loadFont() function would then look like.

I hope I explained it well enough and really really hope someone can help me.

Thanks!

23
Graphics / Centering text on a rectangle not working
« on: May 07, 2014, 04:55:18 pm »
I have an sf::RectangleShape inputFieldRect_ and an sf::Text inputFieldText_ and I want to center the text on the rectangle because the sf::Text's dimensions will vary because its string will have different lengths.

After setting inputFieldText_'s string with inputFieldText_.setString(s); (s is a an std::string that the user inputs) I am adjusting its position so that it's still in the center of inputFieldRect_.

This is my code for that but the text is too much to the left and a little too much to the bottom, so not perfectly centered:

sf::FloatRect rectBounds = inputFieldRect_.getGlobalBounds();
sf::FloatRect textBounds = inputFieldText_.getGlobalBounds();

inputFieldText_.setPosition(
  rectBounds.left + (rectBounds.width / 2) - (textBounds.width / 2),
  rectBounds.top + (rectBounds.height / 2) - (textBounds.height / 2)
);

Can someone please help me? I don't see the flaw.

24
General / Weird behaviour when moving window
« on: April 23, 2014, 03:04:07 pm »
I am working on a platformer with a tile map and collision and stuff. Today I moved the window to see the console output (because the console window was hidden behind my game's window) and to my surprise my character fell through solid tiles and even out of the map's boundaries.

So I did a little testing and it turns out this only happens when I drag the window around. Why is this happening? This could also be potentially disastrous for my game (it crashes for collision testing outside a certain area) but that's not the point. Is there a way to circumvent this? Like either this not happening at all or simply stop updating the game whilst the window is being dragged?

I could make the game full screen but I also want to support windowed mode...

Thanks

25
Graphics / Multiple sf::Views
« on: March 29, 2014, 10:05:24 am »
When using multiple sf::Views, do they really have to be reset every frame?

When I don't call reset(), it won't work, but it feels a bit weird having to do that...

In my game I have a view that displays the UI and stuff (defaultView_), and another view that follows the player and shows a small part of the complete world around the player (camera_). I use this code in my draw function:

  window_->clear();

  // Player camera
  camera_.reset(sf::FloatRect(0, 0, 640, 480));
  camera_.setCenter(calculateNewCameraPosition());
  window_->setView(camera_);

  window_->draw(tileMap_);
  window_->draw(player_);

  // View for the UI
  defaultView_.reset(sf::FloatRect(0, 0, 1024, 768));
  window_->setView(defaultView_);

  window_->draw(playerInfoText_);
  window_->draw(fpsText_);

  window_->display();

Is that the correct way to do it? I'm kind of starting a new project and I want to do everything right from the beginning!

Thanks

26
Graphics / Questions on sf::View
« on: March 25, 2014, 10:14:46 am »
For my side scroller, I need a camera that always centers on my player's position.

I have 3 questions regarding the use of sf::View:

In my player's update function, I create a view, set its center to the player's position, and set it as the window's view.

  sf::View v(sf::FloatRect(0, 0, 320, 240));
  v.setCenter(player_.getPosition());
  window_->setView(v);

1.) I tried using the view as an sf::View class member but it didn't work, so now I'm creating the view every tick as seen in the code above. Is that how it is supposed to be done, or should I be wary of how resource intensive it may be, aka what is the correct way to do it?

2.) Now that I have the view that is smaller than the entire map, not all information is displayed anymore. For example I had a UI (displaying hit points and stuff) and an FPS display in my window's corners which I now can't see anymore unless my player, ie the view, is near it. Do I have to use multiple views or something to display everything?

3.) Due to using a view it's not necessary anymore to render the entire map, but only what is seen in the view. Is that done automatically or do I need to somehow program myself what is to be rendered?

I would appreciate any help on this

Thank you!

27
Graphics / Problem with SFML's tutorial AnimatedSprite by Foaly
« on: March 03, 2014, 07:58:19 pm »
I read this tutorial https://github.com/SFML/SFML/wiki/Source:-AnimatedSprite and tried to implement it myself, but it's not completely working.
Everything is fine except for this line from the example code:

animatedSprite.play(*currentAnimation);

When I run the program with that line, the following error occurs: http://i.imgur.com/ckpzfdk.png
Does anyone know how to fix that? When I for example use the following code instead of the code above everything runs fine

animatedSprite.play(walkingAnimationLeft);

But of course that's not what I want. I want the play the currentAnimation.

28
General / Simple program high CPU usage
« on: March 02, 2014, 03:49:11 pm »
I'm currently working on a platformer and trying to implement a timestep, but for framerate limits greater than 60 the CPU usage goes up from 1% to 25% and more.

I made this minimal program to demonstrate the issue. There are two comments (in red, lines 10-13, lines 26-30) in the code that describe the problem and what I have tested.

Note that the FPS stuff is not relevant to the problem (I think).

I tried to keep the code short and simple:

    #include <memory>
    #include <sstream>
    #include <iomanip>
    #include <SFML\Graphics.hpp>
   
    int main() {
      // Window
      std::shared_ptr<sf::RenderWindow> window;
      window = std::make_shared<sf::RenderWindow>(sf::VideoMode(640, 480, 32), "Test", sf::Style::Close);
      /*
      When I use the setFramerateLimit() function below, the CPU usage is only 1% instead of 25%+
      (And only if I set the limit to 60 or less. For example 120 increases CPU usage to 25%+ again.)
      */

      //window->setFramerateLimit(60);
   
      // FPS text
      sf::Font font;
      font.loadFromFile("font.ttf");
      sf::Text fpsText("", font, 30);
      fpsText.setColor(sf::Color(0, 0, 0));
   
      // FPS
      float fps;
      sf::Clock fpsTimer;
      sf::Time fpsElapsedTime;
      /*
      When I set framerateLimit to 60 (or anything less than 60)
      instead of 120, CPU usage goes down to 1%.
      When the limit is greater, in this case 120, CPU usage is 25%+
      */

      unsigned int framerateLimit = 120;
      sf::Time fpsStep = sf::milliseconds(1000 / framerateLimit);
      sf::Time fpsSleep;
      fpsTimer.restart();
   
      while (window->isOpen()) {
        // Update timer
        fpsElapsedTime = fpsTimer.restart();
        fps = 1000.0f / fpsElapsedTime.asMilliseconds();
   
        // Update FPS text
        std::stringstream ss;
        ss << "FPS: " << std::fixed << std::setprecision(0) << fps;
        fpsText.setString(ss.str());
   
        // Get events
        sf::Event evt;
        while (window->pollEvent(evt)) {
          switch (evt.type) {
          case sf::Event::Closed:
            window->close();
            break;
          default:
            break;
          }
        }
   
        // Draw
        window->clear(sf::Color(255, 255, 255));
        window->draw(fpsText);
        window->display();
   
        // Sleep
        fpsSleep = fpsStep - fpsTimer.getElapsedTime();
        if (fpsSleep.asMilliseconds() > 0) {
          sf::sleep(fpsSleep);
        }
   
      }
   
      return 0;
    }

I don't want to use SFML's setFramerateLimit(), but my own implementation with the sleep because I will use the fps data to update my physics and stuff.

Is there a logic error in my code? I fail to see it, given it works with a framerate limit of for example 60 (or less). Is it because I have a 60 Hz monitor?

PS: Using SFML's window->setVerticalSync() doesn't change the results

Thank you

29
Hi,

I get this error message (in fact, 3 same messages) in the Windows console after closing the window:

Code: [Select]
An internal OpenAL call failed in SoundBuffer.cpp (75) : AL_INVALID_OPERATION, the specified operation is not allowed in the current state
and the program also crashes ("the program has stopped working" window) with the following details:

Code: [Select]
Problem signature:
  Problem Event Name: APPCRASH
  Application Name: Mastermind.exe
  Application Version: 0.1.3.2
  Application Timestamp: 530db220
  Fault Module Name: MSVCP110D.dll
  Fault Module Version: 11.0.51106.1
  Fault Module Timestamp: 50988588
  Exception Code: c0000005
  Exception Offset: 0000f069
  OS Version: 6.1.7601.2.1.0.256.48

Everything in my program is working. Audio and everything else is fine but after closing the program it crashes.

I don't know what code to post, so I'll just post the sound system stuff:

soundsystem.h:

#ifndef __SOUNDSYSTEM_H__
#define __SOUNDSYSTEM_H__

#include <string>
#include <SFML/Audio.hpp>

class SoundSystem {

public:
  SoundSystem();
  virtual ~SoundSystem();

  void setAudioEnabled(bool status) { audioEnabled_ = status; };
  void setMenuSoundsEnabled(bool status) { menuSoundsEnabled_ = status; };
  void setGameSoundsEnabled(bool status) { gameSoundsEnabled_ = status; };
  void forceDisabledAudio() { disabledAudioForced_ = true; };

  bool audioEnabled() const { return audioEnabled_; };
  bool menuSoundsEnabled() const { return menuSoundsEnabled_; };
  bool gameSoundsEnabled() const { return gameSoundsEnabled_; };
  unsigned int getSoundVolume() const { return soundsVolume_; };
  bool disabledAudioForced() const { return disabledAudioForced_; };

  void playSound(const std::string &soundName);
  void setSoundsVolume(unsigned int volume);
  void stopAll();

private:
  int maximumSounds_;
  sf::Sound sounds_[30];
  bool audioEnabled_;
  bool menuSoundsEnabled_;
  bool gameSoundsEnabled_;
  unsigned int soundsVolume_;
  int lastSoundPlayed_;
  bool disabledAudioForced_;

};

#endif

soundsystem.cpp:

#include "soundsystem.h"
#include "config.h"
#include "resources.h"

SoundSystem::SoundSystem() :
  maximumSounds_(30),
  audioEnabled_(true),
  menuSoundsEnabled_(true),
  gameSoundsEnabled_(true),
  soundsVolume_(50),
  lastSoundPlayed_(0),
  disabledAudioForced_(false)
  {
}

SoundSystem::~SoundSystem() {
}

void SoundSystem::playSound(const std::string &soundName) {
  if (audioEnabled_) {
    if (lastSoundPlayed_ == maximumSounds_) {
      lastSoundPlayed_ = 0;
    }
    sf::Sound &sound = sounds_[lastSoundPlayed_];
    if (sound.getStatus() == sf::Sound::Playing) {
      sound.stop();
    }
    sound.setBuffer(resourceHolder.getSoundBuffer(soundName));
    sound.setPitch(1);
    sound.play();
    ++lastSoundPlayed_;
  }
}

void SoundSystem::setSoundsVolume(unsigned int volume) {
  if (volume > 100) {
    volume = 100;
  }
  soundsVolume_ = volume;
  for (int i = 0; i < maximumSounds_; ++i) {
    sounds_[i].setVolume((float)volume);
  }
}

void SoundSystem::stopAll() {
  for (int i = 0; i < maximumSounds_; ++i) {
    if (sounds_[i].getStatus() == sf::Sound::Playing) {
      sounds_[i].stop();
    }
  }
}

Before closing the window I call SoundSystem's stopAll() if that's relevant.

Could anyone please help me?

30
General / Problem with setFramerateLimit()
« on: December 19, 2013, 12:46:08 pm »
Hi!

When I set the window's framerate limit to 60 I get ~35 FPS. When I set the limit to 120 I get ~65 FPS. When I don't define a limit I get over 8000 FPS.

Now, I want my game to run at 60 FPS. I can't really set the framerate limit to 60 though because then for some reason it stays at ~35 FPS.

Can someone please help me? What am I doing wrong?!

Edit: I made a quick example code (untested)

int main() {
  sf::RenderWindow window(sf::VideoMode(800, 600, 32), "Test", sf::Style::Close);
  window.setFramerateLimit(60);

  sf::Font font;
  if (!font.loadFromMemory(fontChar, fontSize)) {
    return -1;
  }

  sf::Clock c;
  sf::Text t = sf::Text("", font, 30);
  t.setColor(sf::Color(0, 0, 0));

  while (window.isOpen()) {
    sf::Event evt;
    while (window.pollEvent(evt)) {
      switch (evt.type) {
      case sf::Event::Closed:
        window.close();
        break;
      default:
        break;
      }
    }

    window.clear(sf::Color(255, 255, 255));

    float fps = 1.f / c.restart().asSeconds();
    std::stringstream ss;
    ss << "FPS: " << (int)fps;
    t.setString(ss.str());

    window.draw(t);
    window.display();
  }

  return 0;
}

Pages: 1 [2] 3
anything