forked from Dynamitos/Seele
Implement texture atlas for fonts
This commit is contained in:
1 parent
17dc1e4d88
commit
22a90fe07c
14 files changed
+388
-50
No files matched your search
@@ -1,6 +1,8 @@
|
||||
#include "FontAsset.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -71,11 +73,12 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
float bitmapTop = (float)fontSizes[fontSize].glyphs[glyphid].bearing.y;
|
||||
position.x += bearingX;
|
||||
position.y += -bitmapTop;
|
||||
render.add(RenderGlyph{
|
||||
.texture = fontSizes[fontSize].glyphs[glyphid].texture,
|
||||
.position = position,
|
||||
.dimensions = dimensions,
|
||||
});
|
||||
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;
|
||||
cursor += Vector2(xAdvance, yAdvance);
|
||||
// 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
|
||||
@@ -96,32 +99,98 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
}
|
||||
|
||||
void FontAsset::loadGlyphs(uint32 fontSize) {
|
||||
if (fontSizes.contains(fontSize)) {
|
||||
return; // packed once; the atlas is immutable
|
||||
}
|
||||
FT_Set_Pixel_Sizes(ft_face, 0, fontSize);
|
||||
// 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;
|
||||
for (int i = 0; i < ft_face->num_glyphs; ++i) {
|
||||
assert(FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER) == 0);
|
||||
FontAsset::Glyph& glyph = fontSizes[fontSize].glyphs[i];
|
||||
glyph.size = IVector2(ft_face->glyph->bitmap.width, ft_face->glyph->bitmap.rows);
|
||||
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);
|
||||
glyph.bearing = IVector2(ft_face->glyph->bitmap_left, ft_face->glyph->bitmap_top);
|
||||
glyph.advance = ft_face->glyph->advance.x;
|
||||
glyph.textureData.resize(glyph.size.x * glyph.size.y);
|
||||
if (glyph.textureData.size() == 0) {
|
||||
glyph.size.x = 1;
|
||||
glyph.size.y = 1;
|
||||
glyph.textureData.add(0);
|
||||
// load a single transparent pixel, so that we dont have to handle empty textures later
|
||||
} else {
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, glyph.textureData.size());
|
||||
}
|
||||
glyph.texture = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = glyph.textureData.size(),
|
||||
.data = glyph.textureData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = glyph.size.x,
|
||||
.height = glyph.size.y,
|
||||
.name = "FontGlyph",
|
||||
});
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
data.atlas = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = atlasData.size(),
|
||||
.data = atlasData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = atlasW,
|
||||
.height = totalH,
|
||||
.name = "FontAtlas",
|
||||
});
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include "Containers/Map.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include "Math/Math.h"
|
||||
|
||||
namespace Seele {
|
||||
struct FontAssetGlyphRects {
|
||||
struct Rect {
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
uint32 width = 0;
|
||||
uint32 height = 0;
|
||||
};
|
||||
uint32 atlasWidth = 0;
|
||||
uint32 atlasHeight = 0;
|
||||
Map<uint32, Rect> glyphs; // glyphId -> packed rect (same order as the atlas upload)
|
||||
Gfx::PTexture2D atlas = nullptr; // the packed atlas (for readback via download)
|
||||
};
|
||||
} // namespace Seele
|
||||
@@ -59,6 +59,8 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
.color = render.backgroundColor,
|
||||
.z = render.level / 100.f,
|
||||
.textureIndex = textureIndex,
|
||||
.uvOffset = render.uvOffset,
|
||||
.uvSize = render.uvSize,
|
||||
});
|
||||
}
|
||||
elementBuffer->rotateBuffer(sizeof(RenderElementStyle) * elements.size());
|
||||
|
||||
@@ -36,8 +36,10 @@ class UIPass : public RenderPass {
|
||||
float opacity = 1;
|
||||
float z = 0;
|
||||
uint32 textureIndex = std::numeric_limits<uint32>::max();
|
||||
uint32 pad0;
|
||||
uint32 pad1;
|
||||
// UV rect for textured quads (glyphs: their rect in the font atlas); unused for untextured quads
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(1);
|
||||
Vector2 pad;
|
||||
};
|
||||
|
||||
Gfx::RenderTargetAttachment colorAttachment;
|
||||
|
||||
@@ -1023,7 +1023,11 @@ void Graphics::createDevice(GraphicsInitializer initializer) {
|
||||
updateQueueInfo(familyIndex, computeQueueInfo, numQueuesForFamily);
|
||||
}
|
||||
}
|
||||
if ((currProps.queueFlags ^ VK_QUEUE_TRANSFER_BIT) == 0) {
|
||||
// a queue family is a valid transfer queue if it supports the transfer bit at all
|
||||
// (previously `(flags ^ TRANSFER) == 0`, which only matched pure-transfer families
|
||||
// that don't exist on standard drivers: no transfer queue was ever created, so
|
||||
// every vkQueueSubmit on the transfer queue path failed with VK_ERROR_DEVICE_LOST)
|
||||
if (currProps.queueFlags & VK_QUEUE_TRANSFER_BIT) {
|
||||
updateQueueInfo(familyIndex, transferQueueInfo, numQueuesForFamily);
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,10 @@ TextureHandle::TextureHandle(PGraphics graphics, VkImageViewType viewType, const
|
||||
// When loading a texture from a file, we will almost always use it as a texture map for fragment shaders
|
||||
changeLayout(Gfx::SE_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
|
||||
// The copy above is only enqueued on a command buffer; it must actually be
|
||||
// submitted to the GPU before any consumer (the UI pass, a test's download,
|
||||
// etc.) can read the image. Without this the image is still all zeros.
|
||||
commandPool->submitCommands();
|
||||
graphics->getDestructionManager()->queueResourceForDestruction(std::move(stagingAlloc));
|
||||
}
|
||||
}
|
||||
@@ -359,6 +363,14 @@ void TextureHandle::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Ar
|
||||
cmdBuffer->bindResource(PBufferAllocation(stagingAlloc));
|
||||
changeLayout(prevLayout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_READ_BIT,
|
||||
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
|
||||
// The copy above is only enqueued; the staging buffer is still all zeros until the
|
||||
// command actually runs. Submit it and wait on its fence before mapping, or the read
|
||||
// below would race the GPU and return a blank texture. (submitCommands() submits the
|
||||
// current command and rotates to a fresh one, exactly like the upload path in the
|
||||
// TextureHandle constructor.)
|
||||
PCommandPool pool = graphics->getQueueCommands(owner);
|
||||
pool->submitCommands();
|
||||
cmdBuffer->waitForCommand();
|
||||
VK_CHECK(vmaMapMemory(graphics->getAllocator(), stagingAlloc->allocation, &data));
|
||||
buffer.resize(imageSize);
|
||||
std::memcpy(buffer.data(), data, buffer.size());
|
||||
|
||||
@@ -19,11 +19,11 @@ struct UIRender {
|
||||
uint32 z;
|
||||
uint32 level;
|
||||
PElement element; // back-ref for input hit-testing
|
||||
// glyph-only (text): the glyph texture is backgroundTexture, this is the
|
||||
// per-glyph rect in *atlas* space (0..1) so the pass can emit a glyph quad
|
||||
bool isGlyph = false;
|
||||
// UV rect for textured quads; glyphs carry their rect in the font's per-size
|
||||
// atlas (backgroundTexture = the atlas), full-rect (0,0,1,1) for plain images.
|
||||
// A "glyph quad" is nothing special: a quad with a texture and a UV rect.
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
Vector2 uvSize = Vector2(1);
|
||||
};
|
||||
class Element {
|
||||
public:
|
||||
|
||||
@@ -79,7 +79,7 @@ class Text : public Element {
|
||||
.level = level,
|
||||
.element = this,
|
||||
});
|
||||
// text: one render quad per shaped glyph, carrying its atlas rect
|
||||
// text: one quad per shaped glyph, carrying its rect in the font's per-size atlas
|
||||
if (style.fontFamily != nullptr) {
|
||||
for (auto& g : glyphs) {
|
||||
result.add(UIRender{
|
||||
@@ -90,9 +90,8 @@ class Text : public Element {
|
||||
.z = style.z,
|
||||
.level = level,
|
||||
.element = this,
|
||||
.isGlyph = true,
|
||||
.uvOffset = Vector2(0),
|
||||
.uvSize = Vector2(1),
|
||||
.uvOffset = g.uvOffset,
|
||||
.uvSize = g.uvSize,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user