gpt4 book ai didi

c++ - 在现代OpenGL中画一条线

转载 作者:行者123 更新时间:2023-12-02 10:05:26 25 4
gpt4 key购买 nike

我只想在屏幕上画一条线。我正在使用OpenGl 4.6。我发现的所有教程都使用了glVertexPointer,据我所知,它已被弃用。

我知道如何使用缓冲区绘制三角形,所以我尝试了一条线。它没有用,只是显示黑屏。 (我正在使用GLFW和GLEW,并且正在使用已经在三角形上测试过的顶点+片段着色器)

    // Make line
float line[] = {
0.0, 0.0,
1.0, 1.0
};

unsigned int buffer; // The ID, kind of a pointer for VRAM
glGenBuffers(1, &buffer); // Allocate memory for the triangle
glBindBuffer(GL_ARRAY_BUFFER, buffer); // Set the buffer as the active array
glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(float), line, GL_STATIC_DRAW); // Fill the buffer with data
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0); // Specify how the buffer is converted to vertices
glEnableVertexAttribArray(0); // Enable the vertex array

// Loop until the user closes the window
while (!glfwWindowShouldClose(window))
{
// Clear previous
glClear(GL_COLOR_BUFFER_BIT);

// Draw the line
glDrawArrays(GL_LINES, 0, 2);

// Swap front and back buffers
glfwSwapBuffers(window);

// Poll for and process events
glfwPollEvents();
}

我是朝着正确的方向前进,还是目前的最佳做法完全不同?
如果是,该如何解决我的代码?

最佳答案

问题是对 glBufferData 的调用。第二个参数是缓冲区的大小(以字节为单位)。由于顶点数组由2个坐标和2个分量组成,因此缓冲区的大小为4 * sizeof(float)而不是2 * sizeof(float):
glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(float), line, GL_STATIC_DRAW);

glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(float), line, GL_STATIC_DRAW);

但是请注意,它仍然不是“现代” OpenGL。如果要使用核心配置文件 OpenGL Context,则必须使用 Shader程序和 Vertex Array Object

关于c++ - 在现代OpenGL中画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60440682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com