algorithm - 帮助在 OpenGL ES 中绘制球体

标签 algorithm opengl-es

我有以下代码,但找不到错误。这似乎是一个与内存相关的问题。原始代码取自 OpenGL superbible 附带的 3d 库,我正在尝试将其改编为 openGL es。关于为什么它总是出现段错误有什么想法吗?

    - (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();
}

最佳答案

您的 j 循环正在执行 iSlices + 1 迭代,因此您需要分配

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

vertexPointer 的字节数。

关于algorithm - 帮助在 OpenGL ES 中绘制球体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482351/

相关文章:

algorithm - 如何构造二叉搜索树

algorithm - 贪心算法的正确性

android - 检测用户在 OpenGL 正方形上的触摸

ios - 调整 GLKView 的大小

java - Frustum near plane OpenGL 使对象看起来更近,而不仅仅是剪裁

algorithm - 如何创建具有常量行列总和的 1's and 0' 的对称矩阵

algorithm - 仅在平面一侧的两个轴对齐框之间的碰撞检测

python - 最小化组数,其中组元素的总和低于特定值

android - 为什么 List<Float>.toFloatArray 与填充 FloatArray 相比这么慢? (漏洞?)

ios - 为 GPUImage 创建耗时的制服