lundi 24 avril 2017

SFML RenderWindow in another thread is unresponsive

I have the following class.

class MainWindow
{
private:
    sf::RenderWindow window;
    std::vector<std::unique_ptr<sf::Drawable> comps;
    mutable std::mutex mutex;

public:
    MainWindow(unsigned w, unsigned h, const std::string& name)
        : window(sf::VideoMode(w, h), name)
    {}

    void show()
    {
        //window.setActive(false);
        std::thread([this] 
        {
            //window.setActive(true);
            while (window.isOpen())
            {
                window.clear(sf::Color::Black);
                // handle events
                std::lock_guard<std::mutex> lock(mutex);
                for (auto&& c : comps)
                    window.draw(*c.get());
                window.display();
            }
        }).join();
        //window.setActive(true);
    }

    void add(sf::Drawable* comp) 
    {
        std::lock_guard<std::mutex> lock(mutex);
        comps.emplace_back(comp);
    }
};

int main() 
{
    MainWindow window(500, 500, "Window name");
    window.add(new sf::CircleShape(5.5f));
    window.show();
}

Basically my goal is to separate the making of the window from the adding of the Drawable elements, as seen in the main function.

I read that since OpenGL doesn't allow you to have a context active in multiple threads, I should call setActive on the window, as I've done above in the commented code.

It all works fine (things are getting drawn), but the window is unresponsive (can't move, resize or close). (All window-related events are handled.)

Why is this happening and how would I fix it?

Aucun commentaire:

Enregistrer un commentaire