【问题标题】:How to properly do Context Sharing with GLFW?如何正确使用 GLFW 进行上下文共享?
【发布时间】:2016-12-04 02:25:55
【问题描述】:

我想要做的是,如果我用一个新窗口替换我正在渲染的窗口,这可能是因为用户切换屏幕,或者从全屏切换到窗口,或者任何数量的其他原因。

到目前为止,我的代码如下所示:

“上下文.h”

struct window_deleter {
    void operator()(GLFWwindow * window) const;
};

class context {
    std::unique_ptr<GLFWwindow, window_deleter> window;
public:
    context(int width, int height, const char * s, GLFWmonitor * monitor, GLFWwindow * old_window, bool borderless);
    GLFWwindow * get_window() const;
    void make_current() const;
};

“上下文.cpp”

context::context(int width, int height, const char * s, GLFWmonitor * monitor, GLFWwindow * old_window, bool borderless) {
    if (!glfwInit()) throw std::runtime_error("Unable to Initialize GLFW");
    if (borderless) glfwWindowHint(GLFW_DECORATED, 0);
    else glfwWindowHint(GLFW_DECORATED, 1);
    window.reset(glfwCreateWindow(width, height, s, monitor, old_window));
    if (!window) throw std::runtime_error("Unable to Create Window");
    make_current();
}

GLFWwindow * context::get_window() const {
    return window.get();
}

void context::make_current() const {
    glfwMakeContextCurrent(window.get());
}

“窗口管理器.h”

#include "Context.h"
class window_style;
/* window_style is basically a really fancy "enum class", and I don't 
 * believe its implementation or interface are relevant to this project.
 * I'll add it if knowing how it works is super critical.
 */

class window_manager {
    context c_context;
    uint32_t c_width, c_height;
    std::string c_title;
    window_style c_style;
    std::function<bool()> close_test;
    std::function<void()> poll_task;
public:
    static GLFWmonitor * get_monitor(window_style style);
    window_manager(uint32_t width, uint32_t height, std::string const& title, window_style style);
    context & get_context();
    const context & get_context() const;
    bool resize(uint32_t width, uint32_t height, std::string const& title, window_style style);
    std::function<bool()> get_default_close_test();
    void set_close_test(std::function<bool()> const& test);
    std::function<void()> get_default_poll_task();
    void set_poll_task(std::function<void()> const& task);

    void poll_loop();
};

“窗口管理器.cpp”

GLFWmonitor * window_manager::get_monitor(window_style style) {
    if (style.type != window_style::style_type::fullscreen) return nullptr;
    if (!glfwInit()) throw std::runtime_error("Unable to initialize GLFW");
    int count;
    GLFWmonitor ** monitors = glfwGetMonitors(&count);
    if (style.monitor_number >= uint32_t(count)) throw invalid_monitor_exception{};
    return monitors[style.monitor_number];
}

std::function<bool()> window_manager::get_default_close_test() {
    return [&] {return glfwWindowShouldClose(c_context.get_window()) != 0; };
}

window_manager::window_manager(uint32_t width, uint32_t height, std::string const& title, window_style style) :
c_context(int(width), int(height), title.c_str(), get_monitor(style), nullptr, style.type == window_style::style_type::borderless),
    c_width(width), c_height(height), c_title(title), c_style(style), close_test(get_default_close_test()), poll_task(get_default_poll_task()) {
}
context & window_manager::get_context() {
    return c_context;
}
const context & window_manager::get_context() const {
    return c_context;
}

bool window_manager::resize(uint32_t width, uint32_t height, std::string const& title, window_style style) {
    if (width == c_width && height == c_height && title == c_title && style == c_style) return false;
    c_width = width;
    c_height = height;
    c_title = title;
    c_style = style;
    c_context = context(int(width), int(height), title.c_str(), get_monitor(style), get_context().get_window(), style.type == window_style::style_type::borderless);
    return true;
}

void window_manager::set_close_test(std::function<bool()> const& test) {
    close_test = test;
}

std::function<void()> window_manager::get_default_poll_task() {
    return [&] {glfwSwapBuffers(c_context.get_window()); };
}

void window_manager::set_poll_task(std::function<void()> const& task) {
    poll_task = task;
}

void window_manager::poll_loop() {
    while (!close_test()) {
        glfwPollEvents();
        poll_task();
    }
}

“Main.cpp”

