working version of text rendering

This commit is contained in:
ohyzha
2024-08-02 09:52:26 +03:00
parent 9b58ba5f55
commit e69a553b18
13 changed files with 491 additions and 102 deletions

View File

@@ -0,0 +1,95 @@
/*
* 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 "FontAtlasGenerator.hpp"
#include "Base/Logger.hpp"
namespace OpenVulkano::Scene
{
using namespace msdfgen;
using namespace msdf_atlas;
void FontAtlasGenerator::GenerateAtlas(const std::string& fontFile, const std::string& outputFile, const Charset& chset)
{
if (chset.empty())
{
return;
}
// TODO: dynamic atlas and add only those symbols which are not present yet in current atlas
Charset absentSymbols;
for (auto c : chset)
{
if (!m_symbols.contains(c))
{
absentSymbols.add(c);
}
}
if (m_loadedFont == fontFile && absentSymbols.empty())
{
return;
}
m_symbols.clear();
m_loadedFont = fontFile;
std::vector<GlyphGeometry> glyphsGeometry;
std::pair<FreetypeHandle*, FontHandle*> handlers = GetHandlers(fontFile);
FreetypeHandle* ft = handlers.first;
FontHandle* font = handlers.second;
// FontGeometry is a helper class that loads a set of glyphs from a single font.
FontGeometry fontGeometry(&glyphsGeometry);
fontGeometry.loadCharset(font, 1, absentSymbols);
TightAtlasPacker packer;
packer.setDimensionsConstraint(DimensionsConstraint::SQUARE);
int width = 1024, height = 1024;
packer.setDimensions(width, height);
// more value - more sdf impact
packer.setPixelRange(26.0);
packer.setMiterLimit(1.0);
packer.pack(glyphsGeometry.data(), glyphsGeometry.size());
m_generator.resize(width, height);
GeneratorAttributes attributes;
m_generator.setAttributes(attributes);
m_generator.setThreadCount(4);
m_generator.generate(glyphsGeometry.data(), glyphsGeometry.size());
int idx = 0;
BitmapConstRef<byte, 1> storage = m_generator.atlasStorage();
for (const auto& glyph: glyphsGeometry)
{
unicode_t c = static_cast<char8_t>(glyph.getCodepoint());
GlyphInfo info;
info.texture.resolution = Math::Vector3ui(storage.width, storage.height, 1);
info.texture.textureBuffer = (msdfgen::byte*)storage.pixels;
info.texture.format = OpenVulkano::DataFormat::R8_UNORM;
info.texture.size = storage.width * storage.height * 1; // 1 channel
info.geometry = glyph;
info.glyphBox = m_generator.getLayout()[idx++];
m_symbols[c] = std::move(info);
}
savePng(m_generator.atlasStorage(), outputFile.c_str());
destroyFont(font);
deinitializeFreetype(ft);
}
std::pair<FreetypeHandle*, FontHandle*> FontAtlasGenerator::GetHandlers(const std::string& fontFile)
{
FreetypeHandle* ft = initializeFreetype();
if (!ft)
{
throw std::runtime_error("Failed to initialize freetype");
}
FontHandle* font = loadFont(ft, fontFile.data());
if (!font)
{
deinitializeFreetype(ft);
throw std::runtime_error(fmt::format("Failed to load font from file {0}", fontFile.data()));
}
return { ft, font };
}
}

View File

@@ -0,0 +1,41 @@
/*
* 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 <string>
#include <map>
#include "Scene/Texture.hpp"
#include "msdfgen.h"
#include "msdfgen-ext.h"
#include "msdf-atlas-gen/msdf-atlas-gen.h"
namespace OpenVulkano::Scene
{
using namespace msdfgen;
using namespace msdf_atlas;
using namespace OpenVulkano::Scene;
struct GlyphInfo
{
GlyphGeometry geometry;
GlyphBox glyphBox;
Texture texture;
};
class FontAtlasGenerator
{
public:
void GenerateAtlas(const std::string& fontFile, const std::string& outputFile, const Charset& = Charset::ASCII);
std::map<unicode_t, GlyphInfo>& GetAtlasInfo() { return m_symbols; }
private:
std::pair<FreetypeHandle*, FontHandle*> GetHandlers(const std::string& fontFile);
private:
ImmediateAtlasGenerator<float, 1, sdfGenerator, BitmapAtlasStorage<msdfgen::byte, 1>> m_generator;
std::map<unicode_t, GlyphInfo> m_symbols;
std::string m_loadedFont;
};
}

View File

@@ -192,18 +192,17 @@ namespace OpenVulkano::Scene
#endif
}
void Geometry::SetIndices(const uint32_t* data, uint32_t size, uint32_t offset) const
void Geometry::SetIndices(const uint32_t* data, uint32_t size, uint32_t indicesOffset) const
{
size += offset;
for(; offset < size; offset++)
for(uint32_t i = 0; i < size; i++)
{
if (indexType == VertexIndexType::UINT16)
{
static_cast<uint16_t*>(indices)[offset] = static_cast<uint16_t>(data[offset]);
static_cast<uint16_t*>(indices)[i + indicesOffset] = static_cast<uint16_t>(data[i]);
}
else
{
static_cast<uint32_t*>(indices)[offset] = data[offset];
static_cast<uint32_t*>(indices)[i + indicesOffset] = data[i];
}
}
}

View File

@@ -60,7 +60,7 @@ namespace OpenVulkano
void Init(aiMesh* mesh);
void SetIndices(const uint32_t* data, uint32_t size, uint32_t offset = 0) const;
void SetIndices(const uint32_t* data, uint32_t size, uint32_t indicesOffset = 0) const;
void Close() override;

View File

@@ -16,14 +16,16 @@ namespace OpenVulkano::Scene
class SimpleDrawable : public Drawable
{
protected:
Geometry* m_mesh = nullptr;
Material* m_material = nullptr;
UniformBuffer* m_uniBuffer = nullptr;
public:
SimpleDrawable(const DrawPhase phase = DrawPhase::MAIN)
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), phase)
{}
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), phase)
{
}
explicit SimpleDrawable(const SimpleDrawable* toCopy)
: Drawable(DrawEncoder::GetDrawEncoder<SimpleDrawable>(), toCopy->GetDrawPhase())

View File

@@ -5,44 +5,123 @@
*/
#include "Text.hpp"
#include "Scene/Geometry.hpp"
#include "Scene/Material.hpp"
#include "Scene/Vertex.hpp"
#include "Scene/UniformBuffer.hpp"
#include "Scene/FontAtlasGenerator.hpp"
#include "Base/Logger.hpp"
#include "fmt/core.h"
#include "msdfgen.h"
#include "msdfgen-ext.h"
#include "msdf-atlas-gen/msdf-atlas-gen.h"
namespace OpenVulkano::Scene
{
using namespace msdfgen;
using namespace msdf_atlas;
void Text::Init(const std::string_view fontFile, char8_t symbol, const std::string_view outputFile)
Text::~Text()
{
delete m_mesh;
delete m_material;
}
void Text::GenerateText(const std::string& text, const Math::Vector3f& pos)
{
FreetypeHandle *ft = initializeFreetype();
if (!ft)
if (!m_fontAtlasGenerator)
{
throw std::runtime_error("Failed to initialize freetype");
Logger::RENDER->error("Can't draw text. FontAtlasGenerator is nullptr");
return;
}
FontHandle *font = loadFont(ft, fontFile.data());
if (!font)
if (m_mesh)
{
deinitializeFreetype(ft);
throw std::runtime_error(fmt::format("Failed to load font freetype from file {0}", fontFile.data()));
delete m_mesh;
m_mesh = nullptr;
}
if (m_material)
{
delete m_material;
m_material = nullptr;
}
if (text.empty())
{
return;
}
std::map<unicode_t, GlyphInfo>& symbols = m_fontAtlasGenerator->GetAtlasInfo();
if (symbols.empty())
{
throw std::runtime_error("Glyphs are not loaded");
}
Shape shape;
if (loadGlyph(shape, font, symbol, FONT_SCALING_EM_NORMALIZED))
m_mesh = new Geometry();
m_material = new Material();
m_mesh->freeAfterUpload = false;
m_mesh->Init(text.size() * 4, text.size() * 6);
struct Bbox
{
shape.normalize();
Bitmap<float, 1> sdf(m_cfg.outputSize, m_cfg.outputSize);
// scale, translation (in em's)
Projection proj(m_cfg.outputSize, Vector2(0.125, 0.125));
// distance mapping
Range rng(0.075);
SDFTransformation t(proj, rng);
generateSDF(sdf, shape, t);
savePng(sdf, outputFile.data());
double l = 0, r = 0, t = 0, b = 0;
};
double cursorX = pos.x;
for (size_t i = 0; i < text.size(); i++)
{
unicode_t c = text[i];
if (symbols.find(c) != symbols.end())
{
Bbox glyphBaselineBbox, glyphAtlasBbox;
int vIdx = i * 4;
uint32_t indices[] = { 1 + vIdx, 2 + vIdx, 3 + vIdx, 1 + vIdx, 3 + vIdx, 0 + vIdx };
GlyphInfo& info = symbols.at(c);
info.geometry.getQuadPlaneBounds(glyphBaselineBbox.l, glyphBaselineBbox.b, glyphBaselineBbox.r,
glyphBaselineBbox.t);
info.geometry.getQuadAtlasBounds(glyphAtlasBbox.l, glyphAtlasBbox.b, glyphAtlasBbox.r,
glyphAtlasBbox.t);
double bearingX = info.glyphBox.bounds.l;
double bearingY = info.glyphBox.bounds.t;
double w = glyphBaselineBbox.r - glyphBaselineBbox.l;
double h = glyphBaselineBbox.t - glyphBaselineBbox.b;
double l = glyphAtlasBbox.l;
double r = glyphAtlasBbox.r;
double t = glyphAtlasBbox.t;
double b = glyphAtlasBbox.b;
double ax = cursorX + bearingX;
double ay = pos.y - (h - bearingY);
m_material->texture = &info.texture;
m_mesh->vertices[vIdx].position.x = ax;
m_mesh->vertices[vIdx].position.y = ay;
m_mesh->vertices[vIdx].position.z = 1;
m_mesh->vertices[vIdx].textureCoordinates.x = l / info.texture.resolution.x;
m_mesh->vertices[vIdx].textureCoordinates.y = b / info.texture.resolution.y;
m_mesh->vertices[vIdx + 1].position.x = ax + w;
m_mesh->vertices[vIdx + 1].position.y = ay;
m_mesh->vertices[vIdx + 1].position.z = 1;
m_mesh->vertices[vIdx + 1].textureCoordinates.x = r / info.texture.resolution.x;
m_mesh->vertices[vIdx + 1].textureCoordinates.y = b / info.texture.resolution.y;
m_mesh->vertices[vIdx + 2].position.x = ax + w;
m_mesh->vertices[vIdx + 2].position.y = ay + h;
m_mesh->vertices[vIdx + 2].position.z = 1;
m_mesh->vertices[vIdx + 2].textureCoordinates.x = r / info.texture.resolution.x;
m_mesh->vertices[vIdx + 2].textureCoordinates.y = t / info.texture.resolution.y;
m_mesh->vertices[vIdx + 3].position.x = ax;
m_mesh->vertices[vIdx + 3].position.y = ay + h;
m_mesh->vertices[vIdx + 3].position.z = 1;
m_mesh->vertices[vIdx + 3].textureCoordinates.x = l / info.texture.resolution.x;
m_mesh->vertices[vIdx + 3].textureCoordinates.y = t / info.texture.resolution.y;
m_mesh->SetIndices(indices, 6, 6 * i);
// TODO: change to lower value(or ideally remove completely) to avoid overlapping and make less space between symbols
// when setting for depth comparison operator will be available( <= )
cursorX += info.glyphBox.advance +0.08;
}
else
{
// throw ? replace with ? character (if available) ?
Logger::RENDER->error(fmt::format("Could not find glyph for character", c));
}
}
destroyFont(font);
deinitializeFreetype(ft);
}
}

