用纹理绘制多个对象

时间:2012-10-02 07:14:52

标签: opengl-es-2.0

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

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

侧面覆盖正面。此过程如图所示: enter image description here

备用图片(带颜色和干净图片): enter image description here

右立方体的侧面与中心立方体的正面重叠。 如何在没有它的情况下移除此效果并显示多个立方体?

1 个答案:

答案 0 :(得分:2)

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

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

  1. 使用glEnable(GL_DEPTH_TEST)
  2. 在初始化时启用深度测试
  3. 通过将其位添加到glClear调用,清除每个帧上的深度缓冲区:     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  4. 在此之后,你不应再看到你的表面突然出现在更近的表面上。

相关问题