int main() {
    try {
        glfwInit();
        const GLFWvidmode * vid_mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
        gl_backend::window_manager window(vid_mode->width, vid_mode->height, "First test of the window manager", gl_backend::window_style::fullscreen(0));
        glfwSetKeyCallback(window.get_context().get_window(), [](GLFWwindow * window, int, int, int, int) {glfwSetWindowShouldClose(window, 1); });
        glbinding::Binding::initialize();
        //Anything with a "glresource" prefix is basically just a std::shared_ptr<GLuint> 
        //with some extra deletion code added.
        glresource::vertex_array vao;
        glresource::buffer square;
        float data[] = {
            -.5f, -.5f,
            .5f, -.5f,
            .5f, .5f,
            -.5f, .5f
        };
        gl::glBindVertexArray(*vao);
        gl::glBindBuffer(gl::GL_ARRAY_BUFFER, *square);
        gl::glBufferData(gl::GL_ARRAY_BUFFER, sizeof(data), data, gl::GL_STATIC_DRAW);
        gl::glEnableVertexAttribArray(0);
        gl::glVertexAttribPointer(0, 2, gl::GL_FLOAT, false, 2 * sizeof(float), nullptr);

        std::string vert_src =
            "#version 430\n"
            "layout(location = 0) in vec2 vertices;"
            "void main() {"
            "gl_Position = vec4(vertices, 0, 1);"
            "}";

        std::string frag_src =
            "#version 430\n"
            "uniform vec4 square_color;"
            "out vec4 fragment_color;"
            "void main() {"
            "fragment_color = square_color;"
            "}";
        glresource::shader vert(gl::GL_VERTEX_SHADER, vert_src);
        glresource::shader frag(gl::GL_FRAGMENT_SHADER, frag_src);
        glresource::program program({ vert, frag });
        window.set_poll_task([&] {
            gl::glUseProgram(*program);
            gl::glBindVertexArray(*vao);
            glm::vec4 color{ (glm::sin(float(glfwGetTime())) + 1) / 2, 0.f, 0.5f, 1.f };
            gl::glUniform4fv(gl::glGetUniformLocation(*program, "square_color"), 1, glm::value_ptr(color));
            gl::glDrawArrays(gl::GL_QUADS, 0, 4);
            glfwSwapBuffers(window.get_context().get_window());
        });
        window.poll_loop();
        window.resize(vid_mode->width, vid_mode->height, "Second test of the window manager", gl_backend::window_style::fullscreen(1));
        glfwSetKeyCallback(window.get_context().get_window(), [](GLFWwindow * window, int, int, int, int) {glfwSetWindowShouldClose(window, 1); });
        window.poll_loop();
    }
    catch (std::exception const& e) {
        std::cerr << e.what() << std::endl;
        std::ofstream error_log("error.log");
        error_log << e.what() << std::endl;
        system("pause");
    }
    return 0;
}

所以当前版本的代码应该做到以下几点

  1. 在主显示器上显示全屏窗口
  2. 在此显示器上,显示一个“正方形”(实际上是矩形......),随着时间的推移在洋红色和蓝色之间转换,而背景在洋红色和绿色之间转换。
  3. 当用户按下一个键时,使用第一个窗口的上下文在第二个监视器上创建一个新的全屏窗口以输入 GLFW 的窗口创建,并销毁原始窗口(按此顺序)
  4. 在第二个窗口上显示相同的矩形
  5. 继续定期转换背景
  6. 当用户再次按键时,销毁第二个窗口并退出程序。

在这些步骤中,步骤 4 根本不起作用,步骤 3 部分起作用:窗口确实已创建,但默认情况下不显示,用户必须通过任务栏调用它。所有其他步骤都按预期工作,包括两个窗口上的过渡背景。

所以我的假设是上下文之间的对象共享出现了问题;具体来说,我创建的第二个上下文似乎没有接收第一个上下文创建的对象。我犯了明显的逻辑错误吗?我应该做其他事情来确保上下文共享按预期工作吗? GLFW中是否有可能只是一个错误?

【问题讨论】:

    标签: c++ opengl glfw


    【解决方案1】:

    所以我的假设是上下文之间的对象共享出现了问题;具体来说,我创建的第二个上下文似乎没有接收第一个上下文创建的对象。我犯了明显的逻辑错误吗?

    是的,你的前提是错误的。共享的 OpenGL 上下文不会共享整个状态,只是实际保存用户特定数据的“大”对象(如 VBO、纹理、着色器和程序、渲染缓冲区等),而不是仅引用它们的对象 - 状态容器像 VAO、FBO 等永远不会共享。

    我是否应该采取其他措施来确保上下文共享按预期工作?

    好吧,如果你真的想走那条路,你必须重新构建所有那些状态容器,并恢复全局状态(所有那些glEnables、深度缓冲区设置、混合状态,还有很多其他的事物)的原始上下文。

    但是,我发现您的整个概念在这里令人怀疑。从全屏切换到窗口,或切换到同一 GPU 上的不同显示器时,您不需要销毁窗口,GLFW 通过glfwSetWindowMonitor() 直接支持。

    即使您确实重新创建了一个窗口,这并不意味着您必须重新创建 GL 上下文。 GLFWs API 在这方面可能会施加一些限制,但基本概念是分开的。您基本上可以在新窗口中使旧上下文成为当前上下文,然后就完成了。 GLFW 只是将 Window 和 Context 不可分割地联系在一起,这是一种不幸的抽象。

    但是,我能想象的唯一需要重新创建窗口的场景是不同的屏幕由不同的 GPU 驱动 - 但 GL 上下文共享无法跨不同的 GL 实现工作,所以即使在这种情况下,您将不得不重建整个上下文状态。

    【讨论】:

    • 是否有一个全面的论坛或博客文章可以准确讨论哪些内容可以共享,哪些内容不可以?我尝试阅读OpenGL spec(第 5 章)来弄清楚,但这对我来说有点太神秘了。我将努力重写我的代码,这样它就不必破坏窗口,但问题仍然是相关的,因为我的下一步是努力让多个窗口同时使用相同的对象,这意味着我将无法摆脱上下文共享的麻烦。
    • 除了规范,我不知道有什么好的描述。请注意,您不一定需要多个窗口的多个上下文,您也可以在一个窗口之后使用具有相同上下文的一个窗口,并且有一些较新的扩展可以使这种上下文切换不那么繁重(尽管仍然不清楚它是否值得)。
    • 好的。我会花更多的时间盯着规范。同时,重写此代码以使用glfwSetWindowMonitor 和其他类似功能解决了我的问题,所以我会接受这个答案。
    猜你喜欢
    • 2021-11-30
    • 2015-05-29
    • 1970-01-01
    • 2014-01-09
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2021-01-18
    相关资源
    最近更新 更多