使用OpenGLES2在3D场景上绘制2D文本?



我试图在3D场景上渲染2D文本。2D文本是使用TTF字体的freetype加载的,并使用正交投影来渲染,场景使用我的相机使用透视投影。我已经修改了代码从这个学习OpenGL教程文本渲染。我可以单独渲染文本和3D场景,但是2D文本在一起绘制时不会出现。

我的渲染函数:
void Engine::render()
{
std::string fpsStr = std::to_string(fps).substr(0, std::to_string(fps).find(".") + 3);
glViewport(0, 0, surface_width, surface_height);
glClearColor(0.53f, 0.8f, 0.92f, 1.0f);
glEnable(GL_DEPTH_TEST);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 3D scene gets rendered here
scene->render(display, surface, deltaTime);
//
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Text gets rendered here
debugText.renderText(fpsStr,25.0f, 25.0f, 1.0f, glm::vec3(0.0, 0.0, 0.0));
//
glDisable(GL_BLEND);
eglSwapBuffers(display, surface);
}

文本投影是一个成员变量(glm::mat4),在创建文本呈现类时初始化,如下所示:

...
projection = glm::ortho(0.0f, static_cast<float>(screenWidth), 0.0f, static_cast<float>(screenHeight));
...

我的渲染文本函数:

void Font::renderText(std::string text, float x, float y, float scale, glm::vec3 colour)
{
// activate corresponding render state
textShader.use();
textShader.setMat4("projection", projection);
textShader.setVec3("textColor", colour);
glActiveTexture(GL_TEXTURE0);
// iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character ch = characters[*c];
float xpos = x + ch.bearing.x * scale;
float ypos = y - (ch.size.y - ch.bearing.y) * scale;
float w = ch.size.x * scale;
float h = ch.size.y * scale;
// update VBO for each character
float vertices[6][4] = {
{ xpos,     ypos + h,   0.0f, 0.0f },
{ xpos,     ypos,       0.0f, 1.0f },
{ xpos + w, ypos,       1.0f, 1.0f },
{ xpos,     ypos + h,   0.0f, 0.0f },
{ xpos + w, ypos,       1.0f, 1.0f },
{ xpos + w, ypos + h,   1.0f, 0.0f }
};
// render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, ch.textureID);
// update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
// now advance cursors for next glyph (note that advance is number of 1/64 pixels)
x += (ch.advance >> 6) * scale; // bitshift by 6 to get value in pixels (2^6 = 64)
}
glBindTexture(GL_TEXTURE_2D, 0);
}

这里有两张图片,在这一张中我只渲染文本,在这一张中我同时启用了3D场景和文本,但是只有3D场景被显示。

我如何将这个2D视角覆盖在3D场景上,使它们都被渲染?

您说过分别渲染它们(2D四边形和3D场景)可以正常工作,但将它们一起渲染会导致2D四边形无法渲染。嗯,试着检查对象的渲染顺序;确保你正确地绑定和解绑定了着色器。是否有一个特殊的原因,你已经禁用了深度测试的文本(尝试启用它,看看是否解决问题)?

最新更新