views:

1103

answers:

1

I have the following code, but I can't find the bug. It seems to be a memory-related issue. The original code is taken from the 3d library which comes with the OpenGL superbible, and i'm trying to adapt it for openGL es. Any ideas as to why it's segfaulting all the time?

- (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  A: 

Your j loop is doing iSlices + 1 iterations so you need to allocate

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

bytes for vertexPointer.

Troubadour
Well it stopped segfaulting, but it still draws wrong. I'll work on it.
Andrei Tanasescu
Well for a start your calls to `glNormal3f` keep changing the current normal but you're not until the `glDrawArrays` command. It will use the last normal you set for all vertices. As for the vertices you seem to be trying to generate a triangle strip but that's not how you've set up your vertex buffer. Rather than try to fix that you might want to generate an index buffer for your triangle strip to save repeating all the vertices from the previous stack iteration i.e. create a vertex buffer that holds each vertex just once. The index buffer is an array of indices into that vertex buffer.
Troubadour
Sorry, that last comment should read "...but you're not _drawing_ until the `glDrawArrays` command."
Troubadour