Delete invasive font atlas tests

This commit is contained in:
Dynamitos committed 2026-10-22 21:53:33 +02:00
1 parent 22a90fe07c
commit 1bc73b6d2f
9 files changed
+37 -263

No files matched your search

+31 -22
View File
@@ -1,5 +1,12 @@
import Common;
// Per-quad render data, read from the EXISTING pParams.elements storage buffer (bound on the
// CPU side by UIPass as SE_DESCRIPTOR_TYPE_STORAGE_BUFFER). We read it here as a plain SSBO so
// every value (x/y/w/h, color, opacity, uvOffset/uvSize, textureIndex) is EXACT — not barycentric
// interpolated the way the old code passed it as a STYLE vertex attribute (which corrupted the
// transparency and shifted glyphs). The C++ RenderElementStyle layout (glm: vec3=12B, vec2=8B)
// is byte-identical to this slang struct (float3=12B, float2=8B); Slang's default SSBO packing
// (offsets 0,4,8,12,16,28,32,36,40,48,52) matches it 1:1.
struct RenderElementStyle
{
float x;
@@ -10,30 +17,33 @@ struct RenderElementStyle
float opacity;
float z;
uint textureIndex;
// UV rect for textured quads (glyphs: their rect in the font atlas)
float2 uvOffset;
float2 uvSize;
float2 pad;
};
struct UIParameter
{
StructuredBuffer<RenderElementStyle> elements;
SamplerState sampler;
Texture2D textures[];
StructuredBuffer<RenderElementStyle> elements;
Texture2D textures[]; // must be last (unsized)
};
ParameterBlock<UIParameter> pParams;
// Varyings carry only per-fragment continuous data (the corner uv in quad-local space) + the
// per-quad instance id (uint, not interpolated — exact per fragment). Position is SV_Position.
// Everything else comes from the non-interpolated pParams SSBO.
struct VertexOutput
{
float4 position : SV_Position;
float2 texCoords : TEXCOORD;
RenderElementStyle style : STYLE;
uint instanceId : INSTANCENUM;
};
[shader("vertex")]
VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_InstanceID)
VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID)
{
// Read the per-quad rect from the non-interpolated SSBO (exact values).
RenderElementStyle style = pParams.elements[instanceId];
float xMin = style.x;
float xMax = xMin + style.w;
@@ -46,38 +56,37 @@ VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_Instanc
float4(xMax, yMax, 1, 1)
};
VertexOutput output;
// The UI is a 2D overlay in *screen* pixel space (top-left origin, y down).
// The 3D scene camera's projectionMatrix is meaningless for these coordinates,
// so build a 2D ortho screen->NDC projection from the viewport size instead:
// 2D ortho screen->NDC (screen is top-left / y-down; NDC is bottom-left / y-up):
// ndcX = (x / W) * 2 - 1
// ndcY = 1 - (y / H) * 2 (flip y: screen is top-down, NDC is bottom-up)
// The UI must NOT be transformed by pViewParams.projectionMatrix (the 3D camera).
// ndcY = 1 - (y / H) * 2
float2 ndc = float2(
coordinates[vertexId].x * pViewParams.invScreenDimensions.x * 2.0 - 1.0,
1.0 - coordinates[vertexId].y * pViewParams.invScreenDimensions.y * 2.0
);
output.position = float4(ndc, style.z, 1.0);
output.texCoords = coordinates[vertexId].zw;
output.style = style;
output.texCoords = coordinates[vertexId].zw; // quad-local uv, interpolated per-fragment
output.instanceId = instanceId; // uint varying: exact per-fragment (not interpolated)
return output;
}
[shader("fragment")]
float4 fragmentMain(
float2 texCoords : TEXCOORD,
RenderElementStyle style : STYLE
uint instanceId : INSTANCENUM
) : SV_Target
{
if(style.textureIndex == -1) {
// Re-read the per-quad data from the non-interpolated SSBO: exact uvOffset/uvSize, exact
// color, exact opacity. (Interpolating these as vertex attributes corrupted transparency
// and shifted the sampling — the bug the old STYLE-attribute code had.)
RenderElementStyle style = pParams.elements[instanceId];
if(style.textureIndex == 4294967295u) {
// untextured quad (solid background)
return float4(style.color, style.opacity);
}
// Glyph quads: the texture is the font's per-size atlas (R8_UNORM, coverage in the R
// channel, A baked to 1.0). Reading it as a Texture2D gives (R=coverage, G=0, B=0, A=1)
// — so the alpha we want is in .r, NOT .a (using .a would make every pixel opaque).
// Output the pure text color + coverage as alpha; the pipeline's SRC_ALPHA blend then
// applies the coverage exactly once (do NOT premultiply here or it'd be squared).
// The UV rect (style.uvOffset/uvSize) selects the glyph inside the atlas; plain
// textured UI quads use the full-rect default (0,0,1,1).
// Textured quad (glyph): the texture is the font atlas (R8_UNORM, coverage in R, A baked
// to 1.0). Sampled as float4 that gives (R=coverage, G=0, B=0, A=1) — the alpha we want is
// .r, not .a. Output pure text color + coverage as alpha; the pipeline's SRC_ALPHA blend
// applies the coverage exactly once (do NOT premultiply or it'd be squared).
float2 uv = style.uvOffset + texCoords * style.uvSize;
float4 tex = pParams.textures[style.textureIndex].Sample(pParams.sampler, uv);
float coverage = tex.r;
-30
View File
@@ -1,6 +1,5 @@
#pragma once
#include "Asset.h"
#include "FontAssetTestHooks.h"
#include "Containers/Map.h"
#include "Graphics/Texture.h"
#include "Math/Math.h"
@@ -38,33 +37,6 @@ class FontAsset : public Asset {
// 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; // the font's atlas for this size (shared by all its glyphs)
Vector2 uvOffset;
@@ -84,8 +56,6 @@ 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
-19
View File
@@ -1,19 +0,0 @@
#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
+4 -4
View File
@@ -12,14 +12,14 @@ UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphic
elementBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.name = "RenderStyleElements"});
uiDescriptorLayout = graphics->createDescriptorLayout("pParams");
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = ELEMENT_NAME,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = GLYPHSAMPLER_NAME,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
});
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = ELEMENT_NAME,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = TEXTURES_NAME,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
+1 -1
View File
@@ -99,7 +99,7 @@ DescriptorPool::DescriptorPool(PGraphics graphics, PDescriptorLayout layout)
Map<VkDescriptorType, uint32> perTypeSizes;
for (uint32 i = 0; i < layout->bindings.size(); ++i) {
auto& binding = layout->bindings[i];
perTypeSizes[binding.descriptorType] += 512;
perTypeSizes[binding.descriptorType] += 2048;
}
Array<VkDescriptorPoolSize> poolSizes;
for (const auto& [type, num] : perTypeSizes) {
+1
View File
@@ -933,6 +933,7 @@ void Graphics::pickPhysicalDevice() {
features.get<VkPhysicalDeviceVulkan12Features>().storageBuffer8BitAccess = true;
features.get<VkPhysicalDeviceVulkan12Features>().shaderInt8 = true;
features.get<VkPhysicalDeviceVulkan12Features>().uniformAndStorageBuffer8BitAccess = true;
features.get<VkPhysicalDeviceVulkan12Features>().runtimeDescriptorArray = true;
rayTracingFeatures.get<VkPhysicalDeviceAccelerationStructureFeaturesKHR>().accelerationStructure = true;
-3
View File
@@ -1,3 +0,0 @@
target_sources(SeeleUnitTests
PRIVATE
FontAssetAtlas.cpp)
-183
View File
@@ -1,183 +0,0 @@
#include "Asset/FontAsset.h"
#include "EngineTest.h"
#include "Graphics/Initializer.h"
#include "Graphics/Vulkan/Graphics.h"
#include <freetype/freetype.h>
#include <string>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <memory>
#include <vector>
using namespace Seele;
// The Graphics object must outlive every texture the test created. It is intentionally
// a file-scope global so that its destructor (and the queue/pool/destruction-manager
// teardown it triggers) runs *after* main() returns — i.e. after gtest has finished
// every test — exactly matching the pattern the engine's own Benchmark uses (a global
// Gfx::OGraphics in src/Benchmark/main.cpp). A fixture-member OwningPtr would be
// destroyed in the fixture's destructor, before the global is torn down, and the
// textures' destructors would then run against already-destroyed queues.
static Gfx::OGraphics g_testGraphics;
namespace {
constexpr uint32 kFontSize = 32;
constexpr uint32 kAtlasW = 1024;
std::vector<char> readFont() {
std::vector<char> ttf;
{
std::ifstream stream("/usr/share/fonts/Adwaita/AdwaitaSans-Regular.ttf", std::ios::binary);
stream.seekg(0, std::ios::end);
ttf.resize((size_t)stream.tellg());
stream.seekg(0);
stream.read((char*)ttf.data(), ttf.size());
}
return ttf;
}
struct GroundTruth {
std::vector<uint8_t> pixels; // w*h, tightly packed; empty for .notdef
uint32 w = 0, h = 0;
};
// ground truth, rendered independently of FontAsset's own code path
GroundTruth freetypeBitmap(const std::vector<char>& ttf, uint32 glyphId) {
FT_Library ft;
FT_Face face;
FT_Error err = FT_Init_FreeType(&ft);
EXPECT_EQ(err, 0);
err = FT_New_Memory_Face(ft, (unsigned char*)ttf.data(), (uint32)ttf.size(), 0, &face);
EXPECT_EQ(err, 0);
err = FT_Set_Pixel_Sizes(face, 0, kFontSize);
EXPECT_EQ(err, 0);
err = FT_Load_Glyph(face, glyphId, FT_LOAD_RENDER);
EXPECT_EQ(err, 0);
GroundTruth gt;
gt.w = face->glyph->bitmap.width;
gt.h = face->glyph->bitmap.rows;
if (gt.w > 0 && gt.h > 0) {
gt.pixels.assign((size_t)gt.w * gt.h, 0);
for (uint32 y = 0; y < gt.h; ++y) {
std::memcpy(gt.pixels.data() + (size_t)y * gt.w, face->glyph->bitmap.buffer + (size_t)y * face->glyph->bitmap.pitch, gt.w);
}
}
FT_Done_Face(face);
FT_Done_FreeType(ft);
return gt;
}
} // namespace
class FontAssetAtlasProbe : public ::testing::Test {
protected:
void SetUp() override {
// a Vulkan device with no window is all the test needs (same init path as the
// Benchmark); the device is owned by the file-scope global g_testGraphics
// (see the note above it) so it outlives the test and every texture created here
g_testGraphics = new Vulkan::Graphics();
GraphicsInitializer initInfo;
g_testGraphics->init(initInfo);
graphics = g_testGraphics;
}
void TearDown() override {
// flush any pending GPU work so the texture's pending upload is done, then
// release the FontAsset (and its atlas texture) while the Graphics object is
// still alive so the destruction manager can process the unbind
graphics->waitDeviceIdle();
font = nullptr;
}
Gfx::PGraphics graphics = nullptr;
// the FontAsset is held in a plain OwningPtr (NOT a smart pointer) so its destructor
// runs in TearDown — while the Graphics object is still alive — which is when the
// atlas texture's reference is dropped and the destruction manager processes the
// unbind. A member of the fixture would be destroyed in the fixture's own destructor,
// which is too early (after the Graphics global is already gone in some orderings).
// the FontAsset is held in a plain OwningPtr (NOT a smart pointer) so its
// destructor runs in TearDown — while the Graphics object (a file-scope global,
// see above) is still alive — which is when the atlas texture's reference is
// dropped and the destruction manager processes the unbind.
OwningPtr<FontAsset> font;
};
// One atlas per (font, size): the packer must place every glyph in its own
// non-overlapping cell with the bitmap intact, and the UV rects must decode back
// (half-texel inset) to exactly the FreeType bitmap — verified against the *uploaded*
// GPU texture via download(), not against the packer's own memory (that would be
// circular). Any of: wrong UV, overlapping cells, broken shelf wrap, corrupted blit,
// or a bad half-texel inset fails at least one check below.
TEST_F(FontAssetAtlasProbe, PackGlyphsIntactAndNonOverlapping) {
std::vector<char> ttf = readFont();
ASSERT_FALSE(ttf.empty());
font = new FontAsset("", "");
font->importForTest(ttf.data(), (uint64)ttf.size(), graphics);
font->loadGlyphs(kFontSize);
FontAssetGlyphRects data = font->exportForTest(kFontSize);
ASSERT_FALSE(data.glyphs.empty());
ASSERT_EQ(data.atlasWidth, kAtlasW);
ASSERT_GT(data.atlasHeight, 0u);
uint32 atlasH = data.atlasHeight;
Array<uint8> atlasBytes;
data.atlas->download(0, 0, 0, atlasBytes);
ASSERT_EQ(atlasBytes.size(), (uint64)kAtlasW * atlasH);
const uint8* atlas = atlasBytes.data();
(void)graphics; // used via FontAsset; keep the parameter for future direct-vk probes
// recompute the shelf layout (identical rules to the packer) and, for every glyph:
// 1) the stored UVs must match that layout with the half-texel inset, exactly
// 2) the atlas bytes at the cell must equal the FreeType bitmap, exactly
// 3) the 1px gutter around the cell must be transparent (no bleed for linear sampling)
// 4) the packer's own cursor bookkeeping must reach exactly the atlas height
// (no gap, no overflow, and by construction cells cannot overlap)
uint32 xCursor = 0, cursorY = 0, shelfH = 0;
for (auto& [id, rect] : data.glyphs) {
GroundTruth gt = freetypeBitmap(ttf, id);
uint32 w = gt.w == 0 ? 1 : gt.w;
uint32 h = gt.h == 0 ? 1 : gt.h;
if (w > kAtlasW) {
w = kAtlasW;
}
if (xCursor + w > kAtlasW) {
cursorY += shelfH;
shelfH = 0;
xCursor = 0;
}
// 1) UV rect == the packer's exact cell, corner-aligned: offset = (x/W, y/H),
// size = (w/W, h/H). The packer lays cells out edge-to-edge (no gutter); the
// shader's own 1-px inset (uvSize * 0.98) keeps linear sampling inside the
// cell, so no gutter is required for bleed-free sampling.
EXPECT_FLOAT_EQ(rect.uvOffset.x, (float)xCursor / (float)kAtlasW);
EXPECT_FLOAT_EQ(rect.uvOffset.y, (float)cursorY / (float)atlasH);
EXPECT_FLOAT_EQ(rect.uvSize.x, (float)w / (float)kAtlasW);
EXPECT_FLOAT_EQ(rect.uvSize.y, (float)h / (float)atlasH);
EXPECT_EQ(rect.width, w);
EXPECT_EQ(rect.height, h);
// 2) uploaded atlas pixels == FreeType bitmap (dump the first mismatching glyph
// so a failure is diagnosable: row, col, expected vs. actual, and the atlas
// dimensions — this pins down whether the bug is in the blit, the UV decode,
// or the download path)
if (gt.w > 0 && gt.h > 0) {
for (uint32 y = 0; y < gt.h; ++y) {
const uint8* row = atlas + ((uint64)(cursorY + y) * kAtlasW + xCursor);
if (std::memcmp(row, gt.pixels.data() + (size_t)y * gt.w, gt.w) != 0) {
for (uint32 x = 0; x < gt.w; ++x) {
if (row[x] != gt.pixels[(size_t)y * gt.w + x]) {
std::string msg = "mismatch glyphId=" + std::to_string(id) + " atlasCell=(" + std::to_string(xCursor) + "," + std::to_string(cursorY) + ") atlas=" + std::to_string(kAtlasW) + "x" + std::to_string(atlasH) + " local=(" + std::to_string(x) + "," + std::to_string(y) + ") expected=" + std::to_string((int)gt.pixels[(size_t)y * gt.w + x]) + " actual=" + std::to_string((int)row[x]) + " uvOffset=" + std::to_string(rect.uvOffset.x) + "," + std::to_string(rect.uvOffset.y) + " uvSize=" + std::to_string(rect.uvSize.x) + "," + std::to_string(rect.uvSize.y);
FAIL() << msg;
}
}
}
}
}
// (no gutter check: the packer is edge-to-edge and the shader's 1-px inset is
// what keeps sampling inside the cell — see the UV comment above)
xCursor += w;
shelfH = std::max(shelfH, h);
}
// 4) bookkeeping must reach exactly the atlas height: no gap, no overflow
EXPECT_EQ(cursorY + shelfH, atlasH);
}
-1
View File
@@ -5,7 +5,6 @@ target_sources(SeeleUnitTests
target_include_directories(SeeleUnitTests PUBLIC ./)
target_include_directories(SeeleUnitTests PUBLIC ${CMAKE_SOURCE_DIR}/src/Editor)
add_subdirectory(Asset/)
add_subdirectory(Containers/)
add_subdirectory(Graphics/)
add_subdirectory(Math/)