プログラムでウィンドウを作成するために OpenGL と SDL を使用しています。
OpenGL ウィンドウで SDL_ttf を使用するにはどうすればよいですか?
たとえば、フォントを読み込んでテキストをレンダリングしたいとします。SDL OpenGL サーフェスを使用してテキストを描画したいと考えています。
方法は次のとおりです。
SDL_SetVideoMode()
。SDL_OPENGL
必ず旗を渡してください。glViewport()
などglMatrixMode()
)。たとえば、SDL_ttfを使用してテキストをレンダリングしますTTF_RenderUTF8_Blended()
。surface->pixels
レンダリング関数はSDL_surfaceを返します。これは、データへのポインタ( )をOpenGLに渡し、データの形式を指定して、OpenGLテクスチャに変換する必要があります。このような:
colors = surface->format->BytesPerPixel;
if (colors == 4) { // alpha
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGBA;
else
texture_format = GL_BGRA;
} else { // no alpha
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGB;
else
texture_format = GL_BGR;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, colors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels);
次に、etcを使用してOpenGLのテクスチャを使用できます。描画が終了したら、glBindTexture()
必ず呼び出してください。SDL_GL_SwapBuffers()
以下に基づいています: http://content.gpwiki.org/index.php/SDL_ttf:Tutorials:Fonts_in_OpenGL
以下のコードは、作成した完成した 3D モデルの上にテキストをレンダリングする方法の例です。
#include "SDL.h"
#include "SDL_ttf.h"
/.../
void RenderText(std::string message, SDL_Color color, int x, int y, int size) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, m_Width, 0, m_Height); // m_Width and m_Height is the resolution of window
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
TTF_Font * font = TTF_OpenFont("pathToFont.ttf", size);
SDL_Surface * sFont = TTF_RenderText_Blended(font, message, color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sFont->w, sFont->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, sFont->pixels);
glBegin(GL_QUADS);
{
glTexCoord2f(0,0); glVertex2f(x, y);
glTexCoord2f(1,0); glVertex2f(x + sFont->w, y);
glTexCoord2f(1,1); glVertex2f(x + sFont->w, y + sFont->h);
glTexCoord2f(0,1); glVertex2f(x, y + sFont->h);
}
glEnd();
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glDeleteTextures(1, &texture);
TTF_CloseFont(font);
SDL_FreeSurface(sFont);
}
/.../
int main() {
/.../ Render 3D stuff here
// Prints out "Hello World" at location (5,10) at font size 12!
SDL_Color color = {255, 0, 0, 0}; // Red
RenderText("Hello World", color, 5, 10, 12);
/.../
return 0;
}