2012-08-15 81 views
0

基本上我想要做的是以編程方式生成我的頂點座標,而不是將其存儲在靜態預定義的數組中。不幸的是,我無法將一個非常簡單的示例轉換爲動態數組。以編程方式在iOS中生成OpenGL頂點數據

一切工作正常,如果我堅持靜態數組:

typedef struct { 
    GLfloat Position[3]; 
    GLfloat Color[4]; 
    GLfloat TexCoord[2]; 
    float Normal[3]; 
} Vertex; 


Vertex sphereVertices[] = { 
    {{1, -1, 1}, {1, 0, 0, 1}, {1, 0}, {0, 0, 1}}, 
    {{1, 1, 1}, {0, 1, 0, 1}, {1, 1}, {0, 0, 1}}, 
    {{-1, 1, 1}, {0, 0, 1, 1}, {0, 1}, {0, 0, 1}}, 
    {{-1, -1, 1}, {0, 0, 0, 1}, {0, 0}, {0, 0, 1}} 
}; 

GLubyte sphereIndices [] = { 
    0, 1, 2, 
    2, 3, 0 
}; 

...

glGenBuffers(1, &sphereIndexBuffer); 
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndexBuffer); 
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphereIndices), sphereIndices, GL_STATIC_DRAW); 

glEnableVertexAttribArray(GLKVertexAttribPosition); 
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, Position)); 

...

glDrawElements(GL_TRIANGLES, 6 * sizeof(GLubyte), GL_UNSIGNED_BYTE, 0); 

只要將我的指數爲動態數組只顯示第一個三角形。

GLubyte *sphereIndices; 

+(void)initialize { 
    sphereIndices = malloc(6 * sizeof(GLubyte)); 
    sphereIndices[0] = 0; 
    sphereIndices[1] = 1; 
    sphereIndices[2] = 2; 
    sphereIndices[3] = 2; 
    sphereIndices[4] = 3; 
    sphereIndices[5] = 0; 
} 

也許這與指針有關。有人知道我做錯了什麼嗎?

謝謝!

回答

4

我自己能夠解決問題。正如我所預料的那樣,這個問題與我對指針缺少的理解有關。

據我發現,沒有辦法獲得動態數組的大小。因爲sizeof(sphereIndices)總是返回4,這是指針的大小而不是數據的大小。這就是爲什麼glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphereIndices), sphereIndices, GL_STATIC_DRAW)只發送4個指數OpenGL的,而不是6

我通過引入額外的變量來跟蹤指數的數的解決了這一問題。