I'm having trouble creating a sf::Sprite in a sf::Thread and then rendering it. Here's a small watered down example of what my code does. Ignore the stupid class names, I made this in about 10 minutes and was trying to make it as readable as possible -
#include <iostream>
#include <vector>
#include <memory>
#include <SFML\Graphics.hpp>
#include <SFML\System.hpp>
//a random class for this example
class ObjectThing{
public:
sf::Sprite sprite;
sf::Texture texture;
ObjectThing(float x, float y, float rotation){
this->texture.loadFromFile("troll.png");
this->sprite.setTexture(this->texture);
this->sprite.setPosition(x, y);
this->sprite.setRotation(rotation);
std::cout << "Hello world!" << std::endl;
}
};
//the class that holds and creates the objectThings
class ObjectThingHolder{
public:
static std::vector<std::unique_ptr<ObjectThing> > objectThings;
static void CreateObjectThing(float x, float y, float rotation){
objectThings.push_back(std::unique_ptr<ObjectThing>(new ObjectThing(x, y, rotation)));
}
};
//define the SpriteHolder's objectThings variable
std::vector<std::unique_ptr<ObjectThing> > ObjectThingHolder::objectThings;
//the function we'll use for our sf::Thread
void threadFunction(){
//this object gets created but doesnt get rendered
ObjectThingHolder::CreateObjectThing(0, 0, 0);
}
int main(){
sf::RenderWindow window(sf::VideoMode(800, 600, 32), "SFML thread sprite test");
//this guy also gets created but does render!
ObjectThingHolder::CreateObjectThing(0, 0, 0);
//create and launch our thread
sf::Thread theThread(threadFunction);
theThread.launch();
//while windows open, poll events and render the world
while(window.isOpen()){
sf::Event e;
while(window.pollEvent(e)){
if (e.type == sf::Event::Closed){
window.close();
}
}
//clear the screen
window.clear(sf::Color(0, 0, 0, 255));
//draw each of the ObjectThings sprites
for(int i = 0; i < (int)ObjectThingHolder::objectThings.size(); i++){
window.draw(ObjectThingHolder::objectThings.at(i)->sprite);
}
//display the result
window.display();
}
}
As you can see after reading the code is that the ObjectThing created from within the main loop does get rendered while the ObjectThing created inside the sf::Thread doesn't. I'm completely oblivious to the reasoning for this. But I'm assuming it has something to do with the scope of the threads and what they can access. Help would be greatly appreciated!