c++ opengl 4.5 不显示对象

c++ opengl 4.5 doesn't show the object

我编写的代码必须显示三角形,但它没有。我真的不知道问题出在哪里。我检查了所有内容,但没有找出问题所在。如果可以,请帮助我。

代码如下:

#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm.hpp>

int width = 800, height = 600;

int main() {

    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(width, height, "engine", NULL, NULL);
    glfwMakeContextCurrent(window);

    gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);

    glViewport(0, 0, width, height);

    const char* VertexShaderData = "#version 450 core\n"
        "layout(location = 0) in vec2 pos;\n"
        "void main(){\n"
        "gl_Position = vec4(pos, 0, 1);\n"
        "}[=10=]";

    GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(VertexShader, 1, &VertexShaderData, NULL);
    glCompileShader(VertexShader);

    const char* FragmentShaderData = "#version 450 core\n"
        "out vec4 Color;\n"
        "void main(){\n"
        "Color = vec4(0.25, 0.8, 0.65, 1);\n"
        "}[=10=]";

    GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(FragmentShader, 1, &FragmentShaderData, NULL);
    glCompileShader(FragmentShader);

    GLuint ShaderProgram = glCreateProgram();
    glAttachShader(ShaderProgram, VertexShader);
    glAttachShader(ShaderProgram, FragmentShader);
    glLinkProgram(ShaderProgram);

    float Points[] = { -1, -1, 0, 1, 1, -1 };
    
    GLuint VAO, VBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0);
    glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW);

    glClearColor(0.3, 0.5, 0.7, 1);

    while (!glfwWindowShouldClose(window)) {
        glfwSwapBuffers(window);

        glClear(GL_COLOR_BUFFER_BIT);

        glBindVertexArray(VAO);
        glEnableVertexAttribArray(0);
        glUseProgram(ShaderProgram);

        glDrawArrays(GL_TRIANGLES, 0, 3);
    }
}

以前我相信数组有什么问题,但现在我不这么认为了。问题一定出在别的地方。

glBufferData 的第二个参数是以字节为单位的缓冲区大小:

glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW);

glBufferData(GL_ARRAY_BUFFER, 6*sizeof(float), Points, GL_STATIC_DRAW);