Для рисования текста с помощью библиотеки stb_truetype.h вы можете использовать следующий подход:
- Включите заголовочный файл stb_truetype.h в свой код:
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_truetype.h"
#include <GL/glut.h>
#include <fstream>
- Загрузите шрифт в память программы. Ниже приведен пример функции, которая открывает файл шрифта и загружает его содержимое:
bool loadFont(const char* filename, unsigned char*& fontBuffer, int& fontSize) {
std::ifstream file(filename, std::ios::binary);
if (!file) {
printf("Error opening font file: %s\n", filename);
return false;
}
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
fontBuffer = new unsigned char[size];
if (!fontBuffer) {
printf("Error allocating memory for font.\n");
return false;
}
if (!file.read((char*)fontBuffer, size)) {
printf("Error reading font file.\n");
return false;
}
fontSize = size;
return true;
}
- Используйте функции библиотеки stb_truetype.h для создания текстурных данных и отображения текста на экране. Ниже приведен пример функции, которая создает и отображает текстуру для заданной строки:
void renderText(const char* text, float x, float y, float scale, unsigned char* fontBuffer, int fontSize) {
stbtt_fontinfo font;
stbtt_InitFont(&font, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0));
int width, height;
stbtt_GetScaledFontVMetrics(&font, scale, &height, nullptr);
glEnable(GL_TEXTURE_2D);
glColor3f(1.0f, 1.0f, 1.0f);
glBindTexture(GL_TEXTURE_2D, 0);
int vertexCount = strlen(text) * 6;
GLfloat* vertices = new GLfloat[vertexCount * 2];
GLfloat* texcoords = new GLfloat[vertexCount * 2];
int x0 = (int)x;
int y0 = (int)y;
for (int i = 0, j = 0; i < strlen(text); i++, j += 12) {
int ax, ay, bw, bh;
stbtt_GetCodepointBitmapBox(&font, text[i], scale, scale, &ax, &ay, &bw, &bh);
int advance, lsb;
stbtt_GetCodepointHMetrics(&font, text[i], &advance, &lsb);
float x1 = x0 + ax * scale;
float y1 = y0 + ay * scale;
float x2 = x1 + bw * scale;
float y2 = y1 + bh * scale;
float s0, t0, s1, t1;
stbtt_GetCodepointBitmapBoxUV(&font, text[i], scale, scale, &s0, &t0, &s1, &t1);
vertices[j] = x1;
vertices[j + 1] = y1;
vertices[j + 2] = x2;
vertices[j + 3] = y1;
vertices[j + 4] = x1;
vertices[j + 5] = y2;
vertices[j + 6] = x1;
vertices[j + 7] = y2;
vertices[j + 8] = x2;
vertices[j + 9] = y1;
vertices[j + 10] = x2;
vertices[j + 11] = y2;
texcoords[j] = s0;
texcoords[j + 1] = t0;
texcoords[j + 2] = s1;
texcoords[j + 3] = t0;
texcoords[j + 4] = s0;
texcoords[j + 5] = t1;
texcoords[j + 6] = s0;
texcoords[j + 7] = t1;
texcoords[j + 8] = s1;
texcoords[j + 9] = t0;
texcoords[j + 10] = s1;
texcoords[j + 11] = t1;
x0 += advance * scale;
}
glVertexPointer(2, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, texcoords);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
delete[] vertices;
delete[] texcoords;
}
- Загрузите и отобразите текст в функции
display:
void display() {
glClear(GL_COLOR_BUFFER_BIT);
float x = 100.0f;
float y = 100.0f;
float scale = 20.0f;
renderText("Hello, World!", x, y, scale, fontBuffer, fontSize);
glutSwapBuffers();
}
- В функции
main загрузите шрифт и запустите цикл отрисовки окна:
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("STB Truetype with OpenGL");
glutDisplayFunc(display);
unsigned char* fontBuffer;
int fontSize;
if (!loadFont("arial.ttf", fontBuffer, fontSize))
return 1;
glutMainLoop();
delete[] fontBuffer;
return 0;
}
Это примерный код, который демонстрирует, как использовать функции из библиотеки stb_truetype.h для отображения текста на экране с использованием OpenGL. Помимо этого, вы также можете настроить масштаб, цвет и другие атрибуты рисуемого текста по своему усмотрению. Не забудьте добавить флаг -lstb_image при компиляции для связывания с библиотекой stb_image и флаг -lfreetype для связывания с библиотекой freetype.