用c+opengl写出能在窗口中画出所有直线的完整代码
时间: 2024-09-28 20:04:01 浏览: 70
使用C++和OpenGL绘制窗口中的所有直线需要一些基本步骤。首先,确保已经包含了必要的头文件并设置了GLFW库用于创建窗口。下面是一个简单的示例,展示了如何在一个窗口中创建并显示线条:
```cpp
#include <GLFW/glfw3.h>
#include <iostream>
// 创建一个顶点结构体来存储线段的起点和终点
struct Vertex {
float x, y;
};
// 线段着色器源代码片段
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n"
"void main() {\n"
" gl_Position = vec4(aPos, 0.0, 1.0);\n"
"}\n";
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main() {\n"
"FragColor = vec4(0.0, 0.0, 0.0, 1.0); // 黑色线条,默认颜色\n"
"}\n";
int main() {
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
// 初始化窗口
GLFWwindow* window = glfwCreateWindow(640, 480, "Line Drawing", NULL, NULL);
if (!window) {
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// 设置着色器
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
if (!glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success)) {
std::cerr << "Vertex shader compilation failed: " << glGetShaderInfoLog(vertexShader) << std::endl;
glDeleteShader(vertexShader);
return -1;
}
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
if (!glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success)) {
std::cerr << "Fragment shader compilation failed: " << glGetShaderInfoLog(fragmentShader) << std::endl;
glDeleteShader(fragmentShader);
return -1;
}
int program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
if (!glGetProgramiv(program, GL_LINK_STATUS, &success)) {
std::cerr << "Program linking failed: " << glGetProgramInfoLog(program) << std::endl;
glDeleteProgram(program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return -1;
}
// 绘制函数
void drawLines(GLFWwindow* window, const std::vector<Vertex>& vertices) {
glUseProgram(program);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), vertices.data());
glDrawArrays(GL_LINES, 0, vertices.size()); // 绘制所有线条
glDisableVertexAttribArray(0);
glUseProgram(0);
}
// 主循环
while (!glfwWindowShouldClose(window)) {
// ... 清除屏幕、事件处理等 ...
// 创建一组随机直线的顶点数据
std::vector<Vertex> lines = { // 示例,替换为实际生成的直线
{0, 0}, {50, 50},
{100, 0}, {150, 100},
// 更多线条...
};
drawLines(window, lines);
// 刷新窗口
glfwSwapBuffers(window);
glfwPollEvents();
}
// 清理资源
glDeleteProgram(program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glfwTerminate();
return 0;
}
```
这个例子中,我们创建了一个简单的窗口,并通过设置着色器来渲染黑色的线条。`drawLines`函数接收一个顶点数组,代表了窗口中的一组线条。你需要根据需求动态生成或配置这些顶点。
注意:这只是一个基础框架,实际项目中你可能还需要处理错误检查、纹理映射、用户输入交互等功能。
阅读全文