opengl 无法创建GLFW窗口

sgtfey8w  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(339)

我想创建共享GLFW窗口,但GLFW无法创建第二个窗口。
我可以创建一个窗口,但不能创建两个窗口
这是我的密码。
我想在另一个线程中使用第二个窗口,这样我就可以共享它们的上下文。


# include "pch.h"

# include <iostream>

# include <gl\glew.h>

# include <glfw3.h>

int SCR_WIDTH = 1920;
int SCR_HEIGHT = 1080;

int main()
{
  glfwInit();
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  // glfw window creation
  // --------------------
  GLFWwindow* sharedWindow = NULL;
  GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", 0, sharedWindow);
  if (window == NULL)
  {
    std::cout << "Failed to create the first  GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  if (sharedWindow == NULL)
  {
    std::cout << "Failed to create the second GLFW window" << std::endl;
    //  glfwTerminate();
    //  return -1;
  }

  while (true)
  {

  }
    std::cout << "Hello World!\n"; 
}
kmbjn2e3

kmbjn2e31#

share是输入参数。请参阅glfwCreateWindow
创建第一个窗口,并为第二个窗口第二次调用glfwCreateWindow

GLFWwindow* wnd  = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", 0, nullptr);

GLFWwindow* wnd2 = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "window 2", 0, window);

该窗口甚至可以在单独的线程中创建,但请注意,在创建第二个窗口时,您必须确保第一个窗口的OpenGL上下文不是当前的。


# include <thread>

# include <mutex>

# include <condition_variable>

GLFWwindow *wnd = nullptr;
bool wnd2created = false;
std::mutex mtx;
std::condition_variable cv;

void wnd2func( void )
{
    GLFWwindow *wnd2 = glfwCreateWindow( 800, 600, "window 2", nullptr, wnd );

    {
        std::unique_lock<std::mutex> lck(mtx);
        wnd2created = true;
        cv.notify_one();
    }

    if (wnd2 == nullptr)
        return;

    glfwMakeContextCurrent(wnd2);

    // [...]
}

int main()
{
    // [...]

    wnd = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", 0, nullptr);
    if (wnd == nullptr)
        return -1;

    std::thread wnd2thread(wnd2func); 

    {
      std::unique_lock<std::mutex> lck(mtx);
      cv.wait(lck, []() -> bool { return wnd2created; });
    }

    glfwMakeContextCurrent(wnd);

    // [...]
}

相关问题