78 lines
2.2 KiB
C++
78 lines
2.2 KiB
C++
#pragma once
|
|
|
|
#include <extra2d/graphics/backends/opengl/gl_texture.h>
|
|
#include <extra2d/graphics/texture/font.h>
|
|
|
|
#include <stb/stb_truetype.h>
|
|
#include <stb/stb_rect_pack.h>
|
|
|
|
#include <unordered_map>
|
|
#include <vector>
|
|
|
|
namespace extra2d {
|
|
|
|
// ============================================================================
|
|
// OpenGL 字体图集实现 (使用 STB 库)
|
|
// ============================================================================
|
|
class GLFontAtlas : public FontAtlas {
|
|
public:
|
|
GLFontAtlas(const std::string& filepath, int fontSize, bool useSDF = false);
|
|
~GLFontAtlas() override;
|
|
|
|
// FontAtlas 接口实现
|
|
const Glyph* getGlyph(char32_t codepoint) const override;
|
|
Texture* getTexture() const override { return texture_.get(); }
|
|
int getFontSize() const override { return fontSize_; }
|
|
float getAscent() const override { return ascent_; }
|
|
float getDescent() const override { return descent_; }
|
|
float getLineGap() const override { return lineGap_; }
|
|
float getLineHeight() const override { return lineHeight_; }
|
|
bool isSDF() const override { return useSDF_; }
|
|
Vec2 measureText(const std::string& text) override;
|
|
|
|
private:
|
|
struct GlyphData {
|
|
float width;
|
|
float height;
|
|
float bearingX;
|
|
float bearingY;
|
|
float advance;
|
|
float u0, v0, u1, v1;
|
|
};
|
|
|
|
struct PackedCharData {
|
|
stbtt_packedchar packedChar;
|
|
bool valid;
|
|
};
|
|
|
|
bool useSDF_;
|
|
int fontSize_;
|
|
|
|
Ptr<GLTexture> texture_;
|
|
std::unordered_map<char32_t, GlyphData> glyphs_;
|
|
std::unordered_map<char32_t, PackedCharData> packedChars_;
|
|
float lineHeight_;
|
|
float ascent_;
|
|
float descent_;
|
|
float lineGap_;
|
|
|
|
// 字体数据
|
|
std::vector<unsigned char> fontData_;
|
|
stbtt_fontinfo fontInfo_;
|
|
float scale_;
|
|
|
|
// 图集打包参数
|
|
static constexpr int ATLAS_WIDTH = 512;
|
|
static constexpr int ATLAS_HEIGHT = 512;
|
|
|
|
// 初始化字体
|
|
bool initFont(const std::string& filepath);
|
|
// 渲染字形到图集
|
|
bool renderGlyph(char32_t codepoint);
|
|
// 更新图集纹理
|
|
void updateAtlas(int x, int y, int width, int height,
|
|
const std::vector<uint8_t>& data);
|
|
};
|
|
|
|
} // namespace extra2d
|