Implement texture atlas for fonts

This commit is contained in:
Dynamitos committed 2026-10-21 21:21:49 +02:00
1 parent 17dc1e4d88
commit 22a90fe07c
14 files changed
+388 -50

No files matched your search

+41 -3
View File
@@ -1,5 +1,6 @@
#pragma once
#include "Asset.h"
#include "FontAssetTestHooks.h"
#include "Containers/Map.h"
#include "Graphics/Texture.h"
#include "Math/Math.h"
@@ -21,24 +22,59 @@ class FontAsset : public Asset {
UVector2 bearing = {};
uint32 advance = 0;
Array<uint8> textureData;
Gfx::OTexture2D texture = nullptr;
// rect of this glyph inside the per-(font,size) atlas; the atlas texture is
// shared by every glyph of the same size (FontData::atlas) — no per-glyph texture
Vector2 uvOffset = Vector2(0);
Vector2 uvSize = Vector2(0);
void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer);
};
struct FontData {
Map<uint32, Glyph> glyphs;
// the single atlas holding every glyph of this size (created in loadGlyphs)
Gfx::OTexture2D atlas = nullptr;
};
void loadFace();
// packs every glyph of `fontSize` into one atlas (created lazily on first use by
// shapeText); public so the unit test can drive the real packer
void loadGlyphs(uint32 fontSize);
// test seam, mirrors exactly what FontLoader::import does (the only other path that
// sets ttfFile/graphics): a unit test uses it to drive loadGlyphs() and read the
// produced atlas back for validation against FreeType ground truth
void importForTest(const char* ttfBytes, uint64 size, Gfx::PGraphics graphics) {
this->ttfFile = Array<char>(size);
std::memcpy(this->ttfFile.data(), ttfBytes, size);
this->graphics = graphics;
loadFace();
}
// unit test: reads the packed atlas + UV rects back for validation (friend)
FontAssetGlyphRects exportForTest(uint32 fontSize) const {
const FontData& data = fontSizes.at(fontSize);
FontAssetGlyphRects out;
out.atlasWidth = data.atlas->getWidth();
out.atlasHeight = data.atlas->getHeight();
out.atlas = data.atlas;
for (auto& [id, glyph] : data.glyphs) {
FontAssetGlyphRects::Rect r;
r.uvOffset = glyph.uvOffset;
r.uvSize = glyph.uvSize;
r.width = glyph.size.x;
r.height = glyph.size.y;
out.glyphs[id] = r;
}
return out;
}
struct RenderGlyph {
Gfx::PTexture2D texture;
Gfx::PTexture2D texture; // the font's atlas for this size (shared by all its glyphs)
Vector2 uvOffset;
Vector2 uvSize;
UVector2 position;
UVector2 dimensions;
};
UVector2 shapeText(std::string_view view, uint32 fontSize, Array<RenderGlyph>& render);
private:
void loadGlyphs(uint32 fontSize);
Gfx::PGraphics graphics;
hb_blob_t* blob;
hb_face_t* hb_face;
@@ -48,6 +84,8 @@ class FontAsset : public Asset {
Array<char> ttfFile;
Map<uint32, FontData> fontSizes;
friend class FontLoader;
// unit test: drives the packer and reads the resulting atlas back for validation
friend class FontAssetAtlasProbe;
};
DECLARE_REF(FontAsset)
} // namespace Seele