c++ - 尝试在 C++ 中使用 glDrawArrays 时出错

标签 c++ opengl sdl glew

我试图在我的游戏中绘制一个简单的矩形,但我一直遇到以下中断: enter image description here

这是我的 Sprite.cpp 中的代码,我在其中绑定(bind)和渲染内容。

void Sprite::init(float x, float y, float width, float height){

this->x = x;
this->y = y;
this->width = width;
this->height = height;


if(vbo == 0)
    glGenBuffers(1, &vbo);

Vertex vertex[6];

vertex[0].setPosition(x, y);
vertex[0].setUV(0, 0);

vertex[1].setPosition(x, y + height);
vertex[1].setUV(0, 1);

vertex[2].setPosition(x + width, y + height);
vertex[2].setUV(1, 1);


vertex[3].setPosition(x, y);
vertex[3].setUV(0, 0);

vertex[4].setPosition(x + width, y);
vertex[4].setUV(1, 0);

vertex[5].setPosition(x + width, y + height);
vertex[5].setUV(1, 1);

for (int i = 0; i < 6; i++)
    vertex[i].setColor(0.0, 0.0, 1.0, 1.0);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(vbo, sizeof(vertex), vertex, GL_DYNAMIC_DRAW);


glBindBuffer(GL_ARRAY_BUFFER, 0);

}



void Sprite::render(){

glBindBuffer(GL_ARRAY_BUFFER, vbo);

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, color));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, uv));

glDrawArrays(GL_TRIANGLES, 0, 6);

glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

glBindBuffer(GL_ARRAY_BUFFER, 0);

}

如果我注释掉“glDrawArrays(GL_TRIANGLES, 0, 6)”这一行,那么程序将运行得非常好。这是我的 Vertex 结构,仅供引用:

#pragma once
#include <GL\glew.h>



struct Position {

float x, y;

};


struct UV{

float u, v;

};

struct Color {

GLubyte r, g, b, a;
};



struct Vertex {


Position position;

Color color;

UV uv;


void setUV(float u, float v) {
    uv.u = u;
    uv.v = v;
}

void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a) {
    color.r = r;
    color.g = g;
    color.b = b;
    color.a = a;
}

void setPosition(float x, float y) {
    position.x = x;
    position.y = y;
}
};

我真的不知道为什么会这样。我听说这个错误与取消引用某些空指针或其他东西有关。我只是不知道如何解决这个问题。非常感谢任何帮助。

最佳答案

这个:glBufferData(vbo, sizeof(vertex), vertex, GL_DYNAMIC_DRAW);

应该是:glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), vertex, GL_STATIC_DRAW);

因为第一个参数指定了数组的使用方式。

关于c++ - 尝试在 C++ 中使用 glDrawArrays 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40374891/

相关文章:

c++ - 如何将 cv::Mat & Img 复制到 unsigned char* img?opencv

c++ - 将数组发送到 R 函数 (C++)

c++ - OpenEXR + OpenGL 未处理的异常

c++ - 需要使用 glGetProgramiv 函数进行说明

c++ - 定时器的使用

c++ - 在模板类上 boost property_tree : multiple values per key,

c++ - 限制 Light 类实例化

c++ - SDL - TTF - 字体未加载

c++ - 来自命令行的 gnu 编译器

c++ - 如何将 uint8_t(SDL 中的 Uint8)转换为字符串?