C++ OpenGL 中,绘制形状返回错误

C++ OpenGL, drawing shapes is returning an error

本文关键字:返回 错误 绘制 OpenGL C++      更新时间:2023-10-16

我正在尝试在我的应用程序上绘制形状。我已将#include <glad/glad.h>添加到我的代码中。

我在头文件中将顶点数组、顶点缓冲区和索引缓冲区设置为无符号整数。

在我的application.h文件中,我添加了以下内容:

unsigned int m_FCvertexArray; // Textured Phong VAO
unsigned int m_FCvertexBuffer;// Textured Phong VBO
unsigned int m_FCindexBuffer; // Index buffer for texture Phong cube

在我的应用程序中.cpp在我的构造函数中,我添加了以下内容:

Application::Application()
{
//------------- OPENGL VALUES -----------//
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Enabling backface culling to ensure triangle vertices are correct ordered (CCW)
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
////--------DRAW VERTICES---------//
float FCvertices[3 * 3] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f,  0.5f, 0.0f
};
glGenVertexArrays(1, &m_FCvertexArray);
glBindVertexArray(m_FCvertexArray);
glCreateBuffers(1, &m_FCvertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_FCvertexBuffer);
//
//
glBufferData(GL_ARRAY_BUFFER, sizeof(FCvertices), FCvertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(sizeof(float) * 3));

////--------DRAW INDICES---------//
glCreateBuffers(1, &m_FCindexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_FCindexBuffer);
unsigned int indices[3] = {0, 1, 2};
glBufferData(GL_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
}

在我的void Application::run()中,我补充说:

glUseProgram(m_FCprogram);
glBindVertexArray(m_FCvertexArray);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr);

现在的问题是当我运行代码时,它给了我标题上提到的错误:

在沙盒.exe中0x000000005D78F420 (nvoglv64.dll( 引发异常: 0xC0000005:访问冲突读取位置0x0000000000000000。

我一直在尝试解决此问题的方法,但似乎不起作用。 如果我注释掉 glDrawElements,代码会运行并工作,但没有绘制任何形状(很明显(。

创建索引缓冲区时,需要使用 GL_ELEMENT_ARRAY_BUFFER 而不是GL_ARRAY_BUFFER。