From ea7fc15ebcaf491b153180907eae2e21ffb27f59 Mon Sep 17 00:00:00 2001 From: SoapyMan Date: Sun, 8 Nov 2026 22:58:38 +0500 Subject: [PATCH 01/16] - grim: read back only used draw invocations, fix out of range activeDrawInvocations after draw infos are freed Co-Authored-By: Claude Opus 5.5 --- shared/grim/GrimBaseRenderer.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/shared/grim/GrimBaseRenderer.cpp b/shared/grim/GrimBaseRenderer.cpp index 2898b7a44..17300bee0 100644 --- a/shared/grim/GrimBaseRenderer.cpp +++ b/shared/grim/GrimBaseRenderer.cpp @@ -1117,7 +1117,10 @@ void GRIMBaseRenderer::UpdateIndirectInstances_Compute(IntermediateState& interm computeRecorder->Complete(); // copy draw invocations to readback buffer - intermediate.cmdRecorder->CopyBufferToBuffer(rendState.drawInvocationsBuffer, 0, rendState.drawInvocationsReadbackBuffer, 0, rendState.drawInvocationsBuffer->GetSize()); + // buffer does not shrink when draw infos are freed, copy only used commands + const int drawInvocationsSize = m_drawInfos.numElem() * static_cast(sizeof(GPUDrawIndexedIndirectCmd)); + if (drawInvocationsSize > 0) + intermediate.cmdRecorder->CopyBufferToBuffer(rendState.drawInvocationsBuffer, 0, rendState.drawInvocationsReadbackBuffer, 0, drawInvocationsSize); } void GRIMBaseRenderer::UpdateIndirectInstances_Software(IntermediateState& intermediate) @@ -1279,7 +1282,8 @@ bool GRIMBaseRenderer::IsSoftwareMode() const void GRIMBaseRenderer::PostPrepareDraw(GRIMRenderState& renderState) { IGPUBufferPtr& drawInvocationsReadbackBuffer = renderState.drawInvocationsReadbackBuffer; - if (IsSoftwareMode() || renderState.drawFrame != m_drawFrame || !drawInvocationsReadbackBuffer) + const int drawInvocationsSize = min(m_drawInfos.numElem() * static_cast(sizeof(GPUDrawIndexedIndirectCmd)), drawInvocationsReadbackBuffer ? static_cast(drawInvocationsReadbackBuffer->GetSize()) : 0); + if (IsSoftwareMode() || renderState.drawFrame != m_drawFrame || drawInvocationsSize <= 0) { renderState.drawInvocationsReadbackFuture = nullptr; return; @@ -1288,7 +1292,7 @@ void GRIMBaseRenderer::PostPrepareDraw(GRIMRenderState& renderState) BitArray& activeDrawInvocations = renderState.activeDrawInvocations; // read draw invocations - renderState.drawInvocationsReadbackFuture = drawInvocationsReadbackBuffer->Lock(0, drawInvocationsReadbackBuffer->GetSize(), 0); + renderState.drawInvocationsReadbackFuture = drawInvocationsReadbackBuffer->Lock(0, drawInvocationsSize, 0); renderState.drawInvocationsReadbackFuture.AddCallback([this, &activeDrawInvocations, drawInvocationsReadbackBuffer](const FutureResult& result) { if (result.IsError()) { @@ -1297,7 +1301,7 @@ void GRIMBaseRenderer::PostPrepareDraw(GRIMRenderState& renderState) } ASSERT(result->data); - const int numIndirectCmds = result->size / sizeof(GPUDrawIndexedIndirectCmd); + const int numIndirectCmds = min(static_cast(result->size / sizeof(GPUDrawIndexedIndirectCmd)), activeDrawInvocations.numBits()); GPUDrawIndexedIndirectCmd* drawIndexedCmd = reinterpret_cast(result->data); int drawnInstances = 0; From 98150c5fc02e2f186726acc6a1344fa0a19e1817 Mon Sep 17 00:00:00 2001 From: SoapyMan Date: Mon, 9 Nov 2026 01:11:49 +0500 Subject: [PATCH 02/16] - matsystem: fix transient uniform data overwritten before use, the buffer ring switches to the next buffer only when the current one is full instead of on every commit - matsystem: QueueCommitInternalBuffers submits the buffer writes under the buffer mutex - matsystem: NextBufferOffset checks the aligned offset against the buffer size - docs: describe transient uniform data in public_rendering_overview.md Co-Authored-By: Claude Opus 5.5 --- core/materialsystem1/MaterialSystem.cpp | 22 ++++++++++++++----- docs/public_rendering_overview.md | 5 +++++ public/materialsystem1/renderers/IGPUBuffer.h | 12 +++++----- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/core/materialsystem1/MaterialSystem.cpp b/core/materialsystem1/MaterialSystem.cpp index 281da8a10..b5df235c6 100644 --- a/core/materialsystem1/MaterialSystem.cpp +++ b/core/materialsystem1/MaterialSystem.cpp @@ -1556,6 +1556,20 @@ GPUBufferView CMaterialSystem::GetTransientUniformBuffer(const void* data, int64 TransientBufferCollection& collection = m_transientUniformBuffers; + // Buffers are switched only when the current one is full. Views handed out earlier stay valid + // until the ring wraps around, even when their draw is recorded into a command buffer that is + // submitted after many internal buffer commits. + if (data && size > 0) + { + ASSERT(size <= maxTransientBufferSize); + const int64 alignedOffset = AlignBufferSize(collection.bufferOffsets[collection.bufferIdx], bufferAlignment); + if (alignedOffset + size > maxTransientBufferSize) + { + collection.bufferIdx = (collection.bufferIdx + 1) % elementsOf(collection.buffers); + collection.bufferOffsets[collection.bufferIdx] = 0; + } + } + const int bufferIndex = collection.bufferIdx; IGPUBufferPtr& buffer = collection.buffers[bufferIndex]; if (!buffer) @@ -1599,16 +1613,12 @@ void CMaterialSystem::QueueCommitInternalBuffers() buffers.append(submitBuf); } + // transient buffers are written from job threads + CScopedMutex m(s_matSystemBufferMutex); if (m_bufferCmdRecorder) { buffers.append(m_bufferCmdRecorder->End()); m_bufferCmdRecorder = nullptr; - - { - TransientBufferCollection& collection = m_transientUniformBuffers; - collection.bufferOffsets[collection.bufferIdx] = 0; - collection.bufferIdx = (collection.bufferIdx + 1) % elementsOf(collection.buffers); - } m_cameraChangeId += 8192; } } diff --git a/docs/public_rendering_overview.md b/docs/public_rendering_overview.md index 2db6bebf9..a1ea246e8 100644 --- a/docs/public_rendering_overview.md +++ b/docs/public_rendering_overview.md @@ -70,6 +70,11 @@ Main responsibilities: `SetupOrtho`, `GetViewProjection`, `GetCameraParams`; `SetFogInfo`. - **Helpers:** `GetDynamicMesh()`, `GetTransientUniformBuffer`, `GetWhiteTexture`, `GetErrorCheckerboardTexture`, `GetShaderAPI()` (RHI access). +- **Transient uniform data:** `GetTransientUniformBuffer(data, size)` is thread safe and returns a + view into a ring of eight 512 KB buffers. The data is written by a command buffer that is queued + before the next submitted command buffers, so the view is valid in any command buffer submitted + later; the ring moves to the next buffer only when the current one is full, so a view stays + valid until about 4 MB more transient data is written. - **Device loss:** `AddDestroyLostCallbacks` / `RemoveLostRestoreCallbacks`. ## Materials — `IMaterial.h`, `IMaterialVar.h` diff --git a/public/materialsystem1/renderers/IGPUBuffer.h b/public/materialsystem1/renderers/IGPUBuffer.h index 1fbfbeace..1ef4bc795 100644 --- a/public/materialsystem1/renderers/IGPUBuffer.h +++ b/public/materialsystem1/renderers/IGPUBuffer.h @@ -60,15 +60,15 @@ template static T NextBufferOffset(T writeSize, T& offset, T bufferSize, int alignment = 4) { ASSERT(writeSize < bufferSize); - if (offset + writeSize > bufferSize) + + // aligned offset must fit, not the previous end + const T writeOffset = (offset + (alignment - 1)) & ~(alignment - 1); + if (writeOffset + writeSize > bufferSize) { - ASSERT_FAIL("Exceeded buffer size %d, needed %d", bufferSize, offset + writeSize); + ASSERT_FAIL("Exceeded buffer size %d, needed %d", bufferSize, writeOffset + writeSize); return 0; } - offset = (offset + (alignment - 1)) & ~(alignment - 1); - - const T writeOffset = offset; - offset += (writeSize + (alignment - 1)) & ~(alignment - 1); + offset = writeOffset + ((writeSize + (alignment - 1)) & ~(alignment - 1)); return writeOffset; } \ No newline at end of file From 41cd1d16057af8659637dfe432ed5bd8143619f5 Mon Sep 17 00:00:00 2001 From: SoapyMan Date: Tue, 10 Nov 2026 02:27:15 +0500 Subject: [PATCH 03/16] - font: add eqfont2 format (msdf / mtsdf / sdf / psdf atlases from msdf-atlas-gen) with kerning pairs - font: replace sdf flag with EFontType, split LoadFont into LoadFontGrid / LoadFontV1 / LoadFontV2 - matsystem: add MsdfParams to SDFFont shader - font: font cache sets MsdfParams of the SDF font material - tools: add fontconv/msdf_to_eqfont.py, converts msdf-atlas-gen output to eqfont2 .fnt and RGBA8 .dds - docs: describe font file formats and eqfont2 in public_rendering_overview.md, fontconv in tools_overview.md Co-Authored-By: Claude Opus 5.5 --- core/materialsystem1/Shaders/Base/SDFFont.cpp | 3 + docs/public_rendering_overview.md | 45 +++ docs/tools_overview.md | 28 ++ shared/font/Font.cpp | 362 +++++++++++++----- shared/font/Font.h | 33 +- shared/font/FontCache.cpp | 1 + shared/font/FontCache.h | 1 + tools/fontconv/msdf_to_eqfont.py | 237 ++++++++++++ 8 files changed, 605 insertions(+), 105 deletions(-) create mode 100644 tools/fontconv/msdf_to_eqfont.py diff --git a/core/materialsystem1/Shaders/Base/SDFFont.cpp b/core/materialsystem1/Shaders/Base/SDFFont.cpp index 098aaedad..af40b9a92 100644 --- a/core/materialsystem1/Shaders/Base/SDFFont.cpp +++ b/core/materialsystem1/Shaders/Base/SDFFont.cpp @@ -51,6 +51,7 @@ BEGIN_SHADER_CLASS( m_shadowParamsVar = GetMaterialVar("ShadowParams", "[0.94 0.95 0, 1]"); m_shadowColor = GetMaterialVar("ShadowColor", "[0 0 0 1]"); m_shadowOffset = GetMaterialVar("ShadowOffset", "[0 0]"); + m_msdfParams = GetMaterialVar("MsdfParams", "[0 0 0 0]"); } SHADER_INIT_RESOURCES() @@ -174,6 +175,7 @@ BEGIN_SHADER_CLASS( bufferData.append(m_shadowColor.Get()); bufferData.append(m_shadowParamsVar.Get()); bufferData.append(Vector4D(m_shadowOffset.Get(), 0.0f)); + bufferData.append(m_msdfParams.Get()); GPUBufferView cameraParamsBuffer; for (const RenderBufferInfo& rendBuffer : setupParams.uniformBuffers) @@ -220,4 +222,5 @@ BEGIN_SHADER_CLASS( MatVec4Proxy m_shadowColor; MatVec4Proxy m_shadowParamsVar; MatVec2Proxy m_shadowOffset; + MatVec4Proxy m_msdfParams; END_SHADER_CLASS \ No newline at end of file diff --git a/docs/public_rendering_overview.md b/docs/public_rendering_overview.md index a1ea246e8..60bf94d0b 100644 --- a/docs/public_rendering_overview.md +++ b/docs/public_rendering_overview.md @@ -290,6 +290,51 @@ const float width = font->GetStringWidth(L"Some text", params); `TEXT_STYLE_USE_TAGS`, `TEXT_STYLE_SCISSOR`, `TEXT_STYLE_UPPERCASE`, `TEXT_STYLE_LOWERCASE`. - Tags (with `TEXT_STYLE_USE_TAGS`): `&#RRGGBB;text&;` — colored text; `&;` closes the tag. Only color is supported. +- Kerning pairs of `eqfont2` fonts are applied by `GetStringWidth` and text drawing. - Custom layouts: implement `ITextLayoutBuilder` (`OnNewLine`, `LayoutChar`) and set it in `params.layoutBuilder`; `CRectangleTextLayoutBuilder` (`shared/font/FontLayoutBuilders.h`) wraps text inside a rectangle. + +### Font file formats + +`CFont::LoadFont` detects the format by the root section of the `.fnt` file: + +| Root section | Source | Rendering | +|---|---|---| +| `Font` | fixed grid bitmap font | legacy SDF | +| `eqfont` | customized BMFont (`isSDF 1` for its outer-distance SDF) | bitmap or legacy SDF | +| `eqfont2` | msdf-atlas-gen + `tools/fontconv/msdf_to_eqfont.py` ([tools_overview.md](tools_overview.md)) | MSDF / MTSDF / SDF | + +All of them are drawn with the `SDFFont` shader (`_sdfRegular` material of the font cache); +`FontParams.w` selects the legacy or the `eqfont2` path. + +### eqfont2 (MSDF) fonts + +``` +eqfont2 +{ + type "mtsdf"; // msdf, mtsdf, sdf or psdf + texture "ui/fonts/roboto"; // atlas texture, materials path + size 48; // atlas pixels per em + distanceRange 8; // distance range in atlas pixels + lineheight 1.171875; // metrics are in ems + ascender 0.927734; + descender 0.244141; + // unicode advance [plane left top right bottom] [atlas left top right bottom] + glyph 32 0.249023; + glyph 33 0.271973 -0.027018 -0.802083 0.306315 0.09375 1899.5 530.5 1915.5 573.5; + kern 65 86 -0.05; // first second advance (ems) +} +``` + +- Plane bounds use a Y-down axis with the origin at the baseline; atlas bounds are in atlas + pixels from the top-left corner. Glyphs without bounds (spaces) only advance. +- `FontStyleParam::scale` is the em size in screen pixels; line height, baseline offset, advances + and kerning are scaled by it. +- The edge is antialiased over one screen pixel at any scale (the shader derives the screen-space + distance range from `distanceRange` and texture coordinate derivatives), so one atlas covers all + text sizes. +- `textWeight` moves the edge outwards (bolder) in normalized distance, `0.5` is the whole outer + half of the range. `shadowWeight` expands and softens the shadow by the same amount; + `shadowOffset` is in screen pixels. MTSDF fonts draw the shadow from the true SDF in alpha. +- `r_font_sdfStart` / `r_font_sdfRange` affect only legacy `eqfont` SDF fonts. diff --git a/docs/tools_overview.md b/docs/tools_overview.md index 2228994b3..69d08586d 100644 --- a/docs/tools_overview.md +++ b/docs/tools_overview.md @@ -18,6 +18,7 @@ commands and ConVars can be passed with `+name value` on the command line. | `shadercooker` | console | `ShaderCooker.CONFIG` + Slang shader sources | Shader packages for RHI backends (`.shd`, DPK format) | | `texcooker` | console | `TextureCooker.CONFIG` + materials + source images + `.atl` atlas descriptions | Batch-converted textures (`.dds`) via external converters, texture atlases (`.atlas` + material) | | `localization_tool` | GUI (C#, WinForms) | `resources/text_/*.txt` | Edited localization files | +| `fontconv/msdf_to_eqfont.py` | Python 3 script | msdf-atlas-gen JSON layout + PNG atlas | `eqfont2` `.fnt` files, uncompressed RGBA8 `.dds` atlas | ## egfCA — EGF compiler (`tools/egfca`) @@ -149,6 +150,33 @@ The tool writes the packed source image, a material (`.mat`) and an `.atlas` fil rectangles (`atlasgroup`); the packed image is then converted like any other texture. Materials with an `.atlas` file expose the rectangles through `IMaterial::GetAtlas()`. +## MSDF font converter (`tools/fontconv`) + +`msdf_to_eqfont.py` converts the output of +[msdf-atlas-gen](https://github.com/Chlumsky/msdf-atlas-gen) (v1.4) into `eqfont2` font files +(format: [public_rendering_overview.md](public_rendering_overview.md#eqfont2-msdf-fonts)). + +``` +msdf-atlas-gen -font Roboto-Regular.ttf -charset charset.txt -fontname Roboto-Regular + -and -font Roboto-Bold.ttf -charset charset.txt -fontname Roboto-Bold + -type mtsdf -size 48 -pxrange 8 -outerpxpadding 2 -yorigin top -potr + -format png -imageout roboto.png -json roboto.json +python msdf_to_eqfont.py roboto.json roboto.png -texture ui/fonts/roboto + -fntout /resources/fonts -ddsout /materials/ui/fonts/roboto.dds +``` + +- `-type mtsdf` is preferred: RGB holds the MSDF for sharp edges, alpha holds a true SDF used for + shadows. `msdf`, `sdf` and `psdf` atlases are accepted as well. +- Several fonts joined with `-and` share one atlas; the script writes one `.fnt` per font, named + by its `-fontname`. With a single font the name comes from `-name`, `-fontname` or the JSON file + name. +- `-pxrange` limits how far `textWeight` / `shadowWeight` can move the edge (half the range on + each side); `-outerpxpadding` keeps shadow samples (offset by `shadowOffset`) from reaching + neighbor glyphs. +- The atlas is written as uncompressed RGBA8 DDS: block compression breaks the distance channels. +- msdf-atlas-gen reads kerning only from the legacy `kern` table, so fonts with GPOS-only kerning + (for example Roboto) get no kerning pairs. + ## Localization tool (`tools/localization_tool`) C# WinForms application (`EqLocalizationTool.sln`, built separately from premake) for editing diff --git a/shared/font/Font.cpp b/shared/font/Font.cpp index ed087dc34..f8faeb5c2 100644 --- a/shared/font/Font.cpp +++ b/shared/font/Font.cpp @@ -28,10 +28,24 @@ DECLARE_CVAR(r_font_sdfRange, "0.06", nullptr, CV_CHEAT); static bool IsVisibleChar( int ch ) { - return (ch != '\n') && + return (ch != '\n') && (ch != '\r'); } +static int ApplyCharCase( int chrId, const FontStyleParam& params ) +{ + if (params.styleFlag & TEXT_STYLE_UPPERCASE) + return CType::UpperChar(chrId); + else if (params.styleFlag & TEXT_STYLE_LOWERCASE) + return CType::LowerChar(chrId); + return chrId; +} + +static uint KerningPairKey( int firstChrId, int secondChrId ) +{ + return (static_cast(firstChrId & 0xFFFF) << 16) | static_cast(secondChrId & 0xFFFF); +} + //----------------------------------------------------------------------------------------- class CPlainTextLayoutBuilder : public ITextLayoutBuilder @@ -104,7 +118,6 @@ static CPlainTextLayoutBuilder s_defaultTextLayout; //----------------------------------------------------------------------------------------- CFont::CFont() { - memset(&m_flags, 1, sizeof(m_flags)); } float CFont::GetStringWidth( const char* str, const FontStyleParam& params, int charCount, int breakOnChar) const @@ -125,7 +138,7 @@ float CFont::GetStringWidth( const wchar_t* str, const FontStyleParam& params, i float CFont::GetLineHeight( const FontStyleParam& params ) const { - if(m_flags.sdf) // only scale SDF characters + if(IsDistanceField()) // only scale SDF characters return m_lineHeight * params.scale.y; return m_lineHeight; @@ -133,12 +146,25 @@ float CFont::GetLineHeight( const FontStyleParam& params ) const float CFont::GetBaselineOffs( const FontStyleParam& params ) const { - if(m_flags.sdf) // only scale SDF characters + if(IsDistanceField()) // only scale SDF characters return m_baseline * params.scale.y; return m_baseline; } +float CFont::GetKerning( int firstChrId, int secondChrId, const FontStyleParam& params ) const +{ + if (m_kerning.isEmpty() || firstChrId == 0) + return 0.0f; + + auto it = m_kerning.find(KerningPairKey(ApplyCharCase(firstChrId, params), ApplyCharCase(secondChrId, params))); + if (it.atEnd()) + return 0.0f; + + // kerning is stored in ems, same as advance + return *it * params.scale.x; +} + enum class ECharMode { NORMAL = 0, @@ -244,6 +270,7 @@ float CFont::_GetStringWidth( const CHAR_T* str, const FontStyleParam& params, i float totalWidth = 0.0f; int count = 0; + int prevChr = 0; auto AddCharWidth = [&](const CHAR_T* str, const FontStyleParam& fontStyle) -> bool { if (count >= charCount) return false; @@ -252,7 +279,13 @@ float CFont::_GetStringWidth( const CHAR_T* str, const FontStyleParam& params, i return false; if (!IsVisibleChar(*str)) + { + prevChr = 0; return true; + } + + totalWidth += GetKerning(prevChr, *str, fontStyle); + prevChr = *str; FontChar chr; GetScaledCharacter(chr, *str, fontStyle); @@ -421,6 +454,7 @@ void CFont::BuildCharVertexBuffer(CMeshBuilder& builder, const CHAR_T* str, cons Vector2D curStartPos = textPos; bool hasNewLine = true; int lineNumber = 0; + int prevChr = 0; auto DrawFontCharacter = [&](const CHAR_T* str, const FontStyleParam& fontStyle) -> bool { // @@ -436,12 +470,16 @@ void CFont::BuildCharVertexBuffer(CMeshBuilder& builder, const CHAR_T* str, cons { lineNumber++; hasNewLine = true; + prevChr = 0; return true; } if (!IsVisibleChar(*str)) return true; + curStartPos.x += GetKerning(prevChr, *str, fontStyle); + prevChr = *str; + // // Render part - text filling // @@ -453,7 +491,7 @@ void CFont::BuildCharVertexBuffer(CMeshBuilder& builder, const CHAR_T* str, cons Vector2D cPos(curStartPos.x + chr.ofsX, curStartPos.y - baseLine + chr.ofsY); Vector2D cSize(chr.x1 - chr.x0, chr.y1 - chr.y0); - if (m_flags.sdf) // only scale SDF characters + if (IsDistanceField()) // only scale SDF characters cSize *= m_scale * fontStyle.scale; if (!layoutBuilder->LayoutChar(fontStyle, (void*)str, isWideChar, chr, curStartPos, cPos, cSize)) @@ -574,16 +612,50 @@ void CFont::SetupDrawTextMeshBuffer(RenderDrawCmd& drawCmd, const FontStyleParam MatVec4Proxy& shadowColor = fontCache->m_shadowColor; MatVec4Proxy& shadowSdfRange = fontCache->m_shadowParams; MatVec2Proxy& shadowOffset = fontCache->m_shadowOffset; + MatVec4Proxy& msdfParams = fontCache->m_msdfParams; baseColor.Set(color_white); + if (IsMSDF()) + { + // FontParams.w >= 2 selects the eqfont2 distance field path in the shader (3 - use alpha SDF). + // Weights are offsets of the edge in normalized distance (0.5 is the glyph edge) + sdfRange.Set(Vector4D(params.textWeight, 0.0f, 1.0f, 2.0f)); + msdfParams.Set(Vector4D(m_distanceRange * m_invTexSize, 0.0f, 0.0f)); + + if ((params.styleFlag & TEXT_STYLE_SHADOW) && params.shadowAlpha > 0.0f) + { + // shadow offset is in screen pixels, convert it to atlas texture coordinates + const Vector2D screenPixelsPerAtlasPixel = m_scale * params.scale; + const Vector2D atlasPixelsPerScreenPixel(1.0f / max(screenPixelsPerAtlasPixel.x, F_EPS), 1.0f / max(screenPixelsPerAtlasPixel.y, F_EPS)); + shadowColor.Set(ColorRGBA(params.shadowColor, params.shadowAlpha)); + shadowOffset.Set(params.shadowOffset * atlasPixelsPerScreenPixel * m_invTexSize); + + // shadow weight expands and softens the shadow like legacy SDF fonts do. + // MTSDF keeps a true SDF in alpha which has no corner artifacts when expanded + shadowSdfRange.Set(Vector4D(params.shadowWeight, params.shadowWeight, 0.0f, (m_type == FONT_TYPE_MTSDF) ? 3.0f : 2.0f)); + } + else + shadowColor.Set(vec4_zero); + + MatSysDefaultRenderPass defaultRenderPass; + defaultRenderPass.blendMode = SHADER_BLEND_TRANSLUCENT; + defaultRenderPass.texture = m_fontTexture; + + RenderPassContext defaultPassContext(rendPassRecorder, &defaultRenderPass); + g_matSystem->SetupDrawCommand(drawCmd, defaultPassContext); + return; + } + + msdfParams.Set(vec4_zero); + // draw shadow if ((params.styleFlag & TEXT_STYLE_SHADOW) && params.shadowAlpha > 0.0f) { shadowColor.Set(ColorRGBA(params.shadowColor, params.shadowAlpha)); shadowOffset.Set(params.shadowOffset / m_fontTexture->GetSize().xy()); - if (m_flags.sdf) + if (IsDistanceField()) { // shadow width const float sdfEndClamped = clamp(r_font_sdfRange.GetFloat() + params.shadowWeight, 0.0f, 1.0f - r_font_sdfStart.GetFloat()); @@ -595,7 +667,7 @@ void CFont::SetupDrawTextMeshBuffer(RenderDrawCmd& drawCmd, const FontStyleParam else shadowColor.Set(vec4_zero); - if (m_flags.sdf) + if (IsDistanceField()) { const float sdfEndClamped = clamp(r_font_sdfRange.GetFloat() + params.textWeight, 0.0f, 1.0f - r_font_sdfStart.GetFloat()); sdfRange.Set(Vector4D(r_font_sdfStart.GetFloat() - params.textWeight, sdfEndClamped, 1.0f, 0.0f)); @@ -639,7 +711,7 @@ void CFont::GetScaledCharacter( FontChar& chr, const int chrId, const FontStyleP chr = GetFontCharById(charId); - if(m_flags.sdf) // only scale SDF characters + if(IsDistanceField()) // only scale SDF characters { chr.advX = chr.advX * params.scale.x; chr.ofsX = chr.ofsX * params.scale.x; @@ -706,131 +778,221 @@ bool CFont::LoadFont( const char* filenamePrefix ) return false; } - const KVSection* fontSec = kvs.FindSection("Font", KV_FLAG_SECTION); - if(fontSec) + if (const KVSection* fontSec = kvs.FindSection("Font", KV_FLAG_SECTION)) + return LoadFontGrid(fontSec, finalFileName); + + if (const KVSection* fontSec = kvs.FindSection("eqFont")) + return LoadFontV1(fontSec, finalFileName); + + if (const KVSection* fontSec = kvs.FindSection("eqfont2", KV_FLAG_SECTION)) + return LoadFontV2(fontSec, finalFileName); + + MsgError("ERROR: '%s' is not a valid font file\n", finalFileName.ToCString()); + + return false; +} + +// loads the texture from the 'texture' key (font name by default) +bool CFont::LoadFontTexture(const KVSection* fontSec, const SamplerStateParams& samplerParams, const char* finalFileName) +{ + const EqString textureName = KV_GetValueString(fontSec->FindSection("texture"), 0, m_name.ToCString()); + m_fontTexture = g_texLoader->LoadTextureFromFileSync(textureName, samplerParams, TEXFLAG_IGNORE_QUALITY, finalFileName); + + if (m_fontTexture == nullptr) { - const int charWide = KV_GetValueInt(fontSec->FindSection("charWidth"), 0, 8); - const int charTall = KV_GetValueInt(fontSec->FindSection("charHeight"), 0, 8); - const int charsPerLine = KV_GetValueInt(fontSec->FindSection("charsPerLine"), 0, 16); - const float interval = KV_GetValueFloat(fontSec->FindSection("interval"), 0, 0.75); + MsgError("ERROR: no texture for font '%s'\n", finalFileName); + return false; + } - { - const EqString textureName = KV_GetValueString(fontSec->FindSection("texture"), 0, filenamePrefix); - const bool filterTexture = KV_GetValueBool(fontSec->FindSection("filterFontTexture")); - SamplerStateParams samplerParams(filterTexture ? TEXFILTER_LINEAR : TEXFILTER_NEAREST, TEXADDRESS_WRAP); - m_fontTexture = g_texLoader->LoadTextureFromFileSync(textureName, samplerParams, TEXFLAG_IGNORE_QUALITY, finalFileName); - } + m_invTexSize = 1.0f / m_fontTexture->GetSize().xy(); + return true; +} - if (m_fontTexture == nullptr) +// 'Font' - fixed size glyph grid of 256 characters +bool CFont::LoadFontGrid(const KVSection* fontSec, const char* finalFileName) +{ + const int charWide = KV_GetValueInt(fontSec->FindSection("charWidth"), 0, 8); + const int charTall = KV_GetValueInt(fontSec->FindSection("charHeight"), 0, 8); + const int charsPerLine = KV_GetValueInt(fontSec->FindSection("charsPerLine"), 0, 16); + const float interval = KV_GetValueFloat(fontSec->FindSection("interval"), 0, 0.75); + + // grid fonts are scaled by FontStyleParam::scale and shaded like legacy SDF fonts + m_type = FONT_TYPE_SDF; + + const bool filterTexture = KV_GetValueBool(fontSec->FindSection("filterFontTexture")); + if (!LoadFontTexture(fontSec, SamplerStateParams(filterTexture ? TEXFILTER_LINEAR : TEXFILTER_NEAREST, TEXADDRESS_WRAP), finalFileName)) + return false; + + m_spacing = KV_GetValueFloat(fontSec->FindSection("spacing")); + m_baseline = charTall; + m_lineHeight = charTall + 4; + + int line = 0; + int lChars = 0; + for (int i = 0; i < 256; i++) + { + if (lChars == charsPerLine) { - MsgError("ERROR: no texture for font '%s'\n", finalFileName.GetData()); - return false; + line++; + lChars = 0; } - m_invTexSize = 1.0f / m_fontTexture->GetSize().xy(); + FontChar& chr = m_charMap[i]; - m_spacing = KV_GetValueFloat(fontSec->FindSection("spacing")); - m_baseline = charTall; - m_lineHeight = charTall + 4; + const float CurCharPos_x = lChars * charTall; + const float CurCharPos_y = line * charTall; - int line = 0; - int lChars = 0; - for (int i = 0; i < 256; i++) - { - if (lChars == charsPerLine) - { - line++; - lChars = 0; - } + chr.x0 = CurCharPos_x + interval; // LineCharCount * interval + chr.x1 = CurCharPos_x + interval + charWide; + chr.y0 = CurCharPos_y + interval; // Line Count * height + chr.y1 = CurCharPos_y + interval + charTall; + + chr.advX = (chr.x1 - chr.x0) + m_spacing; + chr.ofsX = 0; + chr.ofsY = 0; + + lChars++; + } - FontChar& chr = m_charMap[i]; + return true; +} - const float CurCharPos_x = lChars * charTall; - const float CurCharPos_y = line * charTall; +// 'eqFont' - BMFont export, bitmap or legacy SDF +bool CFont::LoadFontV1(const KVSection* fontSec, const char* finalFileName) +{ + m_type = KV_GetValueBool(fontSec->FindSection("isSDF")) ? FONT_TYPE_SDF : FONT_TYPE_BITMAP; - chr.x0 = CurCharPos_x + interval; // LineCharCount * interval - chr.x1 = CurCharPos_x + interval + charWide; - chr.y0 = CurCharPos_y + interval; // Line Count * height - chr.y1 = CurCharPos_y + interval + charTall; + const bool filterTexture = KV_GetValueBool(fontSec->FindSection("filter")) || IsDistanceField(); + if (!LoadFontTexture(fontSec, SamplerStateParams(filterTexture ? TEXFILTER_LINEAR : TEXFILTER_NEAREST, TEXADDRESS_WRAP), finalFileName)) + return false; - chr.advX = (chr.x1 - chr.x0) + m_spacing; - chr.ofsX = 0; - chr.ofsY = 0; + m_spacing = 0.0f; - lChars++; + if (IsDistanceField()) + m_scale = KV_GetVector2D(fontSec->FindSection("scale")); + + m_baseline = KV_GetValueFloat(fontSec->FindSection("baseline")) * m_scale.y; + m_lineHeight = KV_GetValueFloat(fontSec->FindSection("lineheight")) * m_scale.y; + + for (const KVSection& charSec : fontSec->Keys()) + { + // x y w h ox oy advanceX + // 0 1 2 3 4 5 6 + + FontChar fontChar; + const int valueCount = charSec.GetValues( + fontChar.x0, + fontChar.y0, + fontChar.x1, + fontChar.y1, + fontChar.ofsX, + fontChar.ofsY, + fontChar.advX + ); + + if(valueCount != 7) + { + if(valueCount > 2) + { + ASSERT_FAIL("Invalid font file %s", m_name.ToCString()); + } + continue; } - return true; + fontChar.x1 += fontChar.x0; + fontChar.y1 += fontChar.y0; + + fontChar.ofsX *= m_scale.x; + fontChar.ofsY *= m_scale.y; + fontChar.advX *= m_scale.x; + + const int charIdx = atoi(charSec.GetName()); + m_charMap.insert(charIdx, fontChar); } - fontSec = kvs.FindSection("eqFont"); - if (fontSec) + return true; +} + +// 'eqfont2' is produced from msdf-atlas-gen output by tools/fontconv/msdf_to_eqfont.py. +// Metrics are in ems with Y axis down and origin at the baseline, atlas bounds are in pixels. +bool CFont::LoadFontV2(const KVSection* fontSec, const char* finalFileName) +{ + const EqStringRef atlasType = KV_GetValueString(fontSec->FindSection("type"), 0, "mtsdf"); + if (atlasType == "mtsdf") + m_type = FONT_TYPE_MTSDF; + else if (atlasType == "msdf" || atlasType == "sdf" || atlasType == "psdf") + m_type = FONT_TYPE_MSDF; + else { - m_flags.sdf = KV_GetValueBool(fontSec->FindSection("isSDF")); - m_flags.bold = KV_GetValueBool(fontSec->FindSection("bold")); + MsgError("ERROR: font '%s' has unsupported atlas type '%s'\n", finalFileName, atlasType.ToCString()); + return false; + } - { - const EqString textureName = KV_GetValueString(fontSec->FindSection("texture"), 0, filenamePrefix); - const bool filterTexture = KV_GetValueBool(fontSec->FindSection("filter")) || m_flags.sdf; - SamplerStateParams samplerParams(filterTexture ? TEXFILTER_LINEAR : TEXFILTER_NEAREST, TEXADDRESS_WRAP); - m_fontTexture = g_texLoader->LoadTextureFromFileSync(textureName, samplerParams, TEXFLAG_IGNORE_QUALITY, finalFileName); - } + const float atlasEmSize = KV_GetValueFloat(fontSec->FindSection("size"), 0, 0.0f); + if (atlasEmSize <= 0.0f) + { + MsgError("ERROR: font '%s' has invalid atlas size\n", finalFileName); + return false; + } - if (m_fontTexture == nullptr) - { - MsgError("ERROR: no texture for font '%s'\n", finalFileName.GetData()); - return false; - } + if (!LoadFontTexture(fontSec, SamplerStateParams(TEXFILTER_LINEAR, TEXADDRESS_CLAMP), finalFileName)) + return false; - m_invTexSize = 1.0f / m_fontTexture->GetSize().xy(); - m_spacing = 0.0f; + m_distanceRange = KV_GetValueFloat(fontSec->FindSection("distanceRange"), 0, 2.0f); + m_spacing = 0.0f; - if (m_flags.sdf) - m_scale = KV_GetVector2D(fontSec->FindSection("scale")); + // glyph quads are sized from atlas pixels, FontStyleParam::scale is the em size in pixels + m_scale = Vector2D(1.0f / atlasEmSize); - m_baseline = KV_GetValueFloat(fontSec->FindSection("baseline")) * m_scale.y; - m_lineHeight = KV_GetValueFloat(fontSec->FindSection("lineheight")) * m_scale.y; + const float ascender = KV_GetValueFloat(fontSec->FindSection("ascender")); + m_baseline = ascender; + m_lineHeight = KV_GetValueFloat(fontSec->FindSection("lineheight"), 0, 1.0f); - for (const KVSection& charSec : fontSec->Keys()) + for (const KVSection& keySec : fontSec->Keys()) + { + if (!CString::CompareCaseIns(keySec.GetName(), "glyph")) { - // x y w h ox oy advanceX - // 0 1 2 3 4 5 6 + // unicode advance [planeLeft planeTop planeRight planeBottom atlasLeft atlasTop atlasRight atlasBottom] + int charIdx = 0; + float advance = 0.0f; + float planeLeft = 0.0f, planeTop = 0.0f, planeRight = 0.0f, planeBottom = 0.0f; + float atlasLeft = 0.0f, atlasTop = 0.0f, atlasRight = 0.0f, atlasBottom = 0.0f; - FontChar fontChar; - const int valueCount = charSec.GetValues( - fontChar.x0, - fontChar.y0, - fontChar.x1, - fontChar.y1, - fontChar.ofsX, - fontChar.ofsY, - fontChar.advX - ); - - if(valueCount != 7) + const int valueCount = keySec.GetValues(charIdx, advance, + planeLeft, planeTop, planeRight, planeBottom, + atlasLeft, atlasTop, atlasRight, atlasBottom); + + if (valueCount != 2 && valueCount != 10) { - if(valueCount > 2) - { - ASSERT_FAIL("Invalid font file %s", filenamePrefix); - } + MsgError("ERROR: font '%s' has invalid glyph entry\n", finalFileName); continue; } - fontChar.x1 += fontChar.x0; - fontChar.y1 += fontChar.y0; - - fontChar.ofsX *= m_scale.x; - fontChar.ofsY *= m_scale.y; - fontChar.advX *= m_scale.x; + FontChar fontChar; + fontChar.advX = advance; + if (valueCount == 10) + { + fontChar.x0 = atlasLeft; + fontChar.y0 = atlasTop; + fontChar.x1 = atlasRight; + fontChar.y1 = atlasBottom; + + // text drawing subtracts the baseline offset, compensate it here + fontChar.ofsX = planeLeft; + fontChar.ofsY = planeTop + ascender; + } - const int charIdx = atoi(charSec.GetName()); m_charMap.insert(charIdx, fontChar); } - - return true; + else if (!CString::CompareCaseIns(keySec.GetName(), "kern")) + { + int firstChrId = 0; + int secondChrId = 0; + float kerning = 0.0f; + if (keySec.GetValues(firstChrId, secondChrId, kerning) == 3) + m_kerning.insert(KerningPairKey(firstChrId, secondChrId), kerning); + } } - MsgError("ERROR: '%s' is not a valid font file\n", finalFileName.ToCString()); - - return false; + return true; } \ No newline at end of file diff --git a/shared/font/Font.h b/shared/font/Font.h index e7c976bf0..1ca235caf 100644 --- a/shared/font/Font.h +++ b/shared/font/Font.h @@ -10,11 +10,21 @@ #include "font/IFont.h" class CMeshBuilder; +struct KVSection; struct RenderDrawCmd; struct RenderPassContext; +struct SamplerStateParams; class ITexture; using ITexturePtr = CRefPtr; +enum EFontType : int +{ + FONT_TYPE_BITMAP = 0, // bitmap glyphs, not scaled by FontStyleParam::scale + FONT_TYPE_SDF, // legacy BMFont SDF in alpha, edge set by r_font_sdfStart / r_font_sdfRange + FONT_TYPE_MSDF, // eqfont2 msdf / sdf / psdf atlas, distance is the median of RGB + FONT_TYPE_MTSDF, // eqfont2 mtsdf atlas, MSDF in RGB and true SDF in alpha +}; + class CFont : public IEqFont { friend class CEqConsoleInput; @@ -25,6 +35,9 @@ class CFont : public IEqFont bool LoadFont( const char* filenamePrefix ); + // returns kerning between two characters in pixels + float GetKerning( int firstChrId, int secondChrId, const FontStyleParam& params ) const; + // returns string width in pixels float GetStringWidth( const wchar_t* str, const FontStyleParam& params, int charCount = -1, int breakOnChar = -1) const; float GetStringWidth( const char* str, const FontStyleParam& params, int charCount = -1, int breakOnChar = -1) const; @@ -44,6 +57,18 @@ class CFont : public IEqFont protected: using FontCharMap = Map; + using FontKerningMap = Map; + + bool LoadFontGrid( const KVSection* fontSec, const char* finalFileName ); + bool LoadFontV1( const KVSection* fontSec, const char* finalFileName ); + bool LoadFontV2( const KVSection* fontSec, const char* finalFileName ); + bool LoadFontTexture( const KVSection* fontSec, const SamplerStateParams& samplerParams, const char* finalFileName ); + + // glyphs are scaled by FontStyleParam::scale and drawn with distance field shading + bool IsDistanceField() const { return m_type != FONT_TYPE_BITMAP; } + + // eqfont2 distance field atlas + bool IsMSDF() const { return m_type == FONT_TYPE_MSDF || m_type == FONT_TYPE_MTSDF; } void SetupDrawTextMeshBuffer(RenderDrawCmd& drawCmd, const FontStyleParam& params, IGPURenderPassRecorder* rendPassRecorder); @@ -69,20 +94,18 @@ class CFont : public IEqFont // map of chars FontCharMap m_charMap{ PP_SL }; + FontKerningMap m_kerning{ PP_SL }; EqString m_name; float m_spacing{ 0.0f }; float m_baseline{ 0.0f }; float m_lineHeight{ 0.0f }; + float m_distanceRange{ 0.0f }; // eqfont2 distance range in atlas pixels Vector2D m_scale{ 1.0f }; Vector2D m_invTexSize{ 1.0f }; ITexturePtr m_fontTexture; - struct - { - bool sdf : 1; - bool bold : 2; - } m_flags; + EFontType m_type{ FONT_TYPE_BITMAP }; }; \ No newline at end of file diff --git a/shared/font/FontCache.cpp b/shared/font/FontCache.cpp index beda250fb..735e04917 100644 --- a/shared/font/FontCache.cpp +++ b/shared/font/FontCache.cpp @@ -178,6 +178,7 @@ bool CEqFontCache::Init() m_shadowParams = m_sdfMaterial->GetMaterialVar("ShadowParams", "[0.94 0.95 0, 1]"); m_shadowColor = m_sdfMaterial->GetMaterialVar("ShadowColor", "[0 0 0 1]"); m_shadowOffset = m_sdfMaterial->GetMaterialVar("ShadowOffset", "[0 0]"); + m_msdfParams = m_sdfMaterial->GetMaterialVar("MsdfParams", "[0 0 0 0]"); m_sdfMaterial->LoadShaderAndTextures(); diff --git a/shared/font/FontCache.h b/shared/font/FontCache.h index 439a3d931..3eb05406c 100644 --- a/shared/font/FontCache.h +++ b/shared/font/FontCache.h @@ -68,4 +68,5 @@ class CEqFontCache : public IEqFontCache MatVec4Proxy m_shadowColor; MatVec4Proxy m_shadowParams; MatVec2Proxy m_shadowOffset; + MatVec4Proxy m_msdfParams; }; diff --git a/tools/fontconv/msdf_to_eqfont.py b/tools/fontconv/msdf_to_eqfont.py new file mode 100644 index 000000000..aa1bb9799 --- /dev/null +++ b/tools/fontconv/msdf_to_eqfont.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +#//////////////////////////////////////////////////////////////////////////////// +# Copyright (C) Inspiration Byte +# 2009-2026 +#//////////////////////////////////////////////////////////////////////////////// +# Description: converts msdf-atlas-gen JSON layout and PNG atlas to eqfont2 + DDS +#//////////////////////////////////////////////////////////////////////////////// +# +# Usage: +# msdf_to_eqfont.py -texture +# -fntout [-ddsout ] [-name ] +# +# - layout.json / atlas.png are produced by msdf-atlas-gen (-json, -imageout ... -format png). +# - A JSON with several fonts (msdf-atlas-gen -and) produces one .fnt per font variant; every +# variant needs -fontname, it is used as the .fnt file name. All variants share the texture. +# - The atlas is written as uncompressed RGBA8 DDS: block compression breaks (M)SDF channels. + +import argparse +import json +import os +import struct +import sys +import zlib + +SUPPORTED_ATLAS_TYPES = ("sdf", "psdf", "msdf", "mtsdf") + +#-------------------------------------------------------------------------------- + +def DecodePNG(fileName): + with open(fileName, "rb") as f: + data = f.read() + + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise RuntimeError("%s is not a PNG file" % fileName) + + pos = 8 + width = height = bitDepth = colorType = interlace = 0 + idat = bytearray() + while pos < len(data): + length, chunkType = struct.unpack(">I4s", data[pos:pos + 8]) + chunk = data[pos + 8:pos + 8 + length] + pos += 12 + length + if chunkType == b"IHDR": + width, height, bitDepth, colorType, _, _, interlace = struct.unpack(">IIBBBBB", chunk) + elif chunkType == b"IDAT": + idat += chunk + elif chunkType == b"IEND": + break + + channelsByColorType = { 0: 1, 2: 3, 4: 2, 6: 4 } + if bitDepth != 8 or interlace != 0 or colorType not in channelsByColorType: + raise RuntimeError("%s: only 8-bit non-interlaced gray/RGB/RGBA PNG is supported" % fileName) + + channels = channelsByColorType[colorType] + stride = width * channels + raw = zlib.decompress(bytes(idat)) + + pixels = bytearray(stride * height) + prevRow = bytearray(stride) + src = 0 + for y in range(height): + filterType = raw[src] + src += 1 + row = bytearray(raw[src:src + stride]) + src += stride + + if filterType == 1: + for i in range(channels, stride): + row[i] = (row[i] + row[i - channels]) & 0xFF + elif filterType == 2: + for i in range(stride): + row[i] = (row[i] + prevRow[i]) & 0xFF + elif filterType == 3: + for i in range(stride): + left = row[i - channels] if i >= channels else 0 + row[i] = (row[i] + ((left + prevRow[i]) >> 1)) & 0xFF + elif filterType == 4: + for i in range(stride): + a = row[i - channels] if i >= channels else 0 + b = prevRow[i] + c = prevRow[i - channels] if i >= channels else 0 + p = a + b - c + pa = abs(p - a) + pb = abs(p - b) + pc = abs(p - c) + pred = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) + row[i] = (row[i] + pred) & 0xFF + elif filterType != 0: + raise RuntimeError("%s: invalid PNG filter %d" % (fileName, filterType)) + + pixels[y * stride:(y + 1) * stride] = row + prevRow = row + + # expand to RGBA + if channels == 4: + return width, height, bytes(pixels) + + rgba = bytearray(width * height * 4) + for i in range(width * height): + if channels == 1: + v = pixels[i] + rgba[i * 4:i * 4 + 4] = bytes((v, v, v, 255)) + elif channels == 2: + v = pixels[i * 2] + rgba[i * 4:i * 4 + 4] = bytes((v, v, v, pixels[i * 2 + 1])) + else: + rgba[i * 4:i * 4 + 3] = pixels[i * 3:i * 3 + 3] + rgba[i * 4 + 3] = 255 + return width, height, bytes(rgba) + +def WriteDDS(fileName, width, height, rgba): + DDSD_CAPS = 0x1 + DDSD_HEIGHT = 0x2 + DDSD_WIDTH = 0x4 + DDSD_PITCH = 0x8 + DDSD_PIXELFORMAT = 0x1000 + DDPF_ALPHAPIXELS = 0x1 + DDPF_RGB = 0x40 + DDSCAPS_TEXTURE = 0x1000 + + header = struct.pack("<4sIIIIIII44x", b"DDS ", 124, + DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PITCH | DDSD_PIXELFORMAT, + height, width, width * 4, 0, 0) + + # pixel format: R8G8B8A8 in memory order + header += struct.pack(" ") + + glyphCount = 0 + for glyph in variant["glyphs"]: + if "unicode" not in glyph: + continue + + values = [ str(glyph["unicode"]), FormatFloat(glyph["advance"]) ] + + plane = glyph.get("planeBounds") + atlasBounds = glyph.get("atlasBounds") + if plane and atlasBounds: + planeTop = plane["top"] * ySign + planeBottom = plane["bottom"] * ySign + atlasTop = atlasBounds["top"] if yTop else atlasHeight - atlasBounds["top"] + atlasBottom = atlasBounds["bottom"] if yTop else atlasHeight - atlasBounds["bottom"] + values += [ FormatFloat(v) for v in (plane["left"], planeTop, plane["right"], planeBottom) ] + values += [ FormatFloat(v) for v in (atlasBounds["left"], atlasTop, atlasBounds["right"], atlasBottom) ] + + lines.append("\tglyph %s;" % " ".join(values)) + glyphCount += 1 + + kerning = variant.get("kerning", []) + for pair in kerning: + lines.append("\tkern %d %d %s;" % (pair["unicode1"], pair["unicode2"], FormatFloat(pair["advance"]))) + + lines.append("}") + + os.makedirs(os.path.dirname(os.path.abspath(fileName)), exist_ok=True) + with open(fileName, "w", newline="\n", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + + print("%s: %d glyphs, %d kerning pairs" % (fileName, glyphCount, len(kerning))) + +#-------------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser(description="Convert msdf-atlas-gen output to eqfont2 font files") + parser.add_argument("json", help="msdf-atlas-gen JSON layout file") + parser.add_argument("png", nargs="?", help="msdf-atlas-gen PNG atlas image (optional if -ddsout is not used)") + parser.add_argument("-texture", required=True, help="texture name written to the font file (materials path, no extension)") + parser.add_argument("-fntout", required=True, help="output folder for .fnt files") + parser.add_argument("-ddsout", help="output .dds file of the atlas") + parser.add_argument("-name", help="font file name for a single-font atlas (default: JSON name or file name)") + args = parser.parse_args() + + with open(args.json, "r", encoding="utf-8") as f: + layout = json.load(f) + + atlas = layout["atlas"] + if atlas["type"] not in SUPPORTED_ATLAS_TYPES: + print("Unsupported atlas type '%s', supported: %s" % (atlas["type"], ", ".join(SUPPORTED_ATLAS_TYPES))) + return 1 + + if "variants" in layout: + for variant in layout["variants"]: + if not variant.get("name"): + print("Every font of a multi-font atlas needs -fontname in msdf-atlas-gen") + return 1 + WriteFont(os.path.join(args.fntout, variant["name"] + ".fnt"), args.texture, atlas, variant) + else: + name = args.name or layout.get("name") or os.path.splitext(os.path.basename(args.json))[0] + WriteFont(os.path.join(args.fntout, name + ".fnt"), args.texture, atlas, layout) + + if args.ddsout: + if not args.png: + print("PNG atlas is required to write DDS") + return 1 + width, height, rgba = DecodePNG(args.png) + if width != atlas["width"] or height != atlas["height"]: + print("Atlas image size %dx%d does not match JSON %dx%d" % (width, height, atlas["width"], atlas["height"])) + return 1 + WriteDDS(args.ddsout, width, height, rgba) + print("%s: %dx%d RGBA8" % (args.ddsout, width, height)) + + return 0 + +if __name__ == "__main__": + sys.exit(main()) From d3dd3ad5599abb475e2f9e6ced129a0a5e8e43f0 Mon Sep 17 00:00:00 2001 From: SoapyMan Date: Tue, 10 Nov 2026 03:21:13 +0500 Subject: [PATCH 04/16] - deps: add msdfgen 1.13 core as static library - texcooker: generate MSDF / MTSDF / SDF / PSDF font atlases and eqfont2 .fnt files from .font descriptions - texcooker: rasterize glyphs with stb_truetype and msdfgen, pack them with stb_rect_pack, read kerning - texcooker: read charset as key-values (chars, range, code) from files or inline in .font - texcooker: add font atlas textures to materialsSRC/_fonts.mat with usage:fonts for the DDS pass - docs: describe .font files and charsets in tools_overview.md Co-Authored-By: Claude Opus 5.5 --- docs/tools_overview.md | 47 +- src_dependency/msdfgen/LICENSE.txt | 21 + src_dependency/msdfgen/msdfgen/core/Bitmap.h | 60 ++ .../msdfgen/msdfgen/core/Bitmap.hpp | 172 ++++ .../msdfgen/msdfgen/core/BitmapRef.hpp | 154 +++ .../msdfgen/msdfgen/core/Contour.cpp | 90 ++ src_dependency/msdfgen/msdfgen/core/Contour.h | 34 + .../msdfgen/msdfgen/core/DistanceMapping.cpp | 27 + .../msdfgen/msdfgen/core/DistanceMapping.h | 36 + .../msdfgen/msdfgen/core/EdgeColor.h | 20 + .../msdfgen/msdfgen/core/EdgeHolder.cpp | 67 ++ .../msdfgen/msdfgen/core/EdgeHolder.h | 41 + .../msdfgen/core/MSDFErrorCorrection.cpp | 496 ++++++++++ .../msdfgen/core/MSDFErrorCorrection.h | 55 ++ .../msdfgen/msdfgen/core/Projection.cpp | 42 + .../msdfgen/msdfgen/core/Projection.h | 37 + src_dependency/msdfgen/msdfgen/core/Range.hpp | 46 + .../msdfgen/msdfgen/core/SDFTransformation.h | 24 + .../msdfgen/msdfgen/core/Scanline.cpp | 125 +++ .../msdfgen/msdfgen/core/Scanline.h | 56 ++ src_dependency/msdfgen/msdfgen/core/Shape.cpp | 208 ++++ src_dependency/msdfgen/msdfgen/core/Shape.h | 60 ++ .../msdfgen/core/ShapeDistanceFinder.h | 37 + .../msdfgen/core/ShapeDistanceFinder.hpp | 60 ++ .../msdfgen/msdfgen/core/SignedDistance.hpp | 38 + .../msdfgen/msdfgen/core/Vector2.hpp | 167 ++++ .../msdfgen/msdfgen/core/YAxisOrientation.h | 17 + .../msdfgen/msdfgen/core/arithmetics.hpp | 63 ++ src_dependency/msdfgen/msdfgen/core/base.h | 16 + .../msdfgen/core/bitmap-interpolation.hpp | 27 + .../msdfgen/core/contour-combiners.cpp | 141 +++ .../msdfgen/msdfgen/core/contour-combiners.h | 47 + .../core/convergent-curve-ordering.cpp | 140 +++ .../msdfgen/core/convergent-curve-ordering.h | 11 + .../msdfgen/msdfgen/core/edge-coloring.cpp | 531 ++++++++++ .../msdfgen/msdfgen/core/edge-coloring.h | 29 + .../msdfgen/msdfgen/core/edge-segments.cpp | 533 +++++++++++ .../msdfgen/msdfgen/core/edge-segments.h | 146 +++ .../msdfgen/msdfgen/core/edge-selectors.cpp | 262 +++++ .../msdfgen/msdfgen/core/edge-selectors.h | 117 +++ .../msdfgen/msdfgen/core/equation-solver.cpp | 72 ++ .../msdfgen/msdfgen/core/equation-solver.h | 14 + .../msdfgen/msdfgen/core/export-svg.cpp | 79 ++ .../msdfgen/msdfgen/core/export-svg.h | 11 + .../msdfgen/msdfgen/core/generator-config.h | 66 ++ .../msdfgen/core/msdf-error-correction.cpp | 183 ++++ .../msdfgen/core/msdf-error-correction.h | 40 + .../msdfgen/msdfgen/core/msdfgen.cpp | 335 +++++++ .../msdfgen/msdfgen/core/pixel-conversion.hpp | 16 + .../msdfgen/msdfgen/core/rasterization.cpp | 128 +++ .../msdfgen/msdfgen/core/rasterization.h | 28 + .../msdfgen/msdfgen/core/render-sdf.cpp | 194 ++++ .../msdfgen/msdfgen/core/render-sdf.h | 23 + .../msdfgen/msdfgen/core/save-bmp.cpp | 233 +++++ .../msdfgen/msdfgen/core/save-bmp.h | 16 + .../msdfgen/msdfgen/core/save-fl32.cpp | 41 + .../msdfgen/msdfgen/core/save-fl32.h | 12 + .../msdfgen/msdfgen/core/save-rgba.cpp | 139 +++ .../msdfgen/msdfgen/core/save-rgba.h | 16 + .../msdfgen/msdfgen/core/save-tiff.cpp | 195 ++++ .../msdfgen/msdfgen/core/save-tiff.h | 13 + .../msdfgen/core/sdf-error-estimation.cpp | 204 ++++ .../msdfgen/core/sdf-error-estimation.h | 33 + .../msdfgen/core/shape-description.cpp | 335 +++++++ .../msdfgen/msdfgen/core/shape-description.h | 15 + src_dependency/msdfgen/msdfgen/msdfgen.h | 78 ++ src_dependency/msdfgen/premake5.lua | 29 + src_dependency/premake5.lua | 1 + tools/premake5.lua | 3 +- tools/texcooker/FontAtlasGenerator.cpp | 906 ++++++++++++++++++ tools/texcooker/TextureBatchCooker.cpp | 12 +- tools/texcooker/texcooker_defs.h | 4 + 72 files changed, 7771 insertions(+), 3 deletions(-) create mode 100644 src_dependency/msdfgen/LICENSE.txt create mode 100644 src_dependency/msdfgen/msdfgen/core/Bitmap.h create mode 100644 src_dependency/msdfgen/msdfgen/core/Bitmap.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/BitmapRef.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/Contour.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/Contour.h create mode 100644 src_dependency/msdfgen/msdfgen/core/DistanceMapping.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/DistanceMapping.h create mode 100644 src_dependency/msdfgen/msdfgen/core/EdgeColor.h create mode 100644 src_dependency/msdfgen/msdfgen/core/EdgeHolder.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/EdgeHolder.h create mode 100644 src_dependency/msdfgen/msdfgen/core/MSDFErrorCorrection.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/MSDFErrorCorrection.h create mode 100644 src_dependency/msdfgen/msdfgen/core/Projection.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/Projection.h create mode 100644 src_dependency/msdfgen/msdfgen/core/Range.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/SDFTransformation.h create mode 100644 src_dependency/msdfgen/msdfgen/core/Scanline.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/Scanline.h create mode 100644 src_dependency/msdfgen/msdfgen/core/Shape.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/Shape.h create mode 100644 src_dependency/msdfgen/msdfgen/core/ShapeDistanceFinder.h create mode 100644 src_dependency/msdfgen/msdfgen/core/ShapeDistanceFinder.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/SignedDistance.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/Vector2.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/YAxisOrientation.h create mode 100644 src_dependency/msdfgen/msdfgen/core/arithmetics.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/base.h create mode 100644 src_dependency/msdfgen/msdfgen/core/bitmap-interpolation.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/contour-combiners.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/contour-combiners.h create mode 100644 src_dependency/msdfgen/msdfgen/core/convergent-curve-ordering.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/convergent-curve-ordering.h create mode 100644 src_dependency/msdfgen/msdfgen/core/edge-coloring.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/edge-coloring.h create mode 100644 src_dependency/msdfgen/msdfgen/core/edge-segments.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/edge-segments.h create mode 100644 src_dependency/msdfgen/msdfgen/core/edge-selectors.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/edge-selectors.h create mode 100644 src_dependency/msdfgen/msdfgen/core/equation-solver.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/equation-solver.h create mode 100644 src_dependency/msdfgen/msdfgen/core/export-svg.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/export-svg.h create mode 100644 src_dependency/msdfgen/msdfgen/core/generator-config.h create mode 100644 src_dependency/msdfgen/msdfgen/core/msdf-error-correction.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/msdf-error-correction.h create mode 100644 src_dependency/msdfgen/msdfgen/core/msdfgen.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/pixel-conversion.hpp create mode 100644 src_dependency/msdfgen/msdfgen/core/rasterization.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/rasterization.h create mode 100644 src_dependency/msdfgen/msdfgen/core/render-sdf.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/render-sdf.h create mode 100644 src_dependency/msdfgen/msdfgen/core/save-bmp.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/save-bmp.h create mode 100644 src_dependency/msdfgen/msdfgen/core/save-fl32.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/save-fl32.h create mode 100644 src_dependency/msdfgen/msdfgen/core/save-rgba.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/save-rgba.h create mode 100644 src_dependency/msdfgen/msdfgen/core/save-tiff.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/save-tiff.h create mode 100644 src_dependency/msdfgen/msdfgen/core/sdf-error-estimation.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/sdf-error-estimation.h create mode 100644 src_dependency/msdfgen/msdfgen/core/shape-description.cpp create mode 100644 src_dependency/msdfgen/msdfgen/core/shape-description.h create mode 100644 src_dependency/msdfgen/msdfgen/msdfgen.h create mode 100644 src_dependency/msdfgen/premake5.lua create mode 100644 tools/texcooker/FontAtlasGenerator.cpp diff --git a/docs/tools_overview.md b/docs/tools_overview.md index 69d08586d..c66c393e7 100644 --- a/docs/tools_overview.md +++ b/docs/tools_overview.md @@ -16,7 +16,7 @@ commands and ConVars can be passed with `+name value` on the command line. | `egfMan2` | GUI (sysLib + ImGui, Windows) | `.egf`, `.mop`, `.pod` | — (viewer) | | `fcompress` | console | `PackageCooker.CONFIG` | `.epk` packages | | `shadercooker` | console | `ShaderCooker.CONFIG` + Slang shader sources | Shader packages for RHI backends (`.shd`, DPK format) | -| `texcooker` | console | `TextureCooker.CONFIG` + materials + source images + `.atl` atlas descriptions | Batch-converted textures (`.dds`) via external converters, texture atlases (`.atlas` + material) | +| `texcooker` | console | `TextureCooker.CONFIG` + materials + source images + `.atl` atlas descriptions + `.font` font descriptions | Batch-converted textures (`.dds`) via external converters, texture atlases (`.atlas` + material), `eqfont2` fonts | | `localization_tool` | GUI (C#, WinForms) | `resources/text_/*.txt` | Edited localization files | | `fontconv/msdf_to_eqfont.py` | Python 3 script | msdf-atlas-gen JSON layout + PNG atlas | `eqfont2` `.fnt` files, uncompressed RGBA8 `.dds` atlas | @@ -150,6 +150,51 @@ The tool writes the packed source image, a material (`.mat`) and an `.atlas` fil rectangles (`atlasgroup`); the packed image is then converted like any other texture. Materials with an `.atlas` file expose the rectangles through `IMaterial::GetAtlas()`. +### Font atlases + +Font description files (`.font`) in the source materials folder are processed in the same pass +as `.atl` files (`FontAtlasGenerator.cpp`). Glyph outlines and kerning (GPOS or `kern` table) are +read with `stb_truetype`, distance fields are generated with msdfgen (`src_dependency/msdfgen`, +core only) and glyphs are packed with `stb_rect_pack` into the smallest power of two atlas. + +``` +texture "ui/roboto_msdf"; // atlas TGA in the source materials folder, no extension +type mtsdf; // mtsdf (default), msdf, sdf, psdf +size 48; // atlas pixels per em +pxrange 8; // distance range in atlas pixels +padding 2; // extra pixels around each glyph box +charset "charset.txt" // charset files relative to the .font file (optional) +{ + chars "№€"; // inline entries (optional), same keys as in charset files +} +font "roboto_msdf" "ttf/Roboto-Regular.ttf"; // +font "roboto_msdf_b" "ttf/Roboto-Bold.ttf"; // all fonts share one atlas +``` + +- The charset is key-values: each value of the `charset` key is a charset file (key-values, UTF-8, + BOM allowed) relative to the `.font` file, and keys of the `charset` section are added inline. + Charset files and the section use the same keys; order and duplicates do not matter: + + ``` + chars " !\"#$%&'()*+,-./0123456789:;<=>?@"; // every character of the strings + range "A" "Z"; // first and last: a single character or a number + range 0x400 0x45F; + code 0x2116 8364; // code points, decimal or 0x hex + ``` + + A one-character `range` bound is the character itself, so `"0" "9"` are digits. Inside a string + `\"` is a quote and `\n`, `\r`, `\t` are control characters; a backslash cannot end a string + (add it with `code 0x5C`). +- The tool writes the RGBA8 atlas TGA to `/.tga` and one `eqfont2` + file per `font` entry to `/resources/fonts/.fnt` (format: + [public_rendering_overview.md](public_rendering_overview.md#eqfont2-msdf-fonts)). +- Each atlas texture is added to `/_fonts.mat` with `usage:fonts` (existing + entries are kept; the file is written only when an entry is added or changed), so the batch + conversion pass converts the atlas to DDS. The `fonts` usage must keep the texture uncompressed + and without mipmaps (`-f BGRA -m 1` for texconv): block compression breaks the distance channels. +- Glyph quads include `pxrange / 2 + padding` pixels around the outline, which leaves room for + `textWeight` and the shadow offset. + ## MSDF font converter (`tools/fontconv`) `msdf_to_eqfont.py` converts the output of diff --git a/src_dependency/msdfgen/LICENSE.txt b/src_dependency/msdfgen/LICENSE.txt new file mode 100644 index 000000000..fbea359b2 --- /dev/null +++ b/src_dependency/msdfgen/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2014 - 2025 Viktor Chlumsky + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src_dependency/msdfgen/msdfgen/core/Bitmap.h b/src_dependency/msdfgen/msdfgen/core/Bitmap.h new file mode 100644 index 000000000..05c305d64 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/Bitmap.h @@ -0,0 +1,60 @@ + +#pragma once + +#include "YAxisOrientation.h" +#include "BitmapRef.hpp" + +namespace msdfgen { + +/// A 2D image bitmap with N channels of type T. Pixel memory is managed by the class. +template +class Bitmap { + +public: + Bitmap(); + Bitmap(int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION); + explicit Bitmap(const BitmapConstRef &orig); + explicit Bitmap(const BitmapConstSection &orig); + Bitmap(const Bitmap &orig); +#ifdef MSDFGEN_USE_CPP11 + Bitmap(Bitmap &&orig); +#endif + ~Bitmap(); + Bitmap &operator=(const BitmapConstRef &orig); + Bitmap &operator=(const BitmapConstSection &orig); + Bitmap &operator=(const Bitmap &orig); +#ifdef MSDFGEN_USE_CPP11 + Bitmap &operator=(Bitmap &&orig); +#endif + /// Bitmap width in pixels. + int width() const; + /// Bitmap height in pixels. + int height() const; + T *operator()(int x, int y); + const T *operator()(int x, int y) const; +#ifdef MSDFGEN_USE_CPP11 + explicit operator T *(); + explicit operator const T *() const; +#else + operator T *(); + operator const T *() const; +#endif + operator BitmapRef(); + operator BitmapConstRef() const; + operator BitmapSection(); + operator BitmapConstSection() const; + /// Returns a reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax). + BitmapSection getSection(int xMin, int yMin, int xMax, int yMax); + /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax). + BitmapConstSection getConstSection(int xMin, int yMin, int xMax, int yMax) const; + +private: + T *pixels; + int w, h; + YAxisOrientation yOrientation; + +}; + +} + +#include "Bitmap.hpp" diff --git a/src_dependency/msdfgen/msdfgen/core/Bitmap.hpp b/src_dependency/msdfgen/msdfgen/core/Bitmap.hpp new file mode 100644 index 000000000..afb53942f --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/Bitmap.hpp @@ -0,0 +1,172 @@ + +#include "Bitmap.h" + +#include +#include + +namespace msdfgen { + +template +Bitmap::Bitmap() : pixels(NULL), w(0), h(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { } + +template +Bitmap::Bitmap(int width, int height, YAxisOrientation yOrientation) : w(width), h(height), yOrientation(yOrientation) { + pixels = new T[N*w*h]; +} + +template +Bitmap::Bitmap(const BitmapConstRef &orig) : w(orig.width), h(orig.height), yOrientation(orig.yOrientation) { + pixels = new T[N*w*h]; + memcpy(pixels, orig.pixels, sizeof(T)*N*w*h); +} + +template +Bitmap::Bitmap(const BitmapConstSection &orig) : w(orig.width), h(orig.height), yOrientation(orig.yOrientation) { + pixels = new T[N*w*h]; + T *dst = pixels; + const T *src = orig.pixels; + int rowLength = N*w; + for (int y = 0; y < h; ++y) { + memcpy(dst, src, sizeof(T)*rowLength); + dst += rowLength; + src += orig.rowStride; + } +} + +template +Bitmap::Bitmap(const Bitmap &orig) : w(orig.w), h(orig.h), yOrientation(orig.yOrientation) { + pixels = new T[N*w*h]; + memcpy(pixels, orig.pixels, sizeof(T)*N*w*h); +} + +#ifdef MSDFGEN_USE_CPP11 +template +Bitmap::Bitmap(Bitmap &&orig) : pixels(orig.pixels), w(orig.w), h(orig.h), yOrientation(orig.yOrientation) { + orig.pixels = NULL; + orig.w = 0, orig.h = 0; +} +#endif + +template +Bitmap::~Bitmap() { + delete[] pixels; +} + +template +Bitmap &Bitmap::operator=(const BitmapConstRef &orig) { + if (pixels != orig.pixels) { + delete[] pixels; + w = orig.width, h = orig.height; + yOrientation = orig.yOrientation; + pixels = new T[N*w*h]; + memcpy(pixels, orig.pixels, sizeof(T)*N*w*h); + } + return *this; +} + +template +Bitmap &Bitmap::operator=(const BitmapConstSection &orig) { + if (orig.pixels && orig.pixels >= pixels && orig.pixels < pixels+N*w*h) + return *this = Bitmap(orig); + delete[] pixels; + w = orig.width, h = orig.height; + yOrientation = orig.yOrientation; + pixels = new T[N*w*h]; + T *dst = pixels; + const T *src = orig.pixels; + int rowLength = N*w; + for (int y = 0; y < h; ++y) { + memcpy(dst, src, sizeof(T)*rowLength); + dst += rowLength; + src += orig.rowStride; + } + return *this; +} + +template +Bitmap &Bitmap::operator=(const Bitmap &orig) { + if (this != &orig) { + delete[] pixels; + w = orig.w, h = orig.h; + yOrientation = orig.yOrientation; + pixels = new T[N*w*h]; + memcpy(pixels, orig.pixels, sizeof(T)*N*w*h); + } + return *this; +} + +#ifdef MSDFGEN_USE_CPP11 +template +Bitmap &Bitmap::operator=(Bitmap &&orig) { + if (this != &orig) { + delete[] pixels; + pixels = orig.pixels; + w = orig.w, h = orig.h; + yOrientation = orig.yOrientation; + orig.pixels = NULL; + } + return *this; +} +#endif + +template +int Bitmap::width() const { + return w; +} + +template +int Bitmap::height() const { + return h; +} + +template +T *Bitmap::operator()(int x, int y) { + return pixels+N*(w*y+x); +} + +template +const T *Bitmap::operator()(int x, int y) const { + return pixels+N*(w*y+x); +} + +template +Bitmap::operator T *() { + return pixels; +} + +template +Bitmap::operator const T *() const { + return pixels; +} + +template +Bitmap::operator BitmapRef() { + return BitmapRef(pixels, w, h, yOrientation); +} + +template +Bitmap::operator BitmapConstRef() const { + return BitmapConstRef(pixels, w, h, yOrientation); +} + +template +Bitmap::operator BitmapSection() { + return BitmapSection(pixels, w, h, yOrientation); +} + +template +Bitmap::operator BitmapConstSection() const { + return BitmapConstSection(pixels, w, h, yOrientation); +} + +template +BitmapSection Bitmap::getSection(int xMin, int yMin, int xMax, int yMax) { + return BitmapSection(pixels+N*(w*yMin+xMin), xMax-xMin, yMax-yMin, N*w, yOrientation); +} + +template +BitmapConstSection Bitmap::getConstSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapConstSection(pixels+N*(w*yMin+xMin), xMax-xMin, yMax-yMin, N*w, yOrientation); +} + +} diff --git a/src_dependency/msdfgen/msdfgen/core/BitmapRef.hpp b/src_dependency/msdfgen/msdfgen/core/BitmapRef.hpp new file mode 100644 index 000000000..6e93fe983 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/BitmapRef.hpp @@ -0,0 +1,154 @@ + +#pragma once + +#include "YAxisOrientation.h" + +namespace msdfgen { + +/// Reference to a 2D image bitmap or a buffer acting as one. Pixel storage not owned or managed by the object. +template +struct BitmapRef; +/// Constant reference to a 2D image bitmap or a buffer acting as one. Pixel storage not owned or managed by the object. +template +struct BitmapConstRef; +/// Reference to a 2D image bitmap with non-contiguous rows of pixels. Pixel storage not owned or managed by the object. Can represent e.g. a section of a larger bitmap, bitmap with padded rows, or vertically flipped bitmap (rowStride can be negative). +template +struct BitmapSection; +/// Constant reference to a 2D image bitmap with non-contiguous rows of pixels. Pixel storage not owned or managed by the object. Can represent e.g. a section of a larger bitmap, bitmap with padded rows, or vertically flipped bitmap (rowStride can be negative). +template +struct BitmapConstSection; + +template +struct BitmapRef { + + T *pixels; + int width, height; + YAxisOrientation yOrientation; + + inline BitmapRef() : pixels(NULL), width(0), height(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { } + inline BitmapRef(T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), yOrientation(yOrientation) { } + + inline T *operator()(int x, int y) const { + return pixels+N*(width*y+x); + } + + /// Returns a reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapSection getSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapSection(pixels+N*(width*yMin+xMin), xMax-xMin, yMax-yMin, N*width, yOrientation); + } + + /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapConstSection getConstSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapConstSection(pixels+N*(width*yMin+xMin), xMax-xMin, yMax-yMin, N*width, yOrientation); + } + +}; + +template +struct BitmapConstRef { + + const T *pixels; + int width, height; + YAxisOrientation yOrientation; + + inline BitmapConstRef() : pixels(NULL), width(0), height(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { } + inline BitmapConstRef(const T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), yOrientation(yOrientation) { } + inline BitmapConstRef(const BitmapRef &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), yOrientation(orig.yOrientation) { } + + inline const T *operator()(int x, int y) const { + return pixels+N*(width*y+x); + } + + /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapConstSection getSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapConstSection(pixels+N*(width*yMin+xMin), xMax-xMin, yMax-yMin, N*width, yOrientation); + } + + /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapConstSection getConstSection(int xMin, int yMin, int xMax, int yMax) const { + return getSection(xMin, yMin, xMax, yMax); + } + +}; + +template +struct BitmapSection { + + T *pixels; + int width, height; + /// Specifies the difference between the beginnings of adjacent pixel rows as the number of T elements, can be negative. + int rowStride; + YAxisOrientation yOrientation; + + inline BitmapSection() : pixels(NULL), width(0), height(0), rowStride(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { } + inline BitmapSection(T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(N*width), yOrientation(yOrientation) { } + inline BitmapSection(T *pixels, int width, int height, int rowStride, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(rowStride), yOrientation(yOrientation) { } + inline BitmapSection(const BitmapRef &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(N*orig.width), yOrientation(orig.yOrientation) { } + + inline T *operator()(int x, int y) const { + return pixels+rowStride*y+N*x; + } + + /// Returns a reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapSection getSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapSection(pixels+rowStride*yMin+N*xMin, xMax-xMin, yMax-yMin, rowStride, yOrientation); + } + + /// Returns a constant reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapConstSection getConstSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapConstSection(pixels+rowStride*yMin+N*xMin, xMax-xMin, yMax-yMin, rowStride, yOrientation); + } + + /// Makes sure that the section's Y-axis orientation matches the argument by potentially reordering its rows. + inline void reorient(YAxisOrientation newYAxisOrientation) { + if (yOrientation != newYAxisOrientation) { + pixels += rowStride*(height-1); + rowStride = -rowStride; + yOrientation = newYAxisOrientation; + } + } + +}; + +template +struct BitmapConstSection { + + const T *pixels; + int width, height; + /// Specifies the difference between the beginnings of adjacent pixel rows as the number of T elements, can be negative. + int rowStride; + YAxisOrientation yOrientation; + + inline BitmapConstSection() : pixels(NULL), width(0), height(0), rowStride(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { } + inline BitmapConstSection(const T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(N*width), yOrientation(yOrientation) { } + inline BitmapConstSection(const T *pixels, int width, int height, int rowStride, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(rowStride), yOrientation(yOrientation) { } + inline BitmapConstSection(const BitmapRef &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(N*orig.width), yOrientation(orig.yOrientation) { } + inline BitmapConstSection(const BitmapConstRef &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(N*orig.width), yOrientation(orig.yOrientation) { } + inline BitmapConstSection(const BitmapSection &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(orig.rowStride), yOrientation(orig.yOrientation) { } + + inline const T *operator()(int x, int y) const { + return pixels+rowStride*y+N*x; + } + + /// Returns a constant reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapConstSection getSection(int xMin, int yMin, int xMax, int yMax) const { + return BitmapConstSection(pixels+rowStride*yMin+N*xMin, xMax-xMin, yMax-yMin, rowStride, yOrientation); + } + + /// Returns a constant reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax). + inline BitmapConstSection getConstSection(int xMin, int yMin, int xMax, int yMax) const { + return getSection(xMin, yMin, xMax, yMax); + } + + /// Makes sure that the section's Y-axis orientation matches the argument by potentially reordering its rows. + inline void reorient(YAxisOrientation newYAxisOrientation) { + if (yOrientation != newYAxisOrientation) { + pixels += rowStride*(height-1); + rowStride = -rowStride; + yOrientation = newYAxisOrientation; + } + } + +}; + +} diff --git a/src_dependency/msdfgen/msdfgen/core/Contour.cpp b/src_dependency/msdfgen/msdfgen/core/Contour.cpp new file mode 100644 index 000000000..aade65e59 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/Contour.cpp @@ -0,0 +1,90 @@ + +#include "Contour.h" + +#include "arithmetics.hpp" + +namespace msdfgen { + +static double shoelace(const Point2 &a, const Point2 &b) { + return (b.x-a.x)*(a.y+b.y); +} + +void Contour::addEdge(const EdgeHolder &edge) { + edges.push_back(edge); +} + +#ifdef MSDFGEN_USE_CPP11 +void Contour::addEdge(EdgeHolder &&edge) { + edges.push_back((EdgeHolder &&) edge); +} +#endif + +EdgeHolder &Contour::addEdge() { + edges.resize(edges.size()+1); + return edges.back(); +} + +static void boundPoint(double &xMin, double &yMin, double &xMax, double &yMax, Point2 p) { + if (p.x < xMin) xMin = p.x; + if (p.y < yMin) yMin = p.y; + if (p.x > xMax) xMax = p.x; + if (p.y > yMax) yMax = p.y; +} + +void Contour::bound(double &xMin, double &yMin, double &xMax, double &yMax) const { + for (std::vector::const_iterator edge = edges.begin(); edge != edges.end(); ++edge) + (*edge)->bound(xMin, yMin, xMax, yMax); +} + +void Contour::boundMiters(double &xMin, double &yMin, double &xMax, double &yMax, double border, double miterLimit, int polarity) const { + if (edges.empty()) + return; + Vector2 prevDir = edges.back()->direction(1).normalize(true); + for (std::vector::const_iterator edge = edges.begin(); edge != edges.end(); ++edge) { + Vector2 dir = -(*edge)->direction(0).normalize(true); + if (polarity*crossProduct(prevDir, dir) >= 0) { + double miterLength = miterLimit; + double q = .5*(1-dotProduct(prevDir, dir)); + if (q > 0) + miterLength = min(1/sqrt(q), miterLimit); + Point2 miter = (*edge)->point(0)+border*miterLength*(prevDir+dir).normalize(true); + boundPoint(xMin, yMin, xMax, yMax, miter); + } + prevDir = (*edge)->direction(1).normalize(true); + } +} + +int Contour::winding() const { + if (edges.empty()) + return 0; + double total = 0; + if (edges.size() == 1) { + Point2 a = edges[0]->point(0), b = edges[0]->point(1/3.), c = edges[0]->point(2/3.); + total += shoelace(a, b); + total += shoelace(b, c); + total += shoelace(c, a); + } else if (edges.size() == 2) { + Point2 a = edges[0]->point(0), b = edges[0]->point(.5), c = edges[1]->point(0), d = edges[1]->point(.5); + total += shoelace(a, b); + total += shoelace(b, c); + total += shoelace(c, d); + total += shoelace(d, a); + } else { + Point2 prev = edges.back()->point(0); + for (std::vector::const_iterator edge = edges.begin(); edge != edges.end(); ++edge) { + Point2 cur = (*edge)->point(0); + total += shoelace(prev, cur); + prev = cur; + } + } + return sign(total); +} + +void Contour::reverse() { + for (int i = (int) edges.size()/2; i > 0; --i) + EdgeHolder::swap(edges[i-1], edges[edges.size()-i]); + for (std::vector::iterator edge = edges.begin(); edge != edges.end(); ++edge) + (*edge)->reverse(); +} + +} diff --git a/src_dependency/msdfgen/msdfgen/core/Contour.h b/src_dependency/msdfgen/msdfgen/core/Contour.h new file mode 100644 index 000000000..53ceb8eda --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/Contour.h @@ -0,0 +1,34 @@ + +#pragma once + +#include +#include "EdgeHolder.h" + +namespace msdfgen { + +/// A single closed contour of a shape. +class Contour { + +public: + /// The sequence of edges that make up the contour. + std::vector edges; + + /// Adds an edge to the contour. + void addEdge(const EdgeHolder &edge); +#ifdef MSDFGEN_USE_CPP11 + void addEdge(EdgeHolder &&edge); +#endif + /// Creates a new edge in the contour and returns its reference. + EdgeHolder &addEdge(); + /// Adjusts the bounding box to fit the contour. + void bound(double &xMin, double &yMin, double &xMax, double &yMax) const; + /// Adjusts the bounding box to fit the contour border's mitered corners. + void boundMiters(double &xMin, double &yMin, double &xMax, double &yMax, double border, double miterLimit, int polarity) const; + /// Computes the winding of the contour. Returns 1 if positive, -1 if negative. + int winding() const; + /// Reverses the sequence of edges on the contour. + void reverse(); + +}; + +} diff --git a/src_dependency/msdfgen/msdfgen/core/DistanceMapping.cpp b/src_dependency/msdfgen/msdfgen/core/DistanceMapping.cpp new file mode 100644 index 000000000..526e12905 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/DistanceMapping.cpp @@ -0,0 +1,27 @@ + +#include "DistanceMapping.h" + +namespace msdfgen { + +DistanceMapping DistanceMapping::inverse(Range range) { + double rangeWidth = range.upper-range.lower; + return DistanceMapping(rangeWidth, range.lower/(rangeWidth ? rangeWidth : 1)); +} + +DistanceMapping::DistanceMapping() : scale(1), translate(0) { } + +DistanceMapping::DistanceMapping(Range range) : scale(1/(range.upper-range.lower)), translate(-range.lower) { } + +double DistanceMapping::operator()(double d) const { + return scale*(d+translate); +} + +double DistanceMapping::operator()(Delta d) const { + return scale*d.value; +} + +DistanceMapping DistanceMapping::inverse() const { + return DistanceMapping(1/scale, -scale*translate); +} + +} diff --git a/src_dependency/msdfgen/msdfgen/core/DistanceMapping.h b/src_dependency/msdfgen/msdfgen/core/DistanceMapping.h new file mode 100644 index 000000000..fadbefa54 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/DistanceMapping.h @@ -0,0 +1,36 @@ + +#pragma once + +#include "Range.hpp" + +namespace msdfgen { + +/// Linear transformation of signed distance values. +class DistanceMapping { + +public: + /// Explicitly designates value as distance delta rather than an absolute distance. + class Delta { + public: + double value; + inline explicit Delta(double distanceDelta) : value(distanceDelta) { } + inline operator double() const { return value; } + }; + + static DistanceMapping inverse(Range range); + + DistanceMapping(); + DistanceMapping(Range range); + double operator()(double d) const; + double operator()(Delta d) const; + DistanceMapping inverse() const; + +private: + double scale; + double translate; + + inline DistanceMapping(double scale, double translate) : scale(scale), translate(translate) { } + +}; + +} diff --git a/src_dependency/msdfgen/msdfgen/core/EdgeColor.h b/src_dependency/msdfgen/msdfgen/core/EdgeColor.h new file mode 100644 index 000000000..5d3730c9a --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/EdgeColor.h @@ -0,0 +1,20 @@ + +#pragma once + +#include "base.h" + +namespace msdfgen { + +/// Edge color specifies which color channels an edge belongs to. +enum EdgeColor { + BLACK = 0, + RED = 1, + GREEN = 2, + YELLOW = 3, + BLUE = 4, + MAGENTA = 5, + CYAN = 6, + WHITE = 7 +}; + +} diff --git a/src_dependency/msdfgen/msdfgen/core/EdgeHolder.cpp b/src_dependency/msdfgen/msdfgen/core/EdgeHolder.cpp new file mode 100644 index 000000000..f552e98fa --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/EdgeHolder.cpp @@ -0,0 +1,67 @@ + +#include "EdgeHolder.h" + +namespace msdfgen { + +void EdgeHolder::swap(EdgeHolder &a, EdgeHolder &b) { + EdgeSegment *tmp = a.edgeSegment; + a.edgeSegment = b.edgeSegment; + b.edgeSegment = tmp; +} + +EdgeHolder::EdgeHolder(const EdgeHolder &orig) : edgeSegment(orig.edgeSegment ? orig.edgeSegment->clone() : NULL) { } + +#ifdef MSDFGEN_USE_CPP11 +EdgeHolder::EdgeHolder(EdgeHolder &&orig) : edgeSegment(orig.edgeSegment) { + orig.edgeSegment = NULL; +} +#endif + +EdgeHolder::~EdgeHolder() { + delete edgeSegment; +} + +EdgeHolder &EdgeHolder::operator=(const EdgeHolder &orig) { + if (this != &orig) { + delete edgeSegment; + edgeSegment = orig.edgeSegment ? orig.edgeSegment->clone() : NULL; + } + return *this; +} + +#ifdef MSDFGEN_USE_CPP11 +EdgeHolder &EdgeHolder::operator=(EdgeHolder &&orig) { + if (this != &orig) { + delete edgeSegment; + edgeSegment = orig.edgeSegment; + orig.edgeSegment = NULL; + } + return *this; +} +#endif + +EdgeSegment &EdgeHolder::operator*() { + return *edgeSegment; +} + +const EdgeSegment &EdgeHolder::operator*() const { + return *edgeSegment; +} + +EdgeSegment *EdgeHolder::operator->() { + return edgeSegment; +} + +const EdgeSegment *EdgeHolder::operator->() const { + return edgeSegment; +} + +EdgeHolder::operator EdgeSegment *() { + return edgeSegment; +} + +EdgeHolder::operator const EdgeSegment *() const { + return edgeSegment; +} + +} diff --git a/src_dependency/msdfgen/msdfgen/core/EdgeHolder.h b/src_dependency/msdfgen/msdfgen/core/EdgeHolder.h new file mode 100644 index 000000000..5ae2dc231 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/EdgeHolder.h @@ -0,0 +1,41 @@ + +#pragma once + +#include "edge-segments.h" + +namespace msdfgen { + +/// Container for a single edge of dynamic type. +class EdgeHolder { + +public: + /// Swaps the edges held by a and b. + static void swap(EdgeHolder &a, EdgeHolder &b); + + inline EdgeHolder() : edgeSegment() { } + inline EdgeHolder(EdgeSegment *segment) : edgeSegment(segment) { } + inline EdgeHolder(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE) : edgeSegment(EdgeSegment::create(p0, p1, edgeColor)) { } + inline EdgeHolder(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE) : edgeSegment(EdgeSegment::create(p0, p1, p2, edgeColor)) { } + inline EdgeHolder(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE) : edgeSegment(EdgeSegment::create(p0, p1, p2, p3, edgeColor)) { } + EdgeHolder(const EdgeHolder &orig); +#ifdef MSDFGEN_USE_CPP11 + EdgeHolder(EdgeHolder &&orig); +#endif + ~EdgeHolder(); + EdgeHolder &operator=(const EdgeHolder &orig); +#ifdef MSDFGEN_USE_CPP11 + EdgeHolder &operator=(EdgeHolder &&orig); +#endif + EdgeSegment &operator*(); + const EdgeSegment &operator*() const; + EdgeSegment *operator->(); + const EdgeSegment *operator->() const; + operator EdgeSegment *(); + operator const EdgeSegment *() const; + +private: + EdgeSegment *edgeSegment; + +}; + +} diff --git a/src_dependency/msdfgen/msdfgen/core/MSDFErrorCorrection.cpp b/src_dependency/msdfgen/msdfgen/core/MSDFErrorCorrection.cpp new file mode 100644 index 000000000..940db3d49 --- /dev/null +++ b/src_dependency/msdfgen/msdfgen/core/MSDFErrorCorrection.cpp @@ -0,0 +1,496 @@ + +#include "MSDFErrorCorrection.h" + +#include +#include "arithmetics.hpp" +#include "equation-solver.h" +#include "EdgeColor.h" +#include "bitmap-interpolation.hpp" +#include "edge-selectors.h" +#include "contour-combiners.h" +#include "ShapeDistanceFinder.h" +#include "generator-config.h" + +namespace msdfgen { + +#define ARTIFACT_T_EPSILON .01 +#define PROTECTION_RADIUS_TOLERANCE 1.001 + +#define CLASSIFIER_FLAG_CANDIDATE 0x01 +#define CLASSIFIER_FLAG_ARTIFACT 0x02 + +MSDFGEN_PUBLIC const double ErrorCorrectionConfig::defaultMinDeviationRatio = 1.11111111111111111; +MSDFGEN_PUBLIC const double ErrorCorrectionConfig::defaultMinImproveRatio = 1.11111111111111111; + +/// The base artifact classifier recognizes artifacts based on the contents of the SDF alone. +class BaseArtifactClassifier { +public: + inline BaseArtifactClassifier(double span, bool protectedFlag) : span(span), protectedFlag(protectedFlag) { } + /// Evaluates if the median value xm interpolated at xt in the range between am at at and bm at bt indicates an artifact. + inline int rangeTest(double at, double bt, double xt, float am, float bm, float xm) const { + // For protected texels, only consider inversion artifacts (interpolated median has different sign than boundaries). For the rest, it is sufficient that the interpolated median is outside its boundaries. + if ((am > .5f && bm > .5f && xm <= .5f) || (am < .5f && bm < .5f && xm >= .5f) || (!protectedFlag && median(am, bm, xm) != xm)) { + double axSpan = (xt-at)*span, bxSpan = (bt-xt)*span; + // Check if the interpolated median's value is in the expected range based on its distance (span) from boundaries a, b. + if (!(xm >= am-axSpan && xm <= am+axSpan && xm >= bm-bxSpan && xm <= bm+bxSpan)) + return CLASSIFIER_FLAG_CANDIDATE|CLASSIFIER_FLAG_ARTIFACT; + return CLASSIFIER_FLAG_CANDIDATE; + } + return 0; + } + /// Returns true if the combined results of the tests performed on the median value m interpolated at t indicate an artifact. + inline bool evaluate(double t, float m, int flags) const { + return (flags&2) != 0; + } +private: + double span; + bool protectedFlag; +}; + +/// The shape distance checker evaluates the exact shape distance to find additional artifacts at a significant performance cost. +template