【发布时间】:2019-07-17 10:41:27
【问题描述】:
简而言之,我在 C++ 中创建了一个函数,用于基于顶点向量为我创建一个顶点缓冲区数组和一个索引缓冲区数组,即如果您在顶点向量中输入 4 个点,该函数理论上应该返回 2 个数组用于顶点缓冲区和索引缓冲区。然而,这就是问题出现的地方。在函数返回数组、初始化缓冲区并调用 glDrawElements 之后,仅绘制构成正方形的 2 个(对于正方形)三角形中的一个。我很困惑为什么。
这是代码,
结构定义函数返回的东西:
struct ResultDataBuffer {
std::vector<float> positions;
std::vector<unsigned int> indices;
unsigned int psize;
unsigned int isize;
unsigned int bpsize;
unsigned int bisize;
};
//positions and indices are the vectors for the buffers (to be converted to arrays)
//psize and isize are the sizes of the vectors
//bpsize and bisize are the byte size of the vectors (i.e. sizeof())
函数本身:
static ResultDataBuffer CalculateBuffers(std::vector<float> vertixes) {
std::vector<float> positions = vertixes;
std::vector<unsigned int> indices;
int length = vertixes.size();
int l = length / 2;
int i = 0;
while (i < l - 2) { //The logic for the index buffer array. If the length of the vertexes is l, this array(vector here) should be 0,1,2 , 0,2,3 ... 0,l-2,l-1
i += 1;
indices.push_back(0);
indices.push_back(i + 1);
indices.push_back(i + 2);
}
return{ vertixes,indices, positions.size(), indices.size(), sizeof(float)*positions.size(), sizeof(unsigned int)*indices.size() };
}
主函数中的代码(缓冲区和东西的定义):
std::vector<float> vertixes = {
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f,
};
ResultDataBuffer rdb = CalculateBuffers(vertixes);
float* positions = rdb.positions.data(); //Convert vector into array
unsigned int* indices = rdb.indices.data(); //Ditto above
unsigned int buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, rdb.bpsize, positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
unsigned int ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, rdb.bisize, indices, GL_STATIC_DRAW);
主函数中的东西(在游戏循环中):
glDrawElements(GL_TRIANGLES, rdb.isize, GL_UNSIGNED_INT, nullptr);
抱歉这篇文章太长了,我试着删减它。
C++ 完整代码:https://pastebin.com/ZGLSQm3b
着色器代码(位于/res/shaders/Basic.shader):https://pastebin.com/C1ahVUD9
总而言之,这段代码不是绘制一个正方形 - 2 个三角形,而是只绘制一个三角形。
【问题讨论】: