OpenGL 使用glad创建两个窗口
时间: 2024-06-11 22:10:50 浏览: 168
作为一个AI,我无法直接操作OpenGL,但我可以提供一些基本的代码帮助你创建两个窗口。以下是一个用glad创建两个窗口的示例:
```c++
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main()
{
// 初始化GLFW
glfwInit();
// 配置GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// 创建第一个窗口
GLFWwindow* window1 = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Window 1", NULL, NULL);
if (window1 == NULL)
{
std::cout << "Failed to create GLFW window1" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window1);
// 初始化GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// 设置视口大小
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
// 注册窗口大小改变的回调函数
glfwSetFramebufferSizeCallback(window1, framebuffer_size_callback);
// 创建第二个窗口
GLFWwindow* window2 = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Window 2", NULL, window1);
if (window2 == NULL)
{
std::cout << "Failed to create GLFW window2" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window2);
// 初始化GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// 设置视口大小
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
// 注册窗口大小改变的回调函数
glfwSetFramebufferSizeCallback(window2, framebuffer_size_callback);
// 循环渲染
while (!glfwWindowShouldClose(window1) && !glfwWindowShouldClose(window2))
{
// 处理输入
processInput(window1);
processInput(window2);
// 清除颜色缓冲区
glClear(GL_COLOR_BUFFER_BIT);
// 交换缓冲区
glfwSwapBuffers(window1);
glfwSwapBuffers(window2);
// 检查并调用事件
glfwPollEvents();
}
// 清理所有资源
glfwTerminate();
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
```
这个示例中创建了两个窗口,第一个窗口为主窗口,第二个窗口作为第一个窗口的子窗口。两个窗口的渲染和输入处理是分开的,但它们共享OpenGL上下文。在这个示例中,同时按下Esc键会关闭两个窗口。
阅读全文