OpenGL:无法渲染三角形

OpenGL: Cannot not render a triangle

编写代码并 运行 之后,没有任何效果。我设法填充了背景,但没有别的。

这是我的代码:

#include <iostream>
#include <glad\glad.h>
#include <GLFW\glfw3.h>

const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;

const char *vertexShaderSource = "#version 450 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
"   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}[=10=]";

const char *fragmentShaderSource = "#version 450 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
    "FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}[=10=]";

void framebuffer_size_callback(GLFWwindow* window, int width, int height);

int main()
{
    // Initializes GLFW and passes window hints 
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Creates GLFWwindow called window
    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "LearningOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Check if GLAD is initialized
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    float vertices[] = {
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
        0.0f,  0.5f, 0.0f
    };

    int success;
    char infoLog[512];


    // Creating Vertex Shader Object
    unsigned int vertexShader;
    vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    // Creating Fragment Shader Object
    unsigned int fragmentShader;
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }

    // Shader program
    unsigned int shaderProgram;
    shaderProgram = glCreateProgram();

    // Attatching both shaders to the program and then linking them
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    // Interpreting vertex data 
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    // Generating a Vertex Array Object
    unsigned int VAO;
    unsigned int VBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Size of rendering window 
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); 

    // While window is open
    while (!glfwWindowShouldClose(window))
    {
        // Finally
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glBindVertexArray(VAO);
        glUseProgram(shaderProgram);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    // If loop is exited, terminate all allocated resources and close the program
    glfwTerminate();
    return 0;
}

// Frame buffer function that resizes the viewport when the window gets resized
void framebuffer_size_callback(GLFWwindow * window, int width, int height)
{
    glViewport(0, 0, width, height);
}

在绑定 VAO 之前,请勿尝试启用或设置顶点属性指针。在核心上下文中不会做任何有用的事情。

绑定 VAO 然后 enable/set 属性:

unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

// Generating a Vertex Array Object
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray( VAO );

// Interpreting vertex data 
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);

我注意到您的代码存在一些错误或问题:第一个明显的错误是在您调用:

glfwMakeContextCurrent(window);

您应该打电话给:

glfwSetFramebufferSizeCallback( window, framebuffer_size_callback );

这应该在使 window 成为当前上下文之后和所有 OpenGL 内容之前完成。


我看到的第二个问题是在你的 VAOVBO 的设置中,在从你的着色器中读取信息后,你有一些东西的顺序不正确,你是甚至错过了代码这一部分的一两个电话:

// Interpreting vertex data 
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

// Generating a Vertex Array Object
unsigned int VAO;
unsigned int VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

// Size of rendering window 
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); 
  • 首先,您应该在调用 glVertexAttribPointer() & glEnableVertexAtrribArray() 之前创建并初始化 VBO & VAO。从 API - 图书馆的角度考虑这一点。如何启用指向内存中尚不存在的内容的指针?

  • 其次,您缺少对 glBindVertexArray(VAO); 的调用 这应该是在您生成 VAO & VBO.

    [=85 之后=]
  • 第三,最后两行代码我已经解释了函数glfwSetFramebufferSizeCallback()和它应该放在哪里;但对于这一部分,我将解释原因。这是设置视口的函数,因为它是一种回调类型的函数。在将 window 设置为当前上下文之后;这是您要告诉 OpenGL 视口或 window 大小的地方,以便它知道 Screen Size 用于将所有顶点数据转换为屏幕 space 坐标。通过修复此问题,您将不必独立调用 glViewport();因为这就是回调函数为您所做的。

这部分代码应该是这样的:

unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0); 

// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0); 

我看到的最后一件事是在用于渲染的 while 循环中以及在循环之后:

// While window is open
while (!glfwWindowShouldClose(window))
{
   // Finally
   glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
   glClear(GL_COLOR_BUFFER_BIT);
   glBindVertexArray(VAO);
   glUseProgram(shaderProgram);
   glDrawArrays(GL_TRIANGLES, 0, 3);

   glfwSwapBuffers(window);
   glfwPollEvents();
}
// If loop is exited, terminate all allocated resources and close the program
glfwTerminate();
return 0;

我在这里看到两个问题:

First, the order of using the program and binding the vertex arrays are backwards, they should be:

glUseProgram(shaderProgram);
glBindVertexArray(VAO);

Second after your while loop and before the glfwTerimate() call you should be deleting your vertex array and buffers

glDeleteVertexArrays( 1, &VAO );
glDeleteBuffers( 1, &VBO );

如果这些简单的更正不能解决您的问题,您可以尝试另一件事。您可以尝试将 OpenGL 的版本从 4.5 更改为 3.3,因为它们的 GLSL Shader 语言版本略有不同。

如果这不起作用,那么它可能与您如何设置您正在使用的外部库有关。


摘要

在尝试设置任何顶点数据之前,您首先必须设置视口。接下来,您必须先设置 VAO & VBO 信息,然后才能拨打 glVertexAtrribPointer() & glEnableVertexAttribArray(),别忘了拨打 glBindVertexArray(VAO) 在生成它们的调用之后。在所有初始化按正确顺序进行之后,当在渲染循环中使用它时,您应该在 glBindVertexArray 之前调用 glUseProgram。最后,在渲染循环之后,您应该进行适当的调用以删除顶点数组和缓冲区。如果这些都失败了,那么您可以尝试更改 OpenGl - GLSL 的版本并检查正在使用的所有外部库的设置。