以下代码应该在具有 OpenGL 兼容性配置文件的窗口上显示一个红色三角形,但我只能看到一个空白的窗口核心配置文件:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
unsigned int shader_create(const char* src_vertex, const char* src_fragment) {
...
}
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit()) return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK) return -1;
float coordinates[6] = {
-0.5f, -0.5f,
+0.0f, +0.5f,
+0.5f, -0.5f
};
unsigned int buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(coordinates), coordinates, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
const char* vertex_shader = ... ;
const char* fragment_shader = ... ;
unsigned int shader = shader_create(vertex_shader, fragment_shader);
glUseProgram(shader);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
顶点着色器:
#version 330 core
layout(location = 0) in vec4 position;
void main() {
gl_Position = position;
}
片段着色器:
#version 330 core
layout(location = 0) out vec4 color;
void main() {
color = vec4(1.0, 0.0, 0.0, 1.0);
}
当我不使用着色器时(这不是一个好主意),我可以完美地看到默认白色的三角形(至少在我的 GPU 上)。此外,如果使用兼容性配置文件而不是核心配置文件,它也可以工作。
我尝试编译为 C 和 C++ 代码,但都未能显示三角形。
我在这里做错了什么?着色器源代码是否错误?
最佳答案
当您使用核心配置文件时OpenGL Context ,您必须生成并命名为 Vertex Array Object ,因为默认的顶点数组对象 (0) 无效。
切换到兼容性配置文件:
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
或者为顶点规范创建一个命名的VAO:
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
关于c++ - 为什么我在带有 OpenGL 核心配置文件的窗口上看不到红色三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63561910/