View File

@@ -11,20 +11,24 @@
#include "Math/Math.hpp"
#include "DataFormat.hpp"
#include "SimpleDrawable.hpp"
#include "FontAtlasGenerator.hpp"
#include "Texture.hpp"
#include "msdfgen.h"
#include "msdfgen-ext.h"
#include "msdf-atlas-gen/msdf-atlas-gen.h"
namespace OpenVulkano::Scene
{
//using namespace msdfgen;
//using namespace msdf_atlas;
using namespace msdfgen;
using namespace msdf_atlas;
struct TextConfig
{
Math::Vector4f textColor = { 1, 1, 1, 0 }; // vec4 to match paddding (multiple of 16)
Math::Vector3f borderColor = { 1, 0, 0 };
int outputSize = 256;
float threshold = 0.5f;
float borderSize = 0.2f;
float smoothing = 1.f/16.f;
float threshold = 0.4f;
float borderSize = 0.05f;
float smoothing = 1.f/32.f;
bool applyBorder = false;
//bool sdfMultiChannel = false;
};
@@ -32,12 +36,16 @@ namespace OpenVulkano::Scene
class Text : public SimpleDrawable
{
public:
Text(const TextConfig& cfg) : m_cfg(cfg) {}
void Init(const std::string_view fontFile, char8_t symbol, const std::string_view outputFile);
void Init(const std::string_view fontFile, std::vector<char8_t> symbols, const std::string_view outputFile);
void setConfig(const TextConfig& cfg) { m_cfg = cfg; }
Text() = default;
~Text();
void SetUniformBuffer(UniformBuffer* buffer) { m_uniBuffer = buffer; }
void GenerateText(const std::string& text, const Math::Vector3f& pos = Math::Vector3f(0.f));
void SetConfig(const TextConfig& cfg) { m_cfg = cfg; }
TextConfig& GetConfig() { return m_cfg; }
void SetFontAtlasGenerator(FontAtlasGenerator* fontAtlasGenerator) { m_fontAtlasGenerator = fontAtlasGenerator; }
FontAtlasGenerator* GetFontAtlasGenerator() { return m_fontAtlasGenerator; }
private:
FontAtlasGenerator* m_fontAtlasGenerator = nullptr;
TextConfig m_cfg;
};
}