NouVeL/ADVect/Graphics.cpp

77 lines
1.8 KiB
C++
Raw Normal View History

2022-05-09 01:50:09 -04:00
#include "Graphics.h"
#include <iostream>
2022-05-09 03:46:44 -04:00
#include <locale>
#include <codecvt>
2022-05-09 01:50:09 -04:00
namespace {
FT_Library library;
FT_Error error;
FT_Face face;
}
namespace ADVect::Graphics {
void Init() {
error = FT_Init_FreeType(&library);
if (error) {
std::cerr << "FreeType init error: " << error << std::endl;
}
2022-05-09 03:46:44 -04:00
error = FT_New_Face(library, "SourceHanSans-Regular.ttc", 0, &face);
2022-05-09 01:50:09 -04:00
if (error == FT_Err_Unknown_File_Format) {
std::cerr << "FreeType Unknown_File_Format: " << error << std::endl;
}
else if (error) {
std::cerr << "FreeType font loading error: " << error << std::endl;
}
2022-05-09 03:46:44 -04:00
error = FT_Set_Char_Size(face, 0, 20 * 64, 72, 72);
2022-05-09 01:50:09 -04:00
if (error == FT_Err_Unknown_File_Format) {
std::cerr << "FreeType Set_Char_Size error: " << error << std::endl;
}
}
void Destroy() {
FT_Done_Face(face);
FT_Done_FreeType(library);
}
2022-05-09 03:46:44 -04:00
void RenderString(const std::string& s, SDL_Surface* surface, int pos_x, int pos_y) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring w = converter.from_bytes(s);
2022-05-09 01:50:09 -04:00
2022-05-09 03:46:44 -04:00
FT_GlyphSlot slot = face->glyph;
SDL_Color colors[256];
for (int i = 0; i < 256; i++)
{
colors[i].r = colors[i].g = colors[i].b = i;
}
2022-05-09 01:50:09 -04:00
2022-05-09 03:46:44 -04:00
for (const auto& c : w) {
2022-05-09 01:50:09 -04:00
error = FT_Load_Char(face, c, FT_LOAD_RENDER);
if (error)
continue;
SDL_Surface* glyph = SDL_CreateRGBSurfaceFrom(
2022-05-09 03:46:44 -04:00
slot->bitmap.buffer,
2022-05-09 01:50:09 -04:00
slot->bitmap.width,
slot->bitmap.rows,
8,
2022-05-09 03:46:44 -04:00
slot->bitmap.pitch,
2022-05-09 01:50:09 -04:00
0, 0, 0, 255);
2022-05-09 03:46:44 -04:00
SDL_SetPaletteColors(glyph->format->palette, colors, 0, 256);
2022-05-09 01:50:09 -04:00
SDL_SetSurfaceBlendMode(glyph, SDL_BlendMode::SDL_BLENDMODE_NONE);
2022-05-09 03:46:44 -04:00
SDL_Rect pos = { pos_x + slot->bitmap_left, pos_y - slot->bitmap_top, 0, 0 };
2022-05-09 01:50:09 -04:00
SDL_BlitSurface(glyph, nullptr, surface, &pos);
SDL_FreeSurface(glyph);
2022-05-09 03:46:44 -04:00
pos_x += slot->advance.x >> 6;
pos_y += slot->advance.y >> 6;
2022-05-09 01:50:09 -04:00
}
}
}