1

我想使用纹理绘制立方体。

void OperateWithMainMatrix(ESContext* esContext, GLfloat offsetX, GLfloat offsetY, GLfloat offsetZ) {

UserData *userData = (UserData*) esContext->userData;
ESMatrix modelview;
ESMatrix perspective;
    //Manipulation with matrix 
    ...
    glVertexAttribPointer(userData->positionLoc, 3, GL_FLOAT, GL_FALSE, 0, cubeFaces);
    //in cubeFaces coordinates verticles cube
    glVertexAttribPointer(userData->normalLoc, 3, GL_FLOAT, GL_FALSE, 0, cubeFaces);
    //for normals (use in fragment shaider for textures)

    glEnableVertexAttribArray(userData->positionLoc);
    glEnableVertexAttribArray(userData->normalLoc);

    // Load the MVP matrix
    glUniformMatrix4fv(userData->mvpLoc, 1, GL_FALSE, 
                       (GLfloat*)&userData->mvpMatrix.m[0][0]);

    //Bind base map
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, userData->baseMapTexId);

    //Set the base map sampler to texture unit to 0
    glUniform1i(userData->baseMapLoc, 0);

   // Draw the cube
    glDrawArrays(GL_TRIANGLES, 0, 36);
   }

(坐标变换在 OperateWithMainMatrix() 中)然后调用 Draw() 函数:

void Draw(ESContext *esContext)
{
   UserData *userData = esContext->userData;
   // Set the viewport
   glViewport(0, 0, esContext->width, esContext->height);

   // Clear the color buffer
   glClear(GL_COLOR_BUFFER_BIT);

   // Use the program object
   glUseProgram(userData->programObject);

  OperateWithMainMatrix(esContext, 0.0f, 0.0f, 0.0f);

  eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}

这工作正常,但如果我尝试绘制多个立方体(例如下一个代码):

void Draw(ESContext *esContext)
{ ...

    // Use the program object
    glUseProgram(userData->programObject);

    OperateWithMainMatrix(esContext, 2.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, 1.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, 0.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, -1.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, -2.0f, 0.0f, 0.0f);
    eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}

侧面与正面重叠。此过程如图所示: 在此处输入图像描述

备用图片(带有颜色和干净的图像): 在此处输入图像描述

右侧立方体的侧面与中央立方体的正面重叠。如果没有它,我怎样才能消除这种效果并显示多个立方体?

4

1 回答 1

2

要解决此问题,您需要利用所谓的深度缓冲区。这是确保表面不会被绘制在更近的表面之上的原因(例如立方体的侧面显示在立方体的前面)。

幸运的是,这样做并不需要太多工作:

  1. 在初始化时启用深度测试glEnable(GL_DEPTH_TEST)
  2. 通过将其位添加到 glClear 调用来清除每帧上的深度缓冲区: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

在此之后,您应该不再看到您的表面在更近的表面上弹出。

于 2012-10-02T15:51:40.643 回答