Files
Seele/src/Engine/Asset/FontAsset.cpp
T

196 lines
8.7 KiB
C++
Raw Normal View History

2022-04-13 13:01:35 +02:00
#include "FontAsset.h"
2023-01-29 18:58:59 +01:00
#include "Graphics/Graphics.h"
2023-10-26 18:37:29 +02:00
#include "Graphics/Texture.h"
2026-10-21 21:21:49 +02:00
#include <ft2build.h>
#include FT_FREETYPE_H
2022-04-13 13:01:35 +02:00
using namespace Seele;
2024-06-09 12:20:04 +02:00
FontAsset::FontAsset() {}
2022-04-13 13:01:35 +02:00
2025-01-19 16:07:38 +01:00
FontAsset::FontAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {
FT_Error error = FT_Init_FreeType(&ft);
2025-05-23 16:12:33 +02:00
if(error) abort();
2023-11-07 16:55:13 +01:00
}
2025-01-19 16:07:38 +01:00
FontAsset::~FontAsset() {
2025-01-29 16:15:48 +01:00
FT_Done_Face(ft_face);
2025-01-19 16:07:38 +01:00
FT_Done_FreeType(ft);
2025-01-29 16:15:48 +01:00
hb_font_destroy(hb_font);
hb_face_destroy(hb_face);
hb_blob_destroy(blob);
2023-11-07 16:55:13 +01:00
}
2025-01-19 16:07:38 +01:00
void FontAsset::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, ttfFile); }
void FontAsset::load(ArchiveBuffer& buffer) {
Serialization::load(buffer, ttfFile);
graphics = buffer.getGraphics();
loadFace();
}
void FontAsset::loadFace() {
2025-03-20 20:15:38 +01:00
FT_Error error = FT_New_Memory_Face(ft, (unsigned char*)ttfFile.data(), (uint32)ttfFile.size(), 0, &ft_face);
2025-05-23 16:12:33 +02:00
if(error) abort();
2025-03-20 20:15:38 +01:00
blob = hb_blob_create(ttfFile.data(), (uint32)ttfFile.size(), HB_MEMORY_MODE_DUPLICATE, nullptr, nullptr);
2025-01-29 16:15:48 +01:00
hb_face = hb_face_create(blob, 0);
hb_font = hb_font_create(hb_face);
}
UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<RenderGlyph>& render) {
loadGlyphs(fontSize);
hb_buffer_t* buf = hb_buffer_create();
2025-03-20 20:15:38 +01:00
hb_buffer_add_utf8(buf, view.data(), (uint32)view.size(), 0, -1);
2025-01-29 16:15:48 +01:00
hb_buffer_set_language(buf, hb_language_from_string("en", -1));
hb_buffer_set_script(buf, HB_SCRIPT_LATIN);
hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
hb_shape(hb_font, buf, nullptr, 0);
uint32 num_glyphs;
hb_glyph_info_t* glyphs = hb_buffer_get_glyph_infos(buf, &num_glyphs);
hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buf, &num_glyphs);
Vector2 max = Vector2(std::numeric_limits<float>::lowest());
int32 xppem, yppem;
hb_font_get_scale(hb_font, &xppem, &yppem);
2026-10-20 22:01:51 +02:00
// Baseline (in pixels, relative to the text block's top-left) = the font's ascender.
// FreeType gives it in 1/64-pixel units after FT_Set_Pixel_Sizes; convert to pixels.
// Screen space is y-down; the baseline sits `ascender` px *below* the block's top edge.
// (FT metrics ascender is positive-up, so the baseline screen y = +ascender in y-down.)
float ascenderPx = (float)ft_face->size->metrics.ascender / 64.0f;
Vector2 cursor = Vector2(0, ascenderPx);
2025-01-29 16:15:48 +01:00
for (uint32 i = 0; i < num_glyphs; ++i) {
hb_codepoint_t glyphid = glyphs[i].codepoint;
2025-03-20 20:15:38 +01:00
float xOffset = (float)positions[i].x_offset * fontSize / xppem;
float yOffset = (float)positions[i].y_offset * fontSize / yppem;
float xAdvance = (float)positions[i].x_advance * fontSize / xppem;
float yAdvance = (float)positions[i].y_advance * fontSize / yppem;
2025-01-29 16:15:48 +01:00
Vector2 position = cursor + Vector2(xOffset, yOffset);
Vector2 dimensions = fontSizes[fontSize].glyphs[glyphid].size;
2026-10-20 22:01:51 +02:00
// FreeType bitmap_top = distance from the baseline to the TOP of the bitmap
// (positive up). In y-down screen space the bitmap's top edge is therefore at
// (baselineY - bitmap_top). bearing.x (bitmap_left) shifts the bitmap right of the
// pen. This is what was missing: without it every glyph's top sat on the cursor y
// (text top), giving top-aligned instead of baseline-aligned text.
float bearingX = (float)fontSizes[fontSize].glyphs[glyphid].bearing.x;
float bitmapTop = (float)fontSizes[fontSize].glyphs[glyphid].bearing.y;
position.x += bearingX;
position.y += -bitmapTop;
2026-10-21 21:21:49 +02:00
RenderGlyph& rg = render.add({});
rg.texture = fontSizes[fontSize].atlas;
rg.uvOffset = fontSizes[fontSize].glyphs[glyphid].uvOffset;
rg.uvSize = fontSizes[fontSize].glyphs[glyphid].uvSize;
rg.position = position;
rg.dimensions = dimensions;
2025-01-29 16:15:48 +01:00
cursor += Vector2(xAdvance, yAdvance);
2026-10-20 22:01:51 +02:00
// Track the right-most x extent (for auto width). Height is NOT derived from the
// bitmap extents: it must be the full line height (ascender - descender) or
// auto-sized elements would clip descenders. See below.
max.x = std::max(max.x, position.x + dimensions.x);
2025-01-29 16:15:48 +01:00
}
hb_buffer_destroy(buf);
2026-10-20 22:01:51 +02:00
// Width = right-most x extent (glyphs start at x>=0, so max.x is the full width).
// Height = line height from the font metrics: ascender (above baseline) plus the
// descender depth (FT descender is negative-up => its magnitude is below baseline).
// This is the correct auto-size: it fits the whole em, including descenders.
float descenderPx = (float)ft_face->size->metrics.descender / 64.0f; // <= 0 (down is negative-up)
float lineHeightPx = ascenderPx - descenderPx;
if (max.x <= 0.0f) { // empty string
return UVector2(0, 0);
}
return UVector2((uint32)std::ceil(max.x), (uint32)std::ceil(lineHeightPx));
2025-01-19 16:07:38 +01:00
}
2025-01-29 16:15:48 +01:00
void FontAsset::loadGlyphs(uint32 fontSize) {
2026-10-21 21:21:49 +02:00
if (fontSizes.contains(fontSize)) {
return; // packed once; the atlas is immutable
}
2025-01-29 16:15:48 +01:00
FT_Set_Pixel_Sizes(ft_face, 0, fontSize);
2026-10-21 21:21:49 +02:00
// measure every glyph's bitmap size first (one pass, no GPU) so the shelf packer
// can compute each cell's atlas coordinates before any pixels are uploaded
constexpr uint32 atlasW = 1024;
struct Slot {
int glyphId;
uint32 w, h;
uint32 x, y; // atlas coordinates, filled by the packer
};
Array<Slot> slots;
uint32 xCursor = 0;
uint32 cursorY = 0;
uint32 shelfH = 0;
2025-03-20 20:15:38 +01:00
for (int i = 0; i < ft_face->num_glyphs; ++i) {
2026-10-21 21:21:49 +02:00
int err = FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER);
assert(err == 0);
uint32 w = ft_face->glyph->bitmap.width;
uint32 h = ft_face->glyph->bitmap.rows;
if (w == 0 || h == 0) {
w = 1;
h = 1; // keep a 1x1 transparent placeholder so empty glyphs need no special case
}
if (w > atlasW) {
w = atlasW; // shortcut: no per-glyph multi-row splitting; clamp to the atlas width
}
if (xCursor + w > atlasW) {
cursorY += shelfH;
shelfH = 0;
xCursor = 0;
}
Slot s;
s.glyphId = i;
s.w = w;
s.h = h;
s.x = xCursor;
s.y = cursorY;
xCursor += w;
shelfH = std::max(shelfH, h);
slots.add(s);
}
uint32 totalH = cursorY + shelfH;
if (totalH == 0) {
totalH = 1;
}
Array<uint8> atlasData((uint64)atlasW * totalH, 0); // transparent by default
FontData& data = fontSizes[fontSize];
for (auto& s : slots) {
// FT_Load_Glyph resets the face's current glyph — the measured sizes in `slots`
// are already captured, so re-rendering here is safe
// (FreeType's FT_Load_Glyph must NOT be wrapped in assert(): NDEBUG in release
// builds would then never render the bitmap, leaving the atlas all-transparent.)
int err2 = FT_Load_Glyph(ft_face, s.glyphId, FT_LOAD_RENDER);
assert(err2 == 0);
uint32 bw = ft_face->glyph->bitmap.width;
uint32 bh = ft_face->glyph->bitmap.rows;
FontAsset::Glyph& glyph = data.glyphs[s.glyphId];
if (bw == 0 || bh == 0) {
bw = 1;
bh = 1;
glyph.textureData = Array<uint8>(1, 0); // 1x1 transparent placeholder
} else {
glyph.textureData.resize((uint64)bw * bh);
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, (uint64)bw * bh);
}
// blit the bitmap into the atlas at (s.x, s.y), row by row (pitch may differ from width)
for (uint32 y = 0; y < bh; ++y) {
const uint8* src = (bw == 0 || bh == 0) ? nullptr : (const uint8*)ft_face->glyph->bitmap.buffer + (uint64)y * ft_face->glyph->bitmap.pitch;
if (src != nullptr) {
std::memcpy(atlasData.data() + ((uint64)(s.y + y) * atlasW + s.x), src, bw);
}
}
glyph.size = IVector2(bw, bh);
2025-01-29 16:15:48 +01:00
glyph.bearing = IVector2(ft_face->glyph->bitmap_left, ft_face->glyph->bitmap_top);
glyph.advance = ft_face->glyph->advance.x;
2026-10-21 21:21:49 +02:00
// the UV rect is the exact cell, corner-aligned: offset = (x / W, y / H),
// size = (w / W, h / H). The shader already applies a 1-px inset (uvSize * 0.98),
// so linear sampling stays inside the cell and does not bleed into neighbors.
glyph.uvOffset = Vector2((float)s.x / (float)atlasW, (float)s.y / (float)totalH);
glyph.uvSize = Vector2((float)bw / (float)atlasW, (float)bh / (float)totalH);
2025-01-19 16:07:38 +01:00
}
2026-10-21 21:21:49 +02:00
data.atlas = graphics->createTexture2D(TextureCreateInfo{
.sourceData =
{
.size = atlasData.size(),
.data = atlasData.data(),
},
.format = Gfx::SE_FORMAT_R8_UNORM,
.width = atlasW,
.height = totalH,
.name = "FontAtlas",
});
}