geometry - 绘制球体 - 顶点顺序

标签 geometry opengl-es-2.0

我想在没有任何引擎的情况下在纯 OpenGL ES 2.0 中绘制球体。我写下一个代码:

 int GenerateSphere (int Slices, float radius, GLfloat **vertices, GLfloat **colors) {
 srand(time(NULL));
 int i=0, j = 0;
 int Parallels = Slices ;
 float tempColor = 0.0f;    
 int VerticesCount = ( Parallels + 1 ) * ( Slices + 1 );
 float angleStep = (2.0f * M_PI) / ((float) Slices);

 // Allocate memory for buffers
 if ( vertices != NULL ) {
    *vertices = malloc ( sizeof(GLfloat) * 3 * VerticesCount );
 }
 if ( colors != NULL) {
    *colors = malloc( sizeof(GLfloat) * 4 * VerticesCount);
 }

 for ( i = 0; i < Parallels+1; i++ ) {
     for ( j = 0; j < Slices+1 ; j++ ) {

         int vertex = ( i * (Slices + 1) + j ) * 3;

         (*vertices)[vertex + 0] = radius * sinf ( angleStep * (float)i ) *
                    sinf ( angleStep * (float)j );
         (*vertices)[vertex + 1] = radius * cosf ( angleStep * (float)i );
         (*vertices)[vertex + 2] = radius * sinf ( angleStep * (float)i ) *
                        cosf ( angleStep * (float)j );
         if ( colors ) {
                int colorIndex = ( i * (Slices + 1) + j ) * 4;
                tempColor = (float)(rand()%100)/100.0f;

                (*colors)[colorIndex + 0] =  0.0f;
                (*colors)[colorIndex + 1] =  0.0f;
                (*colors)[colorIndex + 2] =  0.0f;
                (*colors)[colorIndex + (rand()%4)] = tempColor;
                (*colors)[colorIndex + 3] =  1.0f;
            }
        }
    }
    return VerticesCount;
}

我正在使用下一个代码绘制它:

glDrawArrays(GL_TRIANGLE_STRIP, 0, userData->numVertices);

其中 userData->numVertices - 来自函数 GenerateSphere 的 VerticesCount。 但是在屏幕上绘制了系列三角形,这些不是球体近似值! 我想,我需要计算顶点并使用 OpenGL ES 2.0 函数 glDrawElements() (带数组,包含顶点数)。但是屏幕上绘制的一系列三角形不是球体近似值。 如何绘制球体近似值?如何指定顺序顶点(OpenGL ES 2.0 术语中的索引)?

最佳答案

在开始使用 OpenGL ES 之前,这里有一些建议:

Avoid bloating CPU/GPU performance

通过使用另一个程序离线渲染形状来消除密集的计算周期肯定会有所帮助。除了导出包含形状等的点 [x,y,z] 的结果集合之外,这些程序将提供有关形状/网格的更多详细信息。

我经历了所有这些痛苦,因为我一直在尝试搜索算法来渲染球体等,然后尝试优化它们。我只是想节省你以后的时间。只需使用 Blender,然后使用您最喜欢的编程语言来解析从 Blender 导出的 obj 文件,我使用 Perl。以下是渲染球体的步骤:(使用 glDrawElements 因为 obj 文件包含索引数组)

1) Download and install Blender.

image-1

2) From the menu, add sphere and then reduce the number of rings and segments.

image-2

3) Select the entire shape and triangulate it.

image-3

4) Export an obj file and parse it for the meshes.

image-4

您应该能够从这个文件中掌握渲染球体的逻辑:http://pastebin.com/4esQdVPP .它适用于 Android,但概念相同。 希望这会有所帮助。

关于geometry - 绘制球体 - 顶点顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14359425/

相关文章:

javascript - 如何水平分布不同大小的矩形?

glsl - WebGL 渲染缓冲区从着色器接收倾斜的像素值

android - 从 NDK 中获取 SurfaceTexture 的 GL 上下文

opengl-es - OpenGL ES 2.0 中的多 channel 着色器

algorithm - 从等正方形构造的几何体中提取轮廓(周长)多边形

3d - Prims vs Polys : what are the pros and cons of each?

javascript - 如何从矩形点计算旋转 Angular ?

WPF圆形进度条

ios - 在 iOS 上处理大量像素

ios - glGetAttribLocation 与 glBindAttribLocation