2009-09-26 55 views
0

我有以下代碼,但找不到該錯誤。這似乎是一個與記憶有關的問題。原始代碼取自OpenGL超級自動化附帶的3d庫,並且我正在嘗試使其適用於openGL es。任何關於爲什麼它一直在進行分割的想法?所以你需要分配在OpenGL ES中繪製球體的幫助

sizeof(GLfloat) * iStacks * (iSlices + 1) * 3 * 2 

字節vertexPointer

- (void)drawSphereOfRadius:(GLfloat)fRadius nbSlices:(GLint)iSlices nbStacks:(GLint)iStacks 
{ 
GLfloat *vertexPointer = malloc(sizeof(GLfloat) * iStacks * iSlices * 3 * 2); 

GLfloat drho = (GLfloat)(3.141592653589)/(GLfloat) iStacks; 
GLfloat dtheta = 2.0f * (GLfloat)(3.141592653589)/(GLfloat) iSlices; 
GLfloat ds = 1.0f/(GLfloat) iSlices; 
GLfloat dt = 1.0f/(GLfloat) iStacks; 
GLfloat t = 1.0f; 
GLfloat s = 0.0f; 
GLint i, j;  // Looping variables 


int idx = 0; 
for (i = 0; i < iStacks; i++) 
{ 
    GLfloat rho = (GLfloat)i * drho; 
    GLfloat srho = (GLfloat)(sin(rho)); 
    GLfloat crho = (GLfloat)(cos(rho)); 
    GLfloat srhodrho = (GLfloat)(sin(rho + drho)); 
    GLfloat crhodrho = (GLfloat)(cos(rho + drho)); 


    s = 0.0f; 

    for (j = 0; j <= iSlices; j++) 
    { 
    GLfloat theta = (j == iSlices) ? 0.0f : j * dtheta; 
    GLfloat stheta = (GLfloat)(-sin(theta)); 
    GLfloat ctheta = (GLfloat)(cos(theta)); 

    GLfloat x = stheta * srho; 
    GLfloat y = ctheta * srho; 
    GLfloat z = crho; 


    glNormal3f(x, y, z); 

    vertexPointer[idx] = x * fRadius; 
    vertexPointer[idx + 1] = y * fRadius; 
    vertexPointer[idx + 2] = z * fRadius; 

    x = stheta * srhodrho; 
    y = ctheta * srhodrho; 
    z = crhodrho; 

    s += ds; 
    glNormal3f(x, y, z); 
    vertexPointer[idx + 3] = x * fRadius; 
    vertexPointer[idx + 4] = y * fRadius; 
    vertexPointer[idx + 5] = z * fRadius; 
    idx += 6; 

    } 


    t -= dt; 
} 


glVertexPointer(3, GL_FLOAT, 0, vertexPointer); 
glEnableClientState(GL_VERTEX_ARRAY); 

glDrawArrays(GL_TRIANGLE_STRIP, 0, iStacks * iSlices * 2); 

free(vertexPointer); 
//glPopMatrix(); 
} 

回答

2

j循環做iSlices + 1迭代。

+0

那麼它停止了segfaulting,但它仍然畫錯了。我會努力的。 – 2009-09-27 15:43:00

+0

對於開始您對'glNormal3f'的調用,請不斷更改當前的正常值,但您不會等到'glDrawArrays'命令。它將使用您爲所有頂點設置的最後一個正常值。至於你似乎試圖生成三角形條的頂點,但這不是你設置頂點緩衝區的方式。與其試圖解決這個問題,您可能想要爲三角形條生成一個索引緩衝區,以節省重複前一個堆棧迭代中的所有頂點,即創建一個只保存一次頂點的頂點緩衝區。索引緩衝區是指向該頂點緩衝區的索引數組。 – Troubadour 2009-09-27 20:40:05

+0

對不起,最後一條評論應該顯示爲「...但是,直到'glDrawArrays'命令不會_drawing_」。 – Troubadour 2009-09-27 21:47:02