简而言之,我在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个三角形,而是仅绘制一个三角形。
答案 0 :(得分:1)
此问题是由生成索引数组的循环引起的:
while (i < l - 2) { i += 1; indices.push_back(0); indices.push_back(i + 1); indices.push_back(i + 2); }
此循环生成索引
0,2,3,0,3,4
但是您必须生成索引
0,1,2,0,2,3
这是因为在将索引附加到向量之前,控制变量已增加。
在循环结束时增加控制变量,以解决该问题:
while (i < l - 2) {
indices.push_back(0);
indices.push_back(i + 1);
indices.push_back(i + 2);
i += 1;
}
或使用for
循环:
for (unsigned int i = 0; i < l-2; ++ i)
{
unsigned int t[]{ 0, i+1, i+2 };
indices.insert(indices.end(), t, t+3);
}