Refactor FontAtlas class

This commit is contained in:
Georg Hagen
2025-01-11 01:25:52 +01:00
parent 6a3c31346f
commit 9cb3d4de85
14 changed files with 246 additions and 247 deletions

View File

@@ -7,10 +7,10 @@
#include "TextExampleApp.hpp" #include "TextExampleApp.hpp"
#include "Scene/Scene.hpp" #include "Scene/Scene.hpp"
#include "Scene/Shader/Shader.hpp" #include "Scene/Shader/Shader.hpp"
#include "Scene/Geometry.hpp"
#include "Scene/TextDrawable.hpp" #include "Scene/TextDrawable.hpp"
#include "Scene/Vertex.hpp" #include "Scene/Vertex.hpp"
#include "Scene/UI/PerformanceInfo.hpp" #include "Scene/UI/PerformanceInfo.hpp"
#include "Scene/Text/FontAtlas.hpp"
#include "Input/InputManager.hpp" #include "Input/InputManager.hpp"
#include "Host/GraphicsAppManager.hpp" #include "Host/GraphicsAppManager.hpp"
#include "Host/GLFW/WindowGLFW.hpp" #include "Host/GLFW/WindowGLFW.hpp"
@@ -68,15 +68,15 @@ namespace OpenVulkano
std::set<uint32_t> s = BitmapFontAtlasGenerator::LoadAllGlyphs(fontPath); std::set<uint32_t> s = BitmapFontAtlasGenerator::LoadAllGlyphs(fontPath);
BitmapFontAtlasGenerator generator; BitmapFontAtlasGenerator generator;
generator.GenerateAtlas(fontPath, s); generator.GenerateAtlas(fontPath, s);
generator.SaveAtlasMetadataInfo("bitmap_atlas"); generator.GetAtlas()->Save("bitmap_atlas_packed.png");
} }
#if defined(MSDFGEN_AVAILABLE) && CREATE_NEW_ATLAS #if defined(MSDFGEN_AVAILABLE) && CREATE_NEW_ATLAS
std::set<uint32_t> s = SdfFontAtlasGenerator::LoadAllGlyphs(fontPath); std::set<uint32_t> s = SdfFontAtlasGenerator::LoadAllGlyphs(fontPath);
m_atlasGenerator.GenerateAtlas(fontPath, s); m_atlasGenerator.GenerateAtlas(fontPath, s);
m_msdfAtlasGenerator.GenerateAtlas(fontPath, s); m_msdfAtlasGenerator.GenerateAtlas(fontPath, s);
m_atlasGenerator.SaveAtlasMetadataInfo("sdf_atlas.png"); m_atlasGenerator.GetAtlas()->Save("sdf_atlas_packed.png");
m_msdfAtlasGenerator.SaveAtlasMetadataInfo("msdf_atlas"); m_msdfAtlasGenerator.GetAtlas()->Save("msdf_atlas_packed.png");
#else #else
auto sdfMetadataInfo = resourceLoader.GetResource("sdf_atlas_packed.png"); auto sdfMetadataInfo = resourceLoader.GetResource("sdf_atlas_packed.png");
auto msdfMetadataInfo = resourceLoader.GetResource("msdf_atlas_packed.png"); auto msdfMetadataInfo = resourceLoader.GetResource("msdf_atlas_packed.png");

View File

@@ -1,46 +0,0 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "Base/Wrapper.hpp"
#include "Math/Math.hpp"
#include "Image/Image.hpp"
#include "Scene/Texture.hpp"
#include "Scene/Text/FontAtlasType.hpp"
#include <string_view>
#include <map>
#include <magic_enum.hpp>
namespace OpenVulkano::Scene
{
struct GlyphInfo
{
//GlyphGeometry geometry;
//GlyphBox glyphBox;
Math::Vector2f_SIMD pos[4] = {};
Math::Vector2f_SIMD uv[4] = {};
double advance = 0;
};
struct AtlasMetadata
{
// vertical difference between baselines
double lineHeight = 0;
FontAtlasType atlasType = FontAtlasType::UNKNOWN;
};
struct AtlasData
{
std::map<uint32_t, GlyphInfo> glyphs;
AtlasMetadata meta;
Unique<Image::Image> img;
Texture texture;
operator bool() const { return !glyphs.empty() && texture.textureBuffer; }
};
}

View File

@@ -6,6 +6,7 @@
#include "BitmapFontAtlasGenerator.hpp" #include "BitmapFontAtlasGenerator.hpp"
#include "Base/Logger.hpp" #include "Base/Logger.hpp"
#include "Text/FontAtlas.hpp"
namespace OpenVulkano::Scene namespace OpenVulkano::Scene
{ {
@@ -31,7 +32,6 @@ namespace OpenVulkano::Scene
return; return;
} }
m_atlasData = std::make_shared<AtlasData>();
const auto& [lib, face] = FontAtlasGeneratorBase::InitFreetype(source); const auto& [lib, face] = FontAtlasGeneratorBase::InitFreetype(source);
FT_Set_Pixel_Sizes(face.get(), 0, m_pixelSizeConfig.CalculatePixelSize()); FT_Set_Pixel_Sizes(face.get(), 0, m_pixelSizeConfig.CalculatePixelSize());
@@ -47,12 +47,9 @@ namespace OpenVulkano::Scene
// but since some algorithms have already been implemented for EM_NORMALIZED mode, currently there is no support for default font metrics (ints) // but since some algorithms have already been implemented for EM_NORMALIZED mode, currently there is no support for default font metrics (ints)
// The coordinates will be normalized to the em size, i.e. 1 = 1 em // The coordinates will be normalized to the em size, i.e. 1 = 1 em
const double scaleFactor = (1. / face->units_per_EM); const double scaleFactor = (1. / face->units_per_EM);
SetupAtlasData(atlasResolution, face->height * scaleFactor, FontAtlasType::BITMAP); m_atlasData = std::make_shared<FontAtlas>(atlasResolution, face->height * scaleFactor, FontAtlasType::BITMAP);
FillGlyphsInfo(allGlyphs, face, scaleFactor); FillGlyphsInfo(allGlyphs, face, scaleFactor);
if (pngOutput) if (pngOutput) m_atlasData->Save(*pngOutput);
{
SavePng(*pngOutput);
}
} }
std::pair<std::vector<GlyphForPacking>, double> std::pair<std::vector<GlyphForPacking>, double>
@@ -94,14 +91,15 @@ namespace OpenVulkano::Scene
} }
FT_GlyphSlot slot = face->glyph; FT_GlyphSlot slot = face->glyph;
char* baseAddress = static_cast<char*>(m_atlasData->GetTexture()->textureBuffer) + glyph.firstGlyphByteInAtlas;
for (int row = 0; row < slot->bitmap.rows; row++) for (int row = 0; row < slot->bitmap.rows; row++)
{ {
std::memcpy(&m_atlasData->img->data[glyph.firstGlyphByteInAtlas + row * m_atlasData->img->resolution.x], std::memcpy(baseAddress + row * m_atlasData->GetTexture()->resolution.x,
&slot->bitmap.buffer[(slot->bitmap.rows - 1 - row) * slot->bitmap.pitch], &slot->bitmap.buffer[(slot->bitmap.rows - 1 - row) * slot->bitmap.pitch],
slot->bitmap.width); slot->bitmap.width);
} }
GlyphInfo& glyphInfo = m_atlasData->glyphs[glyph.code]; GlyphInfo& glyphInfo = m_atlasData->GetGlyphs()[glyph.code];
const Math::Vector2d glyphMetrics = { slot->metrics.width * scaleFactor, const Math::Vector2d glyphMetrics = { slot->metrics.width * scaleFactor,
slot->metrics.height * scaleFactor }; slot->metrics.height * scaleFactor };
const Math::Vector2d glyphBearing = { slot->metrics.horiBearingX * scaleFactor, const Math::Vector2d glyphBearing = { slot->metrics.horiBearingX * scaleFactor,

View File

@@ -5,14 +5,9 @@
*/ */
#include "FontAtlasGeneratorBase.hpp" #include "FontAtlasGeneratorBase.hpp"
#include "Text/FontAtlas.hpp"
#include "Base/Logger.hpp" #include "Base/Logger.hpp"
#include "Extensions/STBZlibCompressor.hpp"
#include <filesystem> #include <filesystem>
#include <fstream>
#define STBI_MSC_SECURE_CRT
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STBIW_ZLIB_COMPRESS Extensions::STBZlibCompressor
#include <stb_image_write.h>
namespace OpenVulkano::Scene namespace OpenVulkano::Scene
{ {
@@ -61,74 +56,10 @@ namespace OpenVulkano::Scene
return fmt::format("Error code is {}", error); return fmt::format("Error code is {}", error);
} }
void FontAtlasGeneratorBase::SaveAtlasMetadataInfo(const std::string& outputFile, bool packIntoSingleFile) const
{
if (m_atlasData->glyphs.empty())
{
Logger::DATA->info("No glyphs loaded. Nothing to save.");
return;
}
std::string fileName = outputFile;
uint32_t packedFlag = packIntoSingleFile;
if (packIntoSingleFile)
{
std::filesystem::path fPath(fileName);
fileName = (fPath.parent_path() / fPath.stem()).string() + "_packed.png";
SavePng(fileName);
}
std::fstream fs(fileName.c_str(), std::ios_base::out | std::ios_base::binary | (packedFlag ? std::ios_base::app : std::ios_base::trunc));
fs.write(reinterpret_cast<const char*>(&m_atlasData->meta), sizeof(AtlasMetadata));
uint64_t metadataBytes = sizeof(AtlasMetadata);
for (const auto& [key, val] : m_atlasData->glyphs)
{
fs.write(reinterpret_cast<const char*>(&key), sizeof(uint32_t));
fs.write(reinterpret_cast<const char*>(&val.pos), sizeof(GlyphInfo::pos));
fs.write(reinterpret_cast<const char*>(&val.pos), sizeof(GlyphInfo::pos)); // TODO remove this after cleaning up the atlas writing code
fs.write(reinterpret_cast<const char*>(&val.uv), sizeof(GlyphInfo::uv));
fs.write(reinterpret_cast<const char*>(&val.advance), sizeof(GlyphInfo::advance));
fs.write(reinterpret_cast<const char*>(&val.advance), sizeof(GlyphInfo::advance)); // TODO remove this afer cleaning up the atlas writing code
metadataBytes += sizeof(uint32_t);
metadataBytes += sizeof(GlyphInfo);
}
fs.write(reinterpret_cast<const char*>(&metadataBytes), sizeof(uint64_t));
fs.write(reinterpret_cast<const char*>(&packedFlag), sizeof(uint32_t));
fs.close();
}
void FontAtlasGeneratorBase::SavePng(std::string output) const
{
stbi_flip_vertically_on_write(1);
if (std::filesystem::path(output).extension() != ".png")
{
output += ".png";
}
stbi_write_png(output.c_str(), m_atlasData->img->resolution.x, m_atlasData->img->resolution.y, m_channelsCount,
m_atlasData->img->data.Data(), m_channelsCount * m_atlasData->img->resolution.x);
}
void FontAtlasGeneratorBase::SetupAtlasData(Math::Vector2ui textureResolution, double lineHeight,
FontAtlasType::Type atlasType)
{
// generate texture
m_atlasData->img = std::make_unique<Image::Image>();
m_atlasData->img->resolution = Math::Vector3ui(textureResolution, 1);
m_atlasData->img->dataFormat = m_channelsCount == 1 ? DataFormat::R8_UNORM : DataFormat::R8G8B8A8_UNORM;
m_atlasData->img->data = Array<uint8_t>(m_atlasData->img->dataFormat.CalculatedSize(textureResolution.x, textureResolution.y));
m_atlasData->texture.resolution = m_atlasData->img->resolution;
m_atlasData->texture.textureBuffer = m_atlasData->img->data.Data();
m_atlasData->texture.format = m_atlasData->img->dataFormat;
m_atlasData->texture.size = m_atlasData->img->data.Size();
m_atlasData->meta.atlasType = atlasType;
m_atlasData->meta.lineHeight = lineHeight;
if (atlasType == FontAtlasType::BITMAP)
{
m_atlasData->texture.m_samplerConfig = &SamplerConfig::NEAREST;
}
}
void FontAtlasGeneratorBase::SetGlyphData(GlyphInfo& info, Math::Vector2d bearing, Math::Vector2d size, void FontAtlasGeneratorBase::SetGlyphData(GlyphInfo& info, Math::Vector2d bearing, Math::Vector2d size,
const Math::AABB& aabb, double advance) const Math::AABB& aabb, double advance)
{ {
const auto& resolution = m_atlasData->GetTexture()->resolution;
const double l = aabb.min.x; const double l = aabb.min.x;
const double r = aabb.max.x; const double r = aabb.max.x;
const double t = aabb.max.y; const double t = aabb.max.y;
@@ -136,23 +67,23 @@ namespace OpenVulkano::Scene
info.pos[0].x = bearing.x; info.pos[0].x = bearing.x;
info.pos[0].y = size.y - bearing.y; info.pos[0].y = size.y - bearing.y;
info.uv[0].x = l / m_atlasData->texture.resolution.x; info.uv[0].x = l / resolution.x;
info.uv[0].y = b / m_atlasData->texture.resolution.y; info.uv[0].y = b / resolution.y;
info.pos[1].x = bearing.x + size.x; info.pos[1].x = bearing.x + size.x;
info.pos[1].y = size.y - bearing.y; info.pos[1].y = size.y - bearing.y;
info.uv[1].x = r / m_atlasData->texture.resolution.x; info.uv[1].x = r / resolution.x;
info.uv[1].y = b / m_atlasData->texture.resolution.y; info.uv[1].y = b / resolution.y;
info.pos[2].x = bearing.x + size.x; info.pos[2].x = bearing.x + size.x;
info.pos[2].y = bearing.y; info.pos[2].y = bearing.y;
info.uv[2].x = r / m_atlasData->texture.resolution.x; info.uv[2].x = r / resolution.x;
info.uv[2].y = t / m_atlasData->texture.resolution.y; info.uv[2].y = t / resolution.y;
info.pos[3].x = bearing.x; info.pos[3].x = bearing.x;
info.pos[3].y = bearing.y; info.pos[3].y = bearing.y;
info.uv[3].x = l / m_atlasData->texture.resolution.x; info.uv[3].x = l / resolution.x;
info.uv[3].y = t / m_atlasData->texture.resolution.y; info.uv[3].y = t / resolution.y;
info.advance = advance; info.advance = advance;
} }

View File

@@ -7,29 +7,27 @@
#pragma once #pragma once
#include "IFontAtlasGenerator.hpp" #include "IFontAtlasGenerator.hpp"
#include "AtlasData.hpp"
#include "Math/AABB.hpp" #include "Math/AABB.hpp"
#include "Extensions/FreetypeHelper.hpp" #include "Extensions/FreetypeHelper.hpp"
#include <variant> #include <variant>
namespace OpenVulkano::Scene namespace OpenVulkano::Scene
{ {
class GlyphInfo;
class FontAtlasGeneratorBase : public IFontAtlasGenerator class FontAtlasGeneratorBase : public IFontAtlasGenerator
{ {
protected: protected:
int m_channelsCount; int m_channelsCount;
std::shared_ptr<AtlasData> m_atlasData; std::shared_ptr<FontAtlas> m_atlasData;
public: public:
FontAtlasGeneratorBase(const int channelsCount) : m_channelsCount(channelsCount) {} FontAtlasGeneratorBase(const int channelsCount) : m_channelsCount(channelsCount) {}
void SaveAtlasMetadataInfo(const std::string& outputFile, bool packIntoSingleFile = true) const override; [[nodiscard]] const std::shared_ptr<FontAtlas>& GetAtlas() const final { return m_atlasData; }
[[nodiscard]] const std::shared_ptr<AtlasData>& GetAtlasData() const override { return m_atlasData; }
[[nodiscard]] int GetAtlasChannelsCount() const { return m_channelsCount; } [[nodiscard]] int GetAtlasChannelsCount() const { return m_channelsCount; }
[[nodiscard]] static std::set<uint32_t> LoadAllGlyphs(const std::variant<std::string, Array<char>>& data); [[nodiscard]] static std::set<uint32_t> LoadAllGlyphs(const std::variant<std::string, Array<char>>& data);
protected: protected:
void SavePng(std::string output) const;
void SetupAtlasData(Math::Vector2ui textureResolution, double lineHeight, FontAtlasType::Type atlasType);
void SetGlyphData(GlyphInfo& info, Math::Vector2d bearing, Math::Vector2d size, const Math::AABB& aabb, double advance); void SetGlyphData(GlyphInfo& info, Math::Vector2d bearing, Math::Vector2d size, const Math::AABB& aabb, double advance);
[[nodiscard]] static std::string GetFreetypeErrorDescription(FT_Error error); [[nodiscard]] static std::string GetFreetypeErrorDescription(FT_Error error);
[[nodiscard]] static std::pair<FtLibraryRecPtr, FtFaceRecPtr> InitFreetype(const std::variant<std::string, Array<char>>& source); [[nodiscard]] static std::pair<FtLibraryRecPtr, FtFaceRecPtr> InitFreetype(const std::variant<std::string, Array<char>>& source);

View File

@@ -14,7 +14,7 @@
namespace OpenVulkano::Scene namespace OpenVulkano::Scene
{ {
struct AtlasData; struct FontAtlas;
class IFontAtlasGenerator class IFontAtlasGenerator
{ {
@@ -24,7 +24,6 @@ namespace OpenVulkano::Scene
const std::optional<std::string>& pngOutput = std::nullopt) = 0; const std::optional<std::string>& pngOutput = std::nullopt) = 0;
virtual void GenerateAtlas(const Array<char>& fontData, const std::set<uint32_t>& charset, virtual void GenerateAtlas(const Array<char>& fontData, const std::set<uint32_t>& charset,
const std::optional<std::string>& pngOutput = std::nullopt) = 0; const std::optional<std::string>& pngOutput = std::nullopt) = 0;
virtual void SaveAtlasMetadataInfo(const std::string& outputFile, bool packIntoSingleFile = true) const = 0; virtual const std::shared_ptr<FontAtlas>& GetAtlas() const = 0;
virtual const std::shared_ptr<AtlasData>& GetAtlasData() const = 0;
}; };
} }

View File

@@ -10,9 +10,10 @@
#include "Scene/Vertex.hpp" #include "Scene/Vertex.hpp"
#include "Scene/Shader/Shader.hpp" #include "Scene/Shader/Shader.hpp"
#include "Scene/IFontAtlasGenerator.hpp" #include "Scene/IFontAtlasGenerator.hpp"
#include "Base/Logger.hpp" #include "Scene/Text/FontAtlasType.hpp"
#include <optional> #include <optional>
namespace OpenVulkano::Scene namespace OpenVulkano::Scene
{ {
namespace namespace
@@ -68,14 +69,11 @@ namespace OpenVulkano::Scene
} }
} }
LabelDrawable::LabelDrawable(const std::shared_ptr<AtlasData>& atlasData, const LabelDrawableSettings& settings) LabelDrawable::LabelDrawable(const std::shared_ptr<FontAtlas>& atlasData, const LabelDrawableSettings& settings)
: Drawable(DrawEncoder::GetDrawEncoder<LabelDrawable>(), DrawPhase::MAIN), m_atlasData(atlasData) : Drawable(DrawEncoder::GetDrawEncoder<LabelDrawable>(), DrawPhase::MAIN), m_atlasData(atlasData)
, m_labelBuffer(sizeof(LabelUniformData), &m_labelData, 4) , m_labelBuffer(sizeof(LabelUniformData), &m_labelData, 4)
{ {
if (atlasData->glyphs.empty() || !atlasData->texture.size) if (!atlasData || !*atlasData) throw std::runtime_error("Can't create label drawable. Either glyphs or texture is empty");
{
throw std::runtime_error("Can't create label drawable. Either glyphs or texture is empty");
}
SetLabelSettings(settings); SetLabelSettings(settings);
SetShader(IsBillboard() ? &BACKGROUND_BILLBOARD_SHADER : &BACKGROUND_SHADER); SetShader(IsBillboard() ? &BACKGROUND_BILLBOARD_SHADER : &BACKGROUND_SHADER);
} }
@@ -97,9 +95,9 @@ namespace OpenVulkano::Scene
TextDrawable& textDrawable = m_texts.emplace_back(m_atlasData, config); TextDrawable& textDrawable = m_texts.emplace_back(m_atlasData, config);
textDrawable.GetConfig().backgroundColor.a = 0; // do not render glyph's background textDrawable.GetConfig().backgroundColor.a = 0; // do not render glyph's background
double lineHeight = m_atlasData->meta.lineHeight; double lineHeight = m_atlasData->GetLineHeight();
textDrawable.GenerateText(text, m_position); textDrawable.GenerateText(text, m_position);
textDrawable.SetShader(GetTextShader(m_atlasData->meta.atlasType, IsBillboard())); textDrawable.SetShader(GetTextShader(m_atlasData->GetAtlasType(), IsBillboard()));
m_bbox.Grow(textDrawable.GetBoundingBox()); m_bbox.Grow(textDrawable.GetBoundingBox());
// update position for next text entry // update position for next text entry
m_position.y = m_bbox.GetMin().y - lineHeight; m_position.y = m_bbox.GetMin().y - lineHeight;

View File

@@ -44,7 +44,7 @@ namespace OpenVulkano::Scene
class LabelDrawable final : public Drawable class LabelDrawable final : public Drawable
{ {
public: public:
LabelDrawable(const std::shared_ptr<AtlasData>& atlasData, const LabelDrawableSettings& settings = LabelDrawableSettings()); LabelDrawable(const std::shared_ptr<FontAtlas>& atlasData, const LabelDrawableSettings& settings = LabelDrawableSettings());
void AddText(const std::string& text, const TextConfig& config = TextConfig()); void AddText(const std::string& text, const TextConfig& config = TextConfig());
void SetLabelSettings(const LabelDrawableSettings& settings); void SetLabelSettings(const LabelDrawableSettings& settings);
@@ -61,7 +61,7 @@ namespace OpenVulkano::Scene
private: private:
LabelDrawableSettings m_settings; LabelDrawableSettings m_settings;
std::shared_ptr<AtlasData> m_atlasData; std::shared_ptr<FontAtlas> m_atlasData;
UniformBuffer m_labelBuffer; UniformBuffer m_labelBuffer;
LabelUniformData m_labelData; LabelUniformData m_labelData;
std::list<TextDrawable> m_texts; // Using list instead of vector for stable iterators std::list<TextDrawable> m_texts; // Using list instead of vector for stable iterators

View File

@@ -5,7 +5,7 @@
*/ */
#if __has_include("msdfgen.h") #if __has_include("msdfgen.h")
#include "Text/FontAtlas.hpp"
#include "SdfFontAtlasGenerator.hpp" #include "SdfFontAtlasGenerator.hpp"
#include "Base/Logger.hpp" #include "Base/Logger.hpp"
#include <msdfgen.h> #include <msdfgen.h>
@@ -106,7 +106,6 @@ namespace OpenVulkano::Scene
void SdfFontAtlasGeneratorGeneric<Channels>::Generate(FreetypeHandle* ft, FontHandle* font, const Charset& chset, void SdfFontAtlasGeneratorGeneric<Channels>::Generate(FreetypeHandle* ft, FontHandle* font, const Charset& chset,
const std::optional<std::string>& pngOutput) const std::optional<std::string>& pngOutput)
{ {
m_atlasData.reset(new AtlasData);
std::vector<GlyphGeometry> glyphsGeometry; std::vector<GlyphGeometry> glyphsGeometry;
// FontGeometry is a helper class that loads a set of glyphs from a single font. // FontGeometry is a helper class that loads a set of glyphs from a single font.
@@ -142,14 +141,14 @@ namespace OpenVulkano::Scene
generator.generate(glyphsGeometry.data(), glyphsGeometry.size()); generator.generate(glyphsGeometry.data(), glyphsGeometry.size());
int idx = 0; int idx = 0;
SetupAtlasData(Math::Vector3ui(width, height, 1), fontGeometry.getMetrics().lineHeight, m_atlasData = std::make_shared<FontAtlas>(Math::Vector2ui{ width, height }, fontGeometry.getMetrics().lineHeight,
channelsCount == 1 ? FontAtlasType::SDF : FontAtlasType::MSDF); channelsCount == 1 ? FontAtlasType::SDF : FontAtlasType::MSDF);
if constexpr (Channels == 3) if constexpr (Channels == 3)
{ {
// store RGB as RGBA // store RGB as RGBA
const BitmapConstRef<msdfgen::byte, 3> storage = generator.atlasStorage(); const BitmapConstRef<msdfgen::byte, 3> storage = generator.atlasStorage();
msdfgen::byte* data = static_cast<msdfgen::byte*>(m_atlasData->img->data.Data()); msdfgen::byte* data = static_cast<msdfgen::byte*>(m_atlasData->GetTexture()->textureBuffer);
for (size_t srcPos = 0, dstPos = 0; srcPos < width * height * 3; srcPos += 3, dstPos += 4) for (size_t srcPos = 0, dstPos = 0; srcPos < width * height * 3; srcPos += 3, dstPos += 4)
{ {
data[dstPos] = storage.pixels[srcPos]; data[dstPos] = storage.pixels[srcPos];
@@ -161,7 +160,7 @@ namespace OpenVulkano::Scene
else else
{ {
const msdfgen::BitmapConstRef<msdfgen::byte, 1>& storage = generator.atlasStorage(); const msdfgen::BitmapConstRef<msdfgen::byte, 1>& storage = generator.atlasStorage();
memcpy(m_atlasData->img->data.Data(), storage.pixels, width * height); memcpy(m_atlasData->GetTexture()->textureBuffer, storage.pixels, width * height);
} }
struct Bbox struct Bbox
@@ -171,7 +170,7 @@ namespace OpenVulkano::Scene
for (const auto& glyph: glyphsGeometry) for (const auto& glyph: glyphsGeometry)
{ {
GlyphInfo& info = m_atlasData->glyphs[glyph.getCodepoint()]; GlyphInfo& info = m_atlasData->GetGlyphs()[glyph.getCodepoint()];
const GlyphBox& glyphBox = generator.getLayout()[idx++]; const GlyphBox& glyphBox = generator.getLayout()[idx++];
Bbox glyphBaselineBbox, glyphAtlasBbox; Bbox glyphBaselineBbox, glyphAtlasBbox;
@@ -195,7 +194,7 @@ namespace OpenVulkano::Scene
SetGlyphData(info, { bearingX, bearingY }, { w, h }, glyphAtlasAABB, glyphBox.advance); SetGlyphData(info, { bearingX, bearingY }, { w, h }, glyphAtlasAABB, glyphBox.advance);
} }
if (pngOutput && !pngOutput->empty()) { SavePng(pngOutput.value()); } if (pngOutput && !pngOutput->empty()) { m_atlasData->Save(*pngOutput); }
destroyFont(font); destroyFont(font);
deinitializeFreetype(ft); deinitializeFreetype(ft);
} }

View File

@@ -0,0 +1,115 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "FontAtlas.hpp"
#include "Base/Logger.hpp"
#include "Image/ImageLoader.hpp"
#include "Extensions/STBZlibCompressor.hpp"
#include <fstream>
#define STBI_MSC_SECURE_CRT
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STBIW_ZLIB_COMPRESS Extensions::STBZlibCompressor
#include <stb_image_write.h>
namespace OpenVulkano::Scene
{
FontAtlas::FontAtlas(const std::filesystem::path& path)
{
auto content = Utils::ReadFile(path);
Load(content);
}
void FontAtlas::Save(const std::filesystem::path& path) const
{
if (!*this) { Logger::DATA->warn("Can't save empty font atlas!"); return; };
stbi_flip_vertically_on_write(1);
stbi_write_png(path.c_str(), m_texture.resolution.x, m_texture.resolution.y, m_texture.format.GetBytesPerPixel(),
m_texture.textureBuffer, m_texture.format.GetBytesPerPixel() * m_texture.resolution.x);
std::fstream fs(path, std::ios_base::out | std::ios_base::binary | std::ios_base::app);
fs.write(reinterpret_cast<const char*>(&m_metadata), sizeof(Metadata));
uint64_t metadataBytes = sizeof(Metadata);
for (const auto& [key, val] : m_glyphs)
{
fs.write(reinterpret_cast<const char*>(&key), sizeof(uint32_t));
fs.write(reinterpret_cast<const char*>(&val), sizeof(GlyphInfo));
metadataBytes += sizeof(uint32_t) + sizeof(GlyphInfo);
}
fs.write(reinterpret_cast<const char*>(&metadataBytes), sizeof(uint64_t));
std::array<uint8_t, 4> flags = { 1, 1, 0, 0 };
fs.write(reinterpret_cast<const char*>(&flags), sizeof(std::array<uint8_t, 4>));
fs.close();
}
void FontAtlas::Load(const std::span<char> data)
{
if (data.size() < 16) { Logger::DATA->warn("Font atlas file is invalid!"); return; };
uint8_t flags[4] = { 0, 0, 0, 0 };
std::memcpy(&flags, data.data() + data.size() - sizeof(flags), sizeof(flags));
size_t headerSize = sizeof(flags) + sizeof(uint64_t);
uint64_t metadataSize = *reinterpret_cast<uint64_t*>(data.data() + data.size() - headerSize);
char* metadata = data.data() + data.size() - headerSize - metadataSize;
if (flags[0] == 0) throw std::runtime_error("No longer support loading of unpacked font atlas!");
LoadImage({ data.data(), data.size() - headerSize - metadataSize });
std::span metadataSpan(metadata, metadataSize);
if (flags[1] == 0) LoadLegacy(metadataSpan);
else LoadNew(metadataSpan);
if (GetAtlasType() >= FontAtlasType::BITMAP) m_texture.m_samplerConfig = &SamplerConfig::NEAREST;
}
void FontAtlas::LoadLegacy(const std::span<char> data)
{
const char* d = data.data();
const char* end = data.data() + data.size();
uint32_t unicode = 0;
std::memcpy(&m_metadata, d, sizeof(Metadata));
d += sizeof(Metadata);
while (d < end)
{
std::memcpy(&unicode, d, sizeof(uint32_t));
d += sizeof(uint32_t);
GlyphInfo& info = m_glyphs[unicode];
for (int i = 0; i < 4; i++)
{
std::memcpy(&info.pos[i], d, sizeof(GlyphInfo::pos) / 4);
d += sizeof(GlyphInfo::pos) / 2;
}
std::memcpy(&info.uv, d, sizeof(GlyphInfo::uv));
d += sizeof(GlyphInfo::uv);
std::memcpy(&info.advance, d, sizeof(GlyphInfo::advance));
d += sizeof(GlyphInfo::advance) * 2;
}
}
void FontAtlas::LoadNew(const std::span<char> data)
{
}
void FontAtlas::LoadImage(const std::span<char> data)
{
auto img = Image::IImageLoader::loadData(reinterpret_cast<const uint8_t*>(data.data()), data.size());
m_imgData = std::move(img->data);
m_texture.format = img->dataFormat;
m_texture.resolution = img->resolution;
m_texture.size = m_imgData.Size();
m_texture.textureBuffer = m_imgData.Data();
}
void FontAtlas::Init(const Math::Vector2ui textureResolution, const double lineHeight, const FontAtlasType atlasType)
{
m_metadata = { lineHeight, atlasType };
m_texture.format = atlasType.GetChannelCount() == 1 ? DataFormat::R8_UNORM : DataFormat::R8G8B8A8_UNORM;
m_texture.resolution = { textureResolution, 1 };
m_imgData = Array<uint8_t>(m_texture.format.CalculatedSize(m_texture.resolution.x, m_texture.resolution.y));
m_texture.textureBuffer = m_imgData.Data();
m_texture.size = m_imgData.Size();
if (atlasType >= FontAtlasType::BITMAP) m_texture.m_samplerConfig = &SamplerConfig::NEAREST;
}
}

View File

@@ -0,0 +1,62 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "FontAtlasType.hpp"
#include "Math/Math.hpp"
#include "Data/Containers/Array.hpp"
#include "Scene/Texture.hpp"
#include <map>
#include <filesystem>
namespace OpenVulkano::Scene
{
struct GlyphInfo
{
//GlyphGeometry geometry;
//GlyphBox glyphBox;
Math::Vector2f_SIMD pos[4] = {};
Math::Vector2f_SIMD uv[4] = {};
double advance = 0;
};
class FontAtlas
{
struct Metadata
{
double lineHeight = 0;
FontAtlasType atlasType = FontAtlasType::UNKNOWN;
};
std::map<uint32_t, GlyphInfo> m_glyphs;
Metadata m_metadata;
Array<uint8_t> m_imgData;
Texture m_texture;
void LoadLegacy(std::span<char> data);
void LoadNew(std::span<char> data);
void LoadImage(std::span<char> data);
public:
FontAtlas() = default;
FontAtlas(const Math::Vector2ui textureResolution, const double lineHeight, const FontAtlasType atlasType) { Init(textureResolution, lineHeight, atlasType); }
FontAtlas(const std::filesystem::path& path);
FontAtlas(const std::span<char> data) { Load(data); }
void Init(Math::Vector2ui textureResolution, double lineHeight, FontAtlasType atlasType);
void Save(const std::filesystem::path& path) const;
void Load(std::span<char> data);
[[nodiscard]] operator bool() const { return !m_glyphs.empty() && m_texture.textureBuffer; }
[[nodiscard]] Texture* GetTexture() { return &m_texture; }
[[nodiscard]] decltype(m_glyphs)& GetGlyphs() { return m_glyphs; }
[[nodiscard]] decltype(Metadata::lineHeight) GetLineHeight() const { return m_metadata.lineHeight;}
[[nodiscard]] FontAtlasType GetAtlasType() const { return m_metadata.atlasType;}
};
}

View File

@@ -23,6 +23,8 @@ namespace OpenVulkano::Scene
static constexpr std::string_view DEFAULT_FG_SHADERS[] = { "Shader/sdfText", "Shader/msdfText", "Shader/text" }; static constexpr std::string_view DEFAULT_FG_SHADERS[] = { "Shader/sdfText", "Shader/msdfText", "Shader/text" };
static constexpr uint32_t CHANNEL_COUNT[] = { 1, 4, 1, 4, 0 };
constexpr FontAtlasType(Type type) : m_type(type) {} constexpr FontAtlasType(Type type) : m_type(type) {}
[[nodiscard]] constexpr Type GetType() const { return m_type; } [[nodiscard]] constexpr Type GetType() const { return m_type; }
@@ -34,8 +36,13 @@ namespace OpenVulkano::Scene
return DEFAULT_FG_SHADERS[static_cast<int>(m_type)]; return DEFAULT_FG_SHADERS[static_cast<int>(m_type)];
} }
[[nodiscard]] constexpr uint32_t GetChannelCount() const { return CHANNEL_COUNT[static_cast<int>(m_type)]; }
[[nodiscard]] constexpr operator Type() const { return m_type; } [[nodiscard]] constexpr operator Type() const { return m_type; }
[[nodiscard]] constexpr auto operator<=>(const FontAtlasType rhs) const { return m_type <=> rhs.m_type; }
[[nodiscard]] constexpr auto operator<=>(const Type rhs) const { return m_type <=> rhs; }
private: private:
Type m_type; Type m_type;
}; };

View File

@@ -9,10 +9,8 @@
#include "Shader/Shader.hpp" #include "Shader/Shader.hpp"
#include "Scene/IFontAtlasGenerator.hpp" #include "Scene/IFontAtlasGenerator.hpp"
#include "Base/Logger.hpp" #include "Base/Logger.hpp"
#include "Host/ResourceLoader.hpp"
#include "Image/ImageLoader.hpp" #include "Image/ImageLoader.hpp"
#include "DataFormat.hpp" #include "DataFormat.hpp"
#include "Base/Logger.hpp"
#include <fstream> #include <fstream>
#include <utf8.h> #include <utf8.h>
@@ -56,88 +54,30 @@ namespace OpenVulkano::Scene
: Drawable(DrawEncoder::GetDrawEncoder<TextDrawable>()), m_cfg(config) : Drawable(DrawEncoder::GetDrawEncoder<TextDrawable>()), m_cfg(config)
{} {}
TextDrawable::TextDrawable(const Array<char>& atlasMetadata, const TextConfig& config)
: TextDrawable(atlasMetadata, nullptr, config)
{}
TextDrawable::TextDrawable(const std::string& atlasMetadataFile, const TextConfig& config) TextDrawable::TextDrawable(const std::string& atlasMetadataFile, const TextConfig& config)
: TextDrawable(Utils::ReadFile(atlasMetadataFile), nullptr, config) : TextDrawable(Utils::ReadFile(atlasMetadataFile), config)
{} {}
TextDrawable::TextDrawable(const std::string& atlasMetadataFile, Texture* atlasTex, const TextConfig& config) TextDrawable::TextDrawable(const Array<char>& atlasMetadata, const TextConfig& config)
: TextDrawable(Utils::ReadFile(atlasMetadataFile), atlasTex, config)
{}
TextDrawable::TextDrawable(const Array<char>& atlasMetadata, Texture* atlasTex, const TextConfig& config)
: Drawable(DrawEncoder::GetDrawEncoder<TextDrawable>()), m_cfg(config) : Drawable(DrawEncoder::GetDrawEncoder<TextDrawable>()), m_cfg(config)
{ {
uint32_t isPacked; m_atlasData = std::make_shared<FontAtlas>(atlasMetadata);
std::memcpy(&isPacked, atlasMetadata.Data() + (atlasMetadata.Size() - sizeof(uint32_t)), sizeof(uint32_t));
uint64_t metadataBytes;
std::memcpy(&metadataBytes, atlasMetadata.Data() + (atlasMetadata.Size() - sizeof(uint32_t) - sizeof(uint64_t)),
sizeof(uint64_t));
uint64_t offsetToMetadata = atlasMetadata.Size() - metadataBytes - sizeof(uint32_t) - sizeof(uint64_t);
m_atlasData = std::make_shared<AtlasData>();
if (isPacked)
{
Texture* texture = &m_atlasData->texture;
m_atlasData->img = Image::IImageLoader::loadData(reinterpret_cast<const uint8_t*>(atlasMetadata.Data()), offsetToMetadata);
texture->format = m_atlasData->img->dataFormat;
texture->resolution = m_atlasData->img->resolution;
texture->size = m_atlasData->img->data.Size();
texture->textureBuffer = m_atlasData->img->data.Data();
}
else
{
if (atlasTex == nullptr) { throw std::runtime_error("Atlas texture cannot be null with non-packed atlas metadata"); }
m_atlasData->texture = *atlasTex;
}
// metadata info
size_t read_bytes = offsetToMetadata;
size_t readMetadataBytes = 0;
uint32_t unicode = 0;
std::memcpy(&m_atlasData->meta, atlasMetadata.Data() + read_bytes, sizeof(AtlasMetadata));
read_bytes += sizeof(AtlasMetadata);
readMetadataBytes += sizeof(AtlasMetadata);
while (readMetadataBytes < metadataBytes)
{
std::memcpy(&unicode, atlasMetadata.Data() + read_bytes, sizeof(uint32_t));
read_bytes += sizeof(uint32_t);
readMetadataBytes += sizeof(uint32_t);
GlyphInfo& info = m_atlasData->glyphs[unicode];
for (int i = 0; i < 4; i++)
{
std::memcpy(&info.pos[i], atlasMetadata.Data() + read_bytes, sizeof(GlyphInfo::pos) / 4);
read_bytes += sizeof(GlyphInfo::pos) / 2;
}
std::memcpy(&info.uv, atlasMetadata.Data() + read_bytes, sizeof(GlyphInfo::uv));
read_bytes += sizeof(GlyphInfo::uv);
std::memcpy(&info.advance, atlasMetadata.Data() + read_bytes, sizeof(GlyphInfo::advance));
read_bytes += sizeof(GlyphInfo::advance) * 2;
readMetadataBytes += sizeof(GlyphInfo) + sizeof(GlyphInfo::pos) + sizeof(double);
}
if (m_atlasData->meta.atlasType == FontAtlasType::BITMAP)
{
m_atlasData->texture.m_samplerConfig = &SamplerConfig::NEAREST;
}
} }
TextDrawable::TextDrawable(const std::shared_ptr<AtlasData>& atlasData, const TextConfig& config) TextDrawable::TextDrawable(const std::shared_ptr<FontAtlas>& atlasData, const TextConfig& config)
: Drawable(DrawEncoder::GetDrawEncoder<TextDrawable>()), m_atlasData(atlasData), m_cfg(config) : Drawable(DrawEncoder::GetDrawEncoder<TextDrawable>()), m_atlasData(atlasData), m_cfg(config)
{ {
if (!atlasData || !*atlasData) throw std::runtime_error("Cannot initialize text drawable with empty atlas data"); if (!atlasData || !*atlasData) throw std::runtime_error("Cannot initialize text drawable with empty atlas data");
} }
uint32_t TextDrawable::GetFallbackGlyph() const uint32_t TextDrawable::GetFallbackGlyph() const
{ { //TODO move into FontAtlas
if (m_atlasData->glyphs.find(MISSING_GLYPH_SYMBOL) != m_atlasData->glyphs.end()) if (m_atlasData->GetGlyphs().contains(MISSING_GLYPH_SYMBOL))
{ {
return MISSING_GLYPH_SYMBOL; return MISSING_GLYPH_SYMBOL;
} }
Logger::RENDER->warn("Could not find glyph for character ? to use as fallback. Using first glyph instead"); Logger::RENDER->warn("Could not find glyph for character ? to use as fallback. Using first glyph instead");
return m_atlasData->glyphs.begin()->first; return m_atlasData->GetGlyphs().begin()->first;
} }
void TextDrawable::GenerateText(const std::string& text, const Math::Vector2f& pos) void TextDrawable::GenerateText(const std::string& text, const Math::Vector2f& pos)
@@ -151,11 +91,10 @@ namespace OpenVulkano::Scene
const size_t len = utf8::distance(text.begin(), text.end()); const size_t len = utf8::distance(text.begin(), text.end());
m_vertexBuffer.Close(); m_vertexBuffer.Close();
TextGlyphVertex* vertices = m_vertexBuffer.Init<TextGlyphVertex>(len); TextGlyphVertex* vertices = m_vertexBuffer.Init<TextGlyphVertex>(len);
std::map<uint32_t, GlyphInfo>* symbols = &m_atlasData->glyphs; const std::map<uint32_t, GlyphInfo>& symbols = m_atlasData->GetGlyphs();
AtlasMetadata* meta = &m_atlasData->meta;
double cursorX = pos.x; double cursorX = pos.x;
const double lineHeight = meta->lineHeight; const double lineHeight = m_atlasData->GetLineHeight();
double posY = pos.y; double posY = pos.y;
Math::Vector3f bmin(pos, 0), bmax(pos, 0); Math::Vector3f bmin(pos, 0), bmax(pos, 0);
for (auto begin = text.begin(), end = text.end(); begin != end;) for (auto begin = text.begin(), end = text.end(); begin != end;)
@@ -169,13 +108,13 @@ namespace OpenVulkano::Scene
} }
// TODO handle special chars // TODO handle special chars
if (!symbols->contains(c)) if (!symbols.contains(c))
{ {
Logger::RENDER->warn("Could not find glyph for character {}, using fallback", c); Logger::RENDER->warn("Could not find glyph for character {}, using fallback", c);
c = fallbackGlyph; c = fallbackGlyph;
} }
GlyphInfo& info = symbols->at(c); const GlyphInfo& info = symbols.at(c);
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
@@ -200,10 +139,10 @@ namespace OpenVulkano::Scene
bmin.x = vertices->position[0].x; bmin.x = vertices->position[0].x;
m_bbox.Init(bmin, bmax); m_bbox.Init(bmin, bmax);
if (!GetShader()) SetShader(GetDefaultShader(m_atlasData->meta.atlasType)); if (!GetShader()) SetShader(GetDefaultShader(m_atlasData->GetAtlasType()));
} }
void TextDrawable::SetAtlasData(const std::shared_ptr<AtlasData>& atlasData) void TextDrawable::SetAtlasData(const std::shared_ptr<FontAtlas>& atlasData)
{ {
if (!atlasData || !*atlasData) throw std::runtime_error("Cannot initialize text drawable with empty atlas data"); if (!atlasData || !*atlasData) throw std::runtime_error("Cannot initialize text drawable with empty atlas data");
m_atlasData = atlasData; m_atlasData = atlasData;

View File

@@ -9,11 +9,12 @@
#include "Drawable.hpp" #include "Drawable.hpp"
#include "Texture.hpp" #include "Texture.hpp"
#include "VertexBuffer.hpp" #include "VertexBuffer.hpp"
#include "AtlasData.hpp"
#include "Image/Image.hpp" #include "Image/Image.hpp"
#include "Text/FontAtlas.hpp"
namespace OpenVulkano::Scene namespace OpenVulkano::Scene
{ {
class FontAtlas;
class IFontAtlasGenerator; class IFontAtlasGenerator;
struct TextConfig struct TextConfig
@@ -33,7 +34,7 @@ namespace OpenVulkano::Scene
class TextDrawable : public Drawable class TextDrawable : public Drawable
{ {
VertexBuffer m_vertexBuffer; VertexBuffer m_vertexBuffer;
std::shared_ptr<AtlasData> m_atlasData; std::shared_ptr<FontAtlas> m_atlasData;
Math::AABB2f m_bbox; Math::AABB2f m_bbox;
std::string m_text; std::string m_text;
size_t m_symbolCount = 0; size_t m_symbolCount = 0;
@@ -43,23 +44,21 @@ namespace OpenVulkano::Scene
public: public:
TextDrawable(const TextConfig& config = TextConfig()); TextDrawable(const TextConfig& config = TextConfig());
TextDrawable(const Array<char>& atlasMetadata, const TextConfig& config = TextConfig());
TextDrawable(const std::string& atlasMetadataFile, const TextConfig& config = TextConfig()); TextDrawable(const std::string& atlasMetadataFile, const TextConfig& config = TextConfig());
TextDrawable(const std::string& atlasMetadataFile, Texture* atlasTex, const TextConfig& config = TextConfig()); TextDrawable(const Array<char>& atlasMetadata, const TextConfig& config = TextConfig());
TextDrawable(const Array<char>& atlasMetadata, Texture* atlasTex, const TextConfig& config = TextConfig()); TextDrawable(const std::shared_ptr<FontAtlas>& atlasData, const TextConfig& config = TextConfig());
TextDrawable(const std::shared_ptr<AtlasData>& atlasData, const TextConfig& config = TextConfig());
void GenerateText(const std::string& text, const Math::Vector2f& pos = Math::Vector2f(0.f)); void GenerateText(const std::string& text, const Math::Vector2f& pos = Math::Vector2f(0.f));
void SetConfig(const TextConfig& cfg) { m_cfg = cfg; } void SetConfig(const TextConfig& cfg) { m_cfg = cfg; }
void SetAtlasData(const std::shared_ptr<AtlasData>& atlasData); void SetAtlasData(const std::shared_ptr<FontAtlas>& atlasData);
[[nodiscard]] Math::AABB2f& GetBoundingBox() { return m_bbox; } [[nodiscard]] Math::AABB2f& GetBoundingBox() { return m_bbox; }
[[nodiscard]] TextConfig& GetConfig() { return m_cfg; } [[nodiscard]] TextConfig& GetConfig() { return m_cfg; }
[[nodiscard]] const std::string& GetText() const { return m_text; } [[nodiscard]] const std::string& GetText() const { return m_text; }
[[nodiscard]] const std::shared_ptr<AtlasData>& GetAtlasData() { return m_atlasData; } [[nodiscard]] const std::shared_ptr<FontAtlas>& GetAtlasData() { return m_atlasData; }
[[nodiscard]] VertexBuffer* GetVertexBuffer() { return &m_vertexBuffer; } [[nodiscard]] VertexBuffer* GetVertexBuffer() { return &m_vertexBuffer; }
[[nodiscard]] Texture* GetTexture() { return &m_atlasData->texture; } [[nodiscard]] Texture* GetTexture() { return m_atlasData->GetTexture(); }
[[nodiscard]] size_t GetSymbolCount() const { return m_symbolCount; } [[nodiscard]] size_t GetSymbolCount() const { return m_symbolCount; }
[[nodiscard]] static Shader MakeDefaultShader(FontAtlasType type); [[nodiscard]] static Shader MakeDefaultShader(FontAtlasType type);