【发布时间】:2014-04-12 05:43:39
【问题描述】:
我正在尝试在 OpenGL 3.2 中绘制一个简单的四边形,但是当我调用“glDrawElements”时,应用程序会因“访问冲突读取位置 0x00000000”而崩溃。
我认为问题是顶点缓冲区数据错误,但我不确定如何解决/调试它(OpenGL 跟踪会很棒,但我也不知道如何启用它......)
初始化代码:
std::vector<CUShort> Indices;
const CUShort IndicesArray[] = { 0, 1, 2, 2, 0, 3 };
for(size_t j = 0; j < 1; j++) {
for(size_t i = 0; i < sizeof(IndicesArray) / sizeof(*IndicesArray); i++) {
Indices.push_back(4 * j + IndicesArray[i]);
}
}
glGenBuffers(1, &m_Elements);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Elements);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, Indices.size() * sizeof(CUShort), &Indices[0], GL_STATIC_DRAW);
glGenVertexArrays(1, &m_Array);
glBindVertexArray(m_Array);
glGenBuffers(1, &m_Buffer);
glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(TexColorVertex), NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_TRUE, sizeof(TexColorVertex), (const GLvoid*)offsetof(TexColorVertex, Color));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TexColorVertex), (const GLvoid*)offsetof(TexColorVertex, Position));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(TexColorVertex), (const GLvoid*)offsetof(TexColorVertex, Texcoord));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
绘图代码:
glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
TexColorVertex Vertices[4];
glm::vec4 SpritePos = glm::vec4(0, 0, 1024.0f, 384.0f);
Vertices[0].Position = glm::vec2(SpritePos.x, SpritePos.y);
Vertices[1].Position = glm::vec2(SpritePos.x, SpritePos.w);
Vertices[2].Position = glm::vec2(SpritePos.z, SpritePos.w);
Vertices[3].Position = glm::vec2(SpritePos.z, SpritePos.y);
Color Kittens = Color::HotPink();
Vertices[0].Color = glm::vec4(Kittens.R(), Kittens.G(), Kittens.B(), 1.0f);
Vertices[1].Color = glm::vec4(Kittens.R(), Kittens.G(), Kittens.B(), 1.0f);
Vertices[2].Color = glm::vec4(Kittens.R(), Kittens.G(), Kittens.B(), 1.0f);
Vertices[3].Color = glm::vec4(Kittens.R(), Kittens.G(), Kittens.B(), 1.0f);
Vertices[0].Texcoord = glm::vec2(0.0f, 0.0f);
Vertices[1].Texcoord = glm::vec2(0.0f, 1.0f);
Vertices[2].Texcoord = glm::vec2(1.0f, 1.0f);
Vertices[3].Texcoord = glm::vec2(1.0f, 0.0f);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(Vertices), sizeof(Vertices), Vertices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Elements);
glBindVertexArray(m_Array);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (const GLvoid*)0);
顶点结构体声明如下:
struct TexColorVertex
{
TexColorVertex(void) { }
TexColorVertex(glm::vec2 const& Position, glm::vec2 const& Texcoord) :
Position(Position), Texcoord(Texcoord)
{ }
glm::vec2 Position;
glm::vec2 Texcoord;
glm::vec4 Color;
};
有没有人对如何解决这个问题并绘制一个占据一半屏幕的简单四边形有任何建议?
【问题讨论】:
-
您将
NULL作为索引数组发送到glDrawElements -
@JesusRamos 我相信这是一个偏移量。 Opengl 从当前绑定的元素数组缓冲区中获取索引数据。
-
@Ben 这是绑定到顶点数组的偏移量数组。在这种情况下,它应该是一个包含 6 个索引的数组。
标签: c++ opengl opengl-3 glm-math