LCOV - code coverage report
Current view: top level - source/graphics - Font.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 176 285 61.8 %
Date: 2026-12-03 01:19:39 Functions: 15 21 71.4 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : #include "Font.h"
      20             : 
      21             : #include "graphics/TextureManager.h"
      22             : #include "lib/debug.h"
      23             : #include "lib/file/vfs/vfs.h"
      24             : #include "maths/Vector2D.h"
      25             : #include "ps/CLogger.h"
      26             : #include "ps/Filesystem.h"
      27             : #include "ps/Profiler2.h"
      28             : #include "ps/strings/StringBuilder.h"
      29             : #include "renderer/Renderer.h"
      30             : #include "renderer/backend/IDevice.h"
      31             : #include "renderer/backend/IDeviceCommandContext.h"
      32             : #include "renderer/backend/ITexture.h"
      33             : #include "renderer/backend/Sampler.h"
      34             : 
      35             : #include FT_ERRORS_H
      36             : #include FT_TYPES_H
      37             : #include <algorithm>
      38             : #include <cmath>
      39             : #include <cstring>
      40             : #include <numeric>
      41             : #include <span>
      42             : #include <sstream>
      43             : #include <string>
      44             : #include <utility>
      45             : #include <vector>
      46             : 
      47             : namespace
      48             : {
      49             : /**
      50             : * FreeType represents most of its size and position values in 26.6 fixed-point format — that is,
      51             : * 26 bits for the integer part and 6 bits for the fractional part.
      52             : * FreeType's metrics such as: ascender, descender, height, advance, etc. are measured in 1/64th of a pixel.
      53             : */
      54           5 : inline FT_F26Dot6 FloatToF26Dot6(float value)
      55             : {
      56           5 :     return static_cast<FT_F26Dot6>(std::lround(value * 64.0f));
      57             : }
      58             : 
      59        3613 : inline float FPosF26Dot6ToFloat(FT_Pos value)
      60             : {
      61        3613 :     return static_cast<float>(value) / 64.0f;
      62             : }
      63             : 
      64             : struct FTGlyphDeleter {
      65         476 :     void operator()(FT_Glyph glyph) const
      66             :     {
      67         476 :         FT_Done_Glyph(glyph);
      68         476 :     }
      69             : };
      70             : 
      71             : using UniqueFTGlyph = std::unique_ptr<std::remove_pointer_t<FT_Glyph>, FTGlyphDeleter>;
      72             : 
      73             : } // end namespace
      74             : 
      75       24667 : const CFont::GlyphData* CFont::GlyphMap::get(std::uint16_t codepoint) const
      76             : {
      77           0 :     if (!m_Data[codepoint >> 8])
      78             :         return nullptr;
      79       24661 :     if (!(*m_Data[codepoint >> 8])[codepoint & 0xff].defined)
      80             :         return nullptr;
      81       24191 :     return &(*m_Data[codepoint >> 8])[codepoint & 0xff];
      82             : }
      83             : 
      84         476 : void CFont::GlyphMap::set(std::uint16_t codepoint, const GlyphData& glyph)
      85             : {
      86         476 :     if (!m_Data[codepoint >> 8])
      87           6 :         m_Data[codepoint >> 8] = std::make_unique<std::array<GlyphData, 256>>();
      88         476 :     (*m_Data[codepoint >> 8])[codepoint & 0xff] = glyph;
      89         476 :     (*m_Data[codepoint >> 8])[codepoint & 0xff].defined = 1;
      90         476 : }
      91             : 
      92         692 : float CFont::GetHeight() const {
      93         692 :     return m_Height / m_Scale;
      94             : }
      95             : 
      96        2656 : float CFont::GetCapHeight()
      97             : {
      98        5312 :     const CFont::GlyphData* g{GetGlyph(L'I')};
      99        2656 :     return (g ? g->yadvance : 0) + std::abs(FPosF26Dot6ToFloat(m_Faces.front()->size->metrics.descender)) / m_Scale;
     100             : }
     101             : 
     102         970 : float CFont::GetCharacterWidth(wchar_t c)
     103             : {
     104         970 :     PROFILE2("GetCharacterWidth font texture generate");
     105         970 :     const CFont::GlyphData* g{GetGlyph(c)};
     106             : 
     107         970 :     return g ? g->xadvance : 0;
     108         970 : }
     109             : 
     110        1670 : void CFont::CalculateStringSize(const wchar_t* string, float& width, float& height)
     111             : {
     112        1670 :     PROFILE2("CalculateStringSize font texture generate");
     113        1670 :     width = 0;
     114        1670 :     height = 0;
     115             : 
     116             :     // Compute the width as the width of the longest line.
     117        1670 :     std::wstring original{string};
     118        1670 :     std::wistringstream stream{string};
     119        1670 :     std::wstring line;
     120        1670 :     bool firstLine{true};
     121        3340 :     while (std::getline(stream, line))
     122             :     {
     123        1670 :         FT_UInt glyphIndexStorage{0};
     124        1670 :         const float lineWidth{std::accumulate(line.begin(), line.end(), 0.0f, [&](float sum, wchar_t c)
     125             :             {
     126       20095 :                 const CFont::GlyphData* g{GetGlyph(c)};
     127             : 
     128       20095 :                 if (!g)
     129             :                     return sum;
     130             : 
     131       20095 :                 if (!FT_HAS_KERNING(g->face))
     132       20095 :                     return sum + g->xadvance;
     133             : 
     134           0 :                 const FT_UInt glyphIndex{FT_Get_Char_Index(g->face, c)};
     135           0 :                 if (!glyphIndex)
     136           0 :                     return sum + g->xadvance;
     137             : 
     138           0 :                 const FT_UInt prevGlyph{std::exchange(glyphIndexStorage, glyphIndex)};
     139           0 :                 if (!prevGlyph)
     140           0 :                     return sum + g->xadvance;
     141             : 
     142             :                 // Get the kerning value between the previous and current glyph.
     143           0 :                 FT_Vector kerning;
     144           0 :                 FT_Get_Kerning(g->face, prevGlyph, glyphIndex, FT_KERNING_DEFAULT, &kerning);
     145             :                 // Add the kerning distance.
     146           0 :                 return sum + g->xadvance + FPosF26Dot6ToFloat(kerning.x);
     147             :             })
     148        1670 :         };
     149             : 
     150        1670 :         width = std::max(width, lineWidth);
     151             : 
     152        1670 :         if (!firstLine || !line.empty())
     153        1625 :             height += firstLine ? GetCapHeight() : GetHeight();
     154             : 
     155        1670 :         firstLine = false;
     156             :     }
     157             : 
     158        1670 :     if (original.back() == L'\n')
     159          45 :         height += GetHeight();
     160        3131 : }
     161             : 
     162           5 : bool CFont::SetFontParams(
     163             :     Renderer::Backend::IDevice* device, const std::string& fontName,
     164             :     float size, float strokeWidth, float scale)
     165             : {
     166           5 :     ENSURE(m_FontSize == 0 && size > 0);
     167             : 
     168             :     // TODO: expose the Stroke Width outside class.
     169           5 :     m_Scale = scale;
     170           5 :     m_StrokeWidth = strokeWidth * scale;
     171           5 :     m_FontSize = size * scale;
     172           5 :     m_FontName = fontName;
     173             : 
     174           5 :     if (m_StrokeWidth)
     175             :     {
     176           0 :         FT_Stroker stroker;
     177           0 :         if (FT_Error error{FT_Stroker_New(m_FreeType, &stroker)})
     178             :         {
     179           0 :             LOGERROR("Failed to create stroker: {}", error);
     180           0 :             return false;
     181             :         }
     182           0 :         m_Stroker.reset(stroker);
     183           0 :         FT_Stroker_Set(m_Stroker.get(), FloatToF26Dot6(m_StrokeWidth), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0);
     184             :     }
     185             : 
     186           5 :     if (!ConstructAtlasTexture(device))
     187             :     {
     188           0 :         LOGERROR("Failed to create font texture atlas {}", fontName);
     189           0 :         return false;
     190             :     }
     191             : 
     192             :     return true;
     193             : }
     194             : 
     195           5 : bool CFont::AddFontFromPath(const OsPath& fontPath)
     196             : {
     197           5 :     ENSURE(m_FontSize > 0);
     198             : 
     199           5 :     if (!VfsFileExists(fontPath))
     200             :     {
     201           0 :         LOGERROR("Font file does not exist: {}", fontPath.string8());
     202           0 :         return false;
     203             :     }
     204             : 
     205           5 :     std::unique_ptr<std::uint8_t[], AlignedDeleter> fontData;
     206           5 :     size_t fontDataSize;
     207           5 :     if (g_VFS->LoadFile(fontPath, fontData, fontDataSize) != 0)
     208             :     {
     209           0 :         LOGERROR("Failed to load font file: {}", fontPath.string8());
     210           0 :         return false;
     211             :     }
     212             : 
     213           5 :     FT_Face face;
     214           5 :     if (FT_Error error{FT_New_Memory_Face(m_FreeType, fontData.get(), static_cast<FT_Long>(fontDataSize), 0, &face)}; error == FT_Err_Unknown_File_Format)
     215             :     {
     216           0 :         LOGERROR("Font file format is not supported: {}", fontPath.string8());
     217           5 :         return false;
     218             :     }
     219           5 :     else if (error)
     220             :     {
     221           0 :         LOGERROR("Failed to load font {}: {}", fontPath.string8(), error);
     222           0 :         return false;
     223             :     }
     224             : 
     225             :     // Keep the font data alive.
     226           5 :     m_FontsData.push_back(std::move(fontData));
     227             : 
     228             :     // Set the font size.
     229           5 :     if (FT_Error error{FT_Set_Char_Size(face, 0, FloatToF26Dot6(m_FontSize), 0 , 0)})
     230             :     {
     231           0 :         LOGERROR("Failed to set font size {}: {}", m_FontSize, error);
     232           0 :         return false;
     233             :     }
     234             : 
     235             :     // Get the height of the font.
     236           5 :     if (m_Faces.empty())
     237           5 :         m_Height = FPosF26Dot6ToFloat(face->size->metrics.height);
     238             : 
     239             :     // Add the fallback font to the list.
     240           5 :     m_Faces.push_back({face, &ftFaceDeleter});
     241             : 
     242           5 :     return true;
     243             : }
     244             : 
     245           5 : Renderer::Backend::Sampler::Desc CFont::ChooseTextureFormatAndSampler()
     246             : {
     247           5 :     Renderer::Backend::Sampler::Desc defaultSamplerDesc{
     248           0 :         Renderer::Backend::Sampler::MakeDefaultSampler(
     249             :             Renderer::Backend::Sampler::Filter::LINEAR,
     250             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE)
     251             :     };
     252             : 
     253           5 :     if (m_StrokeWidth > 0)
     254             :         return defaultSamplerDesc;
     255             : 
     256             :     // TODO: Add Support for R8_UNORM.
     257             :     // for R8 we will use texture swizzling to convert to RGBA.
     258             :     // and sampler will be changed
     259             : 
     260             :     // Legacy Format
     261           5 :     m_TextureFormat = Renderer::Backend::Format::A8_UNORM;
     262           5 :     m_TextureFormatStride = 1;
     263           5 :     m_HasRGB = false;
     264             : 
     265           5 :     return defaultSamplerDesc;
     266             : }
     267             : 
     268           5 : bool CFont::ConstructAtlasTexture(Renderer::Backend::IDevice* device)
     269             : {
     270             :     // Make backend texture ahead of time.
     271             :     // TODO: calculate based on device support.
     272           5 :     const int textureSize{1024};
     273           5 :     m_AtlasWidth = textureSize;
     274           5 :     m_AtlasHeight = textureSize;
     275           5 :     m_HasRGB = true;
     276           5 :     m_AtlasPadding = 4 + m_StrokeWidth * 2;
     277           5 :     m_AtlasX = m_AtlasY = 0;
     278             : 
     279           5 :     m_Bounds.right = textureSize;
     280           5 :     m_Bounds.bottom = textureSize;
     281             : 
     282             :     // TODO: preload from cache?.
     283             : 
     284           5 :     const Renderer::Backend::Sampler::Desc defaultSamplerDesc{ChooseTextureFormatAndSampler()};
     285             : 
     286           5 :     m_AtlasSize = m_AtlasWidth * m_AtlasHeight * m_TextureFormatStride;
     287             : 
     288           5 :     char buffer[128];
     289           5 :     PS::StringBuilder fontTextureNameBuilder{{std::begin(buffer), std::end(buffer)}};
     290           5 :     fontTextureNameBuilder.Append("Font Texture ");
     291           5 :     fontTextureNameBuilder.Append(m_FontName);
     292          10 :     m_Texture = g_Renderer.GetTextureManager().WrapBackendTexture(device->CreateTexture2D(
     293           5 :         fontTextureNameBuilder.Str().data(),
     294             :         Renderer::Backend::ITexture::Usage::TRANSFER_DST |
     295             :             Renderer::Backend::ITexture::Usage::SAMPLED,
     296             :         m_TextureFormat,
     297             :         textureSize, textureSize, defaultSamplerDesc
     298           5 :     ));
     299             : 
     300           5 :     if (!m_Texture)
     301             :     {
     302           0 :         LOGERROR("Failed to create font texture {}", m_FontName);
     303           0 :         return false;
     304             :     }
     305             : 
     306             :     // Initialise texture with transparency, for the areas we don't
     307             :     // overwrite with uploading later.
     308          10 :     m_TexData = std::make_unique<std::uint8_t[]>(m_AtlasSize);
     309           5 :     std::fill_n(m_TexData.get(), m_AtlasSize, 0x00);
     310             : 
     311           5 :     m_IsTextureInitialized = false;
     312             : 
     313           5 :     return true;
     314             : }
     315             : 
     316           0 : void CFont::InitalizeAtlasTextureIfNeeded(
     317             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     318             : {
     319           0 :     if (m_IsTextureInitialized)
     320             :         return;
     321             : 
     322           0 :     deviceCommandContext->UploadTexture(
     323           0 :         m_Texture->GetBackendTexture(), m_TextureFormat,
     324           0 :         m_TexData.get(), m_AtlasSize);
     325             : 
     326           0 :     m_IsTextureInitialized = true;
     327             : }
     328             : 
     329       24191 : const CFont::GlyphData* CFont::GetGlyph(std::uint16_t codepoint)
     330             : {
     331       24191 :     const CFont::GlyphData* g{m_Glyphs.get(codepoint)};
     332       24191 :     return (g && g->defined) ? g : ExtractAndGenerateGlyph(codepoint);
     333             : }
     334             : 
     335         476 : const CFont::GlyphData* CFont::ExtractAndGenerateGlyph(std::uint16_t codepoint)
     336             : {
     337         476 :     ENSURE(!m_Faces.empty());
     338         952 :     PROFILE2("Glyph font texture generate");
     339             : 
     340         476 :     const auto [faceToUse, glyphIndex]{[&]()->std::pair<FT_Face, FT_UInt>
     341             :         {
     342         476 :             FT_UInt index{0};
     343        1428 :             std::vector<UniqueFTFace>::iterator it{std::find_if(m_Faces.begin(), m_Faces.end(), [&](const UniqueFTFace& face)
     344             :                 {
     345         952 :                     index = FT_Get_Char_Index(face.get(), codepoint);
     346         476 :                     return index != 0;
     347             :                 }
     348             :             )};
     349             : 
     350         476 :             return {it != m_Faces.end() ? it->get() : m_Faces.front().get(), index};
     351         476 :         }()
     352             :     };
     353         476 :     const FT_Int32 loadFlags{FT_LOAD_DEFAULT | (m_FontSize <= MINIMAL_FONT_SIZE_ANTIALIASING ? FT_LOAD_TARGET_MONO : 0)};
     354             : 
     355         476 :     if (FT_Error error{FT_Load_Glyph(faceToUse, glyphIndex, loadFlags)})
     356             :     {
     357           0 :         LOGERROR("Failed to load glyph {}: {}", codepoint, error);
     358           0 :         return nullptr;
     359             :     }
     360             : 
     361         476 :     const FT_GlyphSlot slot{faceToUse->glyph};
     362         476 :     FT_Glyph glyph;
     363         476 :     if (FT_Error error{FT_Get_Glyph(slot, &glyph)})
     364             :     {
     365           0 :         LOGERROR("Failed to get glyph {}: {}", codepoint, error);
     366           0 :         return nullptr;
     367             :     }
     368         952 :     UniqueFTGlyph glyphPtr(glyph);
     369             : 
     370         476 :     const float baselineInAtlas{FPosF26Dot6ToFloat(faceToUse->size->metrics.ascender)};
     371         476 :     const float glyphW{FPosF26Dot6ToFloat(slot->advance.x)};
     372             : 
     373         476 :     if (m_AtlasX + glyphW + m_StrokeWidth + m_AtlasPadding > m_AtlasWidth)
     374             :     {
     375           1 :         m_AtlasX = 0;
     376           1 :         m_AtlasY += std::ceil(m_Height + m_StrokeWidth + m_AtlasPadding);
     377             :     }
     378             : 
     379         476 :     if (m_AtlasY + m_Height + m_StrokeWidth + m_AtlasPadding > m_AtlasHeight)
     380             :     {
     381           0 :         LOGERROR("Font texture atlas is full, cannot load more glyphs");
     382           0 :         return nullptr;
     383             :     }
     384             : 
     385         476 :     m_IsDirty = true;
     386         476 :     CVector2D offset{0.0f, 0.0f};
     387             : 
     388         476 :     const FT_Render_Mode renderMode{FT_RENDER_MODE_NORMAL};
     389             : 
     390         476 :     if (m_StrokeWidth)
     391             :     {
     392           0 :         std::optional<CVector2D> offsetStroke{GenerateStrokeGlyphBitmap(glyph, codepoint, renderMode, baselineInAtlas)};
     393           0 :         if (!offsetStroke.has_value())
     394             :         {
     395           0 :             LOGERROR("Failed to generate stroke glyph {}", codepoint);
     396           0 :             return nullptr;
     397             :         }
     398             : 
     399           0 :         offset = offsetStroke.value();
     400             :     }
     401             : 
     402         476 :     std::optional<CVector2D> offsetGlyph{GenerateGlyphBitmap(glyph, codepoint, renderMode, offset, baselineInAtlas)};
     403         476 :     if (!offsetGlyph.has_value())
     404             :     {
     405           0 :         LOGERROR("Failed to generate glyph {}", codepoint);
     406           0 :         return nullptr;
     407             :     }
     408         476 :     offset = offsetGlyph.value();
     409             : 
     410         476 :     CFont::GlyphData gd;
     411         476 :     gd.u0 = static_cast<float>(m_AtlasX) / m_AtlasWidth;
     412         476 :     gd.v0 = static_cast<float>(m_AtlasY) / m_AtlasHeight;
     413         476 :     gd.u1 = static_cast<float>(m_AtlasX - offset.X + glyphW + m_StrokeWidth * 2) / m_AtlasWidth;
     414         476 :     gd.v1 = static_cast<float>(m_AtlasY + offset.Y + m_Height + m_StrokeWidth * 2) / m_AtlasHeight;
     415             : 
     416         476 :     gd.x0 = (offset.X - m_StrokeWidth) / m_Scale;
     417         476 :     gd.y0 = (-(m_Height + offset.Y + m_StrokeWidth)) / m_Scale;
     418         476 :     gd.x1 = (glyphW + m_StrokeWidth) / m_Scale;
     419         476 :     gd.y1 = m_StrokeWidth / m_Scale;
     420             : 
     421         476 :     gd.xadvance = glyphW / m_Scale;
     422         476 :     gd.yadvance = FPosF26Dot6ToFloat(slot->metrics.height) / m_Scale;
     423         476 :     gd.defined = 1;
     424         476 :     gd.face = faceToUse;
     425             : 
     426         476 :     m_Glyphs.set(codepoint, gd);
     427             : 
     428             :     // Update positions for next glyph.
     429         476 :     m_AtlasX += std::ceil(glyphW + m_StrokeWidth + m_AtlasPadding);
     430             : 
     431         952 :     return m_Glyphs.get(codepoint);
     432             : }
     433             : 
     434           0 : std::optional<CVector2D> CFont::GenerateStrokeGlyphBitmap(const FT_Glyph& glyph, std::uint16_t codepoint,
     435             :     FT_Render_Mode renderMode, const float baselineInAtlas)
     436             : {
     437           0 :     FT_Glyph strokedGlyph;
     438           0 :     if (FT_Error error{FT_Glyph_Copy(glyph, &strokedGlyph)})
     439             :     {
     440           0 :         LOGERROR("Failed to copy glyph {}: {}", codepoint, error);
     441           0 :         FT_Done_Glyph(strokedGlyph);
     442           0 :         return std::nullopt;
     443             :     }
     444             : 
     445           0 :     if (FT_Error error{FT_Glyph_StrokeBorder(&strokedGlyph, m_Stroker.get(), 0, 1)})
     446             :     {
     447           0 :         LOGERROR("Failed to stroke glyph {}: {}", codepoint, error);
     448           0 :         FT_Done_Glyph(strokedGlyph);
     449           0 :         return std::nullopt;
     450             :     }
     451             : 
     452           0 :     if (FT_Error error{FT_Glyph_To_Bitmap(&strokedGlyph, renderMode, nullptr, 1)})
     453             :     {
     454           0 :         LOGERROR("Failed to render glyph {}: {}", codepoint, error);
     455           0 :         FT_Done_Glyph(strokedGlyph);
     456           0 :         return std::nullopt;
     457             :     }
     458             : 
     459           0 :     FT_BitmapGlyph bitmapGlyph{reinterpret_cast<FT_BitmapGlyph>(strokedGlyph)};
     460           0 :     FT_Bitmap& bitmapStroke{bitmapGlyph->bitmap};
     461             : 
     462           0 :     CVector2D offset{0.0f, 0.0f};
     463           0 :     int targetStrokeY{static_cast<int>(std::ceil(m_AtlasY + m_StrokeWidth + baselineInAtlas - bitmapGlyph->top))};
     464           0 :     int targetStrokeX{static_cast<int>(std::ceil(m_AtlasX + m_StrokeWidth + bitmapGlyph->left))};
     465           0 :     if (targetStrokeX < m_AtlasX)
     466             :     {
     467           0 :         offset.X = bitmapGlyph->left + m_StrokeWidth;
     468           0 :         targetStrokeX = m_AtlasX;
     469             :     }
     470           0 :     if (targetStrokeY < m_AtlasY)
     471             :     {
     472           0 :         offset.Y = bitmapGlyph->top - baselineInAtlas - m_StrokeWidth;
     473           0 :         targetStrokeY = m_AtlasY;
     474             :     }
     475           0 :     BlendGlyphBitmapToTexture(bitmapStroke, targetStrokeX, targetStrokeY, 0, 0, 0);
     476           0 :     FT_Done_Glyph(strokedGlyph);
     477           0 :     return offset;
     478             : }
     479             : 
     480         476 : std::optional<CVector2D> CFont::GenerateGlyphBitmap(FT_Glyph& glyph, std::uint16_t codepoint,
     481             :     FT_Render_Mode renderMode, CVector2D offset, const float baselineInAtlas)
     482             : {
     483         476 :     if (FT_Error error{FT_Glyph_To_Bitmap(&glyph, renderMode, nullptr, 0)})
     484             :     {
     485           0 :         LOGERROR("Failed to render glyph {}: {}", codepoint, error);
     486           0 :         return std::nullopt;
     487             :     }
     488         476 :     FT_BitmapGlyph bitmapGlyph{reinterpret_cast<FT_BitmapGlyph>(glyph)};
     489         476 :     FT_Bitmap& bitmap{bitmapGlyph->bitmap};
     490             : 
     491         476 :     int targetY{static_cast<int>(std::ceil(m_AtlasY + offset.Y + m_StrokeWidth + baselineInAtlas - bitmapGlyph->top))};
     492         476 :     int targetX{static_cast<int>(std::ceil(m_AtlasX - offset.X + m_StrokeWidth + bitmapGlyph->left))};
     493         476 :     CVector2D newOffset{0.0f, 0.0f};
     494         476 :     if (targetX < m_AtlasX)
     495             :     {
     496           2 :         newOffset.X = bitmapGlyph->left + m_StrokeWidth;
     497           2 :         targetX = m_AtlasX;
     498             :     }
     499             : 
     500         476 :     if (targetY < m_AtlasY)
     501             :     {
     502           0 :         newOffset.Y = bitmapGlyph->top - baselineInAtlas - m_StrokeWidth;
     503           0 :         targetY = m_AtlasY;
     504             :     }
     505             : 
     506         476 :     BlendGlyphBitmapToTexture(bitmap, targetX, targetY, 255, 255, 255);
     507         476 :     FT_Done_Glyph(glyph);
     508         476 :     return newOffset;
     509             : }
     510             : 
     511           0 : void CFont::UploadAtlasTextureToGPU(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     512             : {
     513           0 :     if (!m_IsDirty)
     514             :         return;
     515             : 
     516           0 :     deviceCommandContext->UploadTexture(
     517           0 :         m_Texture->GetBackendTexture(),
     518             :         m_TextureFormat,
     519           0 :         m_TexData.get(),
     520           0 :         m_AtlasSize
     521             :     );
     522             : 
     523           0 :     m_IsDirty = false;
     524             : }
     525             : 
     526         476 : void CFont::BlendGlyphBitmapToTexture(const FT_Bitmap& bitmap, int targetX, int targetY, std::uint8_t r,
     527             :     std::uint8_t g, std::uint8_t b)
     528             : {
     529         476 :     PROFILE2("BlendGlyphBitmapToTexture font texture generate");
     530         476 :     if (m_TextureFormat == Renderer::Backend::Format::R8G8B8A8_UNORM)
     531           0 :         BlendGlyphBitmapToTextureRGBA(bitmap, targetX, targetY, r, g, b);
     532             :     else
     533         476 :         BlendGlyphBitmapToTextureR8(bitmap, targetX, targetY);
     534         476 : }
     535             : 
     536           0 : void CFont::BlendGlyphBitmapToTextureRGBA(const FT_Bitmap& bitmap, int targetX, int targetY,
     537             :     std::uint8_t r, std::uint8_t g, std::uint8_t b)
     538             : {
     539           0 :     for (unsigned int y{0}; y != bitmap.rows; ++y)
     540             :     {
     541           0 :         const std::uint8_t* srcRow{bitmap.buffer + y * bitmap.pitch};
     542           0 :         std::uint8_t* dstRow{m_TexData.get() + ((targetY + y) * m_AtlasWidth + targetX) * m_TextureFormatStride};
     543             : 
     544           0 :         for (unsigned int x{0}; x != bitmap.width; ++x)
     545             :         {
     546           0 :             std::uint8_t* tempDstRow{dstRow + x * m_TextureFormatStride};
     547           0 :             std::uint8_t alpha{srcRow[x]};
     548             : 
     549           0 :             const float srcAlpha{m_StrokeWidth > 0 ? m_GammaCorrectionLUT.get()[alpha] : alpha / 255.0f};
     550           0 :             const float dstAlpha{tempDstRow[3] / 255.0f};
     551           0 :             const float outAlpha{srcAlpha + dstAlpha * (1.0f - srcAlpha)};
     552             : 
     553           0 :             if (outAlpha == 0.0f)
     554           0 :                 continue;
     555             : 
     556           0 :             tempDstRow[0] = static_cast<std::uint8_t>(std::round(((r * srcAlpha + tempDstRow[0] *
     557           0 :                 dstAlpha * (1.0f - srcAlpha)) / outAlpha)));
     558           0 :             tempDstRow[1] = static_cast<std::uint8_t>(std::round(((g * srcAlpha + tempDstRow[1] *
     559           0 :                 dstAlpha * (1.0f - srcAlpha)) / outAlpha)));
     560           0 :             tempDstRow[2] = static_cast<std::uint8_t>(std::round(((b * srcAlpha + tempDstRow[2] *
     561           0 :                 dstAlpha * (1.0f - srcAlpha)) / outAlpha)));
     562           0 :             tempDstRow[3] = static_cast<std::uint8_t>(std::round(outAlpha * 255.0f));
     563             :         }
     564             :     }
     565           0 : }
     566             : 
     567         476 : void  CFont::BlendGlyphBitmapToTextureR8(const FT_Bitmap& bitmap, int targetX, int targetY)
     568             : {
     569        3704 :     for (unsigned int y{0}; y != bitmap.rows; ++y)
     570             :     {
     571        3228 :         const std::uint8_t* srcRow{bitmap.buffer + y * bitmap.pitch};
     572        3228 :         std::uint8_t* dstRow{m_TexData.get() + ((targetY + y) * m_AtlasWidth + targetX)};
     573             : 
     574        3228 :         std::memcpy(dstRow, srcRow, bitmap.width);
     575             :     }
     576         476 : }

Generated by: LCOV version 1.16