engine/src/resources/font.cpp

68 lines
1.8 KiB
C++
Raw Normal View History

2022-09-02 11:06:59 +00:00
#include "resources/font.hpp"
2022-11-23 16:20:08 +00:00
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
#include "util/files.hpp"
#include "gfx_device.hpp"
2022-09-02 11:06:59 +00:00
2022-11-23 18:09:49 +00:00
#include "log.hpp"
2022-10-06 10:30:44 +00:00
namespace engine::resources {
2022-09-02 11:06:59 +00:00
Font::Font(const std::filesystem::path& resPath) : Resource(resPath, "font")
{
2022-11-23 16:20:08 +00:00
// TODO: load font
2022-11-27 14:35:41 +00:00
auto fontBuffer = util::readBinaryFile(resPath.string());
2022-09-02 11:06:59 +00:00
2022-11-28 09:39:00 +00:00
constexpr int FIRST_CHAR = 32;
constexpr int NUM_CHARS = 96;
2022-11-27 14:35:41 +00:00
constexpr int BITMAP_WIDTH = 1024;
constexpr int BITMAP_HEIGHT = 1024;
auto pixels = std::make_unique<unsigned char[]>(BITMAP_WIDTH * BITMAP_HEIGHT);
2022-11-28 09:39:00 +00:00
auto bakedChars = std::make_unique<stbtt_bakedchar[]>(NUM_CHARS);
2022-09-02 11:06:59 +00:00
2022-11-28 09:39:00 +00:00
stbtt_BakeFontBitmap(fontBuffer->data(), 0, 128.0f, pixels.get(), BITMAP_WIDTH, BITMAP_HEIGHT, FIRST_CHAR, NUM_CHARS, bakedChars.get());
2022-09-02 11:06:59 +00:00
2022-11-27 14:35:41 +00:00
auto textureData = std::make_unique<uint8_t[]>(BITMAP_WIDTH * BITMAP_HEIGHT * 4);
2022-09-02 11:06:59 +00:00
2022-11-27 14:35:41 +00:00
for (int i = 0; i < BITMAP_WIDTH * BITMAP_HEIGHT; i++) {
textureData[i * 4 + 0] = pixels[i];
textureData[i * 4 + 1] = pixels[i];
textureData[i * 4 + 2] = pixels[i];
textureData[i * 4 + 3] = pixels[i];
2022-09-02 11:06:59 +00:00
}
2022-11-27 14:35:41 +00:00
m_atlas = gfxdev->createTexture(textureData.get(), BITMAP_WIDTH, BITMAP_HEIGHT, gfx::TextureFilter::LINEAR, gfx::TextureFilter::LINEAR);
2022-09-02 11:06:59 +00:00
2022-11-28 09:39:00 +00:00
for (int i = FIRST_CHAR; i < NUM_CHARS; i++) {
CharData charData{};
charData.atlas_top_left = { bakedChars[i].x0, bakedChars[i].y0 };
charData.atlas_bottom_right = { bakedChars[i].x1, bakedChars[i].y1 };
charData.offset = { bakedChars[i].xoff, bakedChars[i].yoff };
charData.xAdvance = bakedChars[i].xadvance;
m_charData[i] = charData;
// TODO
}
2022-09-02 11:06:59 +00:00
}
Font::~Font()
{
2022-11-27 14:35:41 +00:00
gfxdev->destroyTexture(m_atlas);
2022-09-02 11:06:59 +00:00
}
2022-11-27 14:35:41 +00:00
const gfx::Texture* Font::getAtlasTexture()
2022-09-02 11:06:59 +00:00
{
2022-11-27 14:35:41 +00:00
return m_atlas;
2022-09-02 11:06:59 +00:00
}
2022-11-28 09:39:00 +00:00
Font::CharData Font::getCharData(uint32_t charCode)
{
return m_charData[charCode];
}
2022-09-02 11:06:59 +00:00
}