axmol/core/2d/FontAtlas.cpp

522 lines
16 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2021-2022 Bytedance Inc.
2021-11-11 17:20:21 +08:00
2022-10-01 16:24:52 +08:00
https://axmolengine.github.io/
2019-11-23 20:27:39 +08:00
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/FontAtlas.h"
2022-07-16 10:43:05 +08:00
#if AX_TARGET_PLATFORM != AX_PLATFORM_WIN32 && AX_TARGET_PLATFORM != AX_PLATFORM_ANDROID
#elif AX_TARGET_PLATFORM == AX_PLATFORM_ANDROID
2022-10-01 16:24:52 +08:00
# include "platform/android/jni/Java_org_axmol_lib_AxmolEngine.h"
2019-11-23 20:27:39 +08:00
#endif
#include <algorithm>
#include "2d/FontFreeType.h"
#include "base/UTF8.h"
#include "base/Director.h"
#include "base/EventListenerCustom.h"
#include "base/EventDispatcher.h"
#include "base/EventType.h"
2019-11-23 20:27:39 +08:00
#include "simdjson/simdjson.h"
#include "zlib.h"
#include "fmt/format.h"
#include "base/ZipUtils.h"
#include "base/PaddedString.h"
NS_AX_BEGIN
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
const int FontAtlas::CacheTextureWidth = 512;
const int FontAtlas::CacheTextureHeight = 512;
2019-11-23 20:27:39 +08:00
const char* FontAtlas::CMD_PURGE_FONTATLAS = "__cc_PURGE_FONTATLAS";
const char* FontAtlas::CMD_RESET_FONTATLAS = "__cc_RESET_FONTATLAS";
void FontAtlas::loadFontAtlas(std::string_view fontatlasFile, hlookup::string_map<FontAtlas*>& outAtlasMap)
{
using namespace simdjson;
try
{
auto strJson = PaddedString::load(fontatlasFile);
ondemand::parser parser;
ondemand::document settings = parser.iterate(strJson);
std::string_view type = settings["type"];
if (type != "fontatlas")
{
ax::print("Load fontatlas %s fail, invalid asset type: ", fontatlasFile.data(), type.data());
return;
}
// std::string_view version = settings["version"];
std::string_view atlasName = settings["atlasName"];
auto it = outAtlasMap.find(atlasName);
if (it != outAtlasMap.end())
{
if (it->second->getReferenceCount() != 1)
{
ax::print("Load fontatlas %s fail, due to exist fontatlas with same key %s and in used",
fontatlasFile.data(), atlasName.data());
return;
}
else
it->second->release();
outAtlasMap.erase(it);
}
std::string_view sourceFont = settings["sourceFont"];
int faceSize = static_cast<int>(static_cast<int64_t>(settings["faceSize"]));
auto font = FontFreeType::create(sourceFont, faceSize, GlyphCollection::DYNAMIC, ""sv, true, 0.0f);
if (!font)
{
ax::print("Load fontatils %s fail due to create source font %s fail", fontatlasFile.data(),
sourceFont.data());
return;
}
int atlasDim[2];
auto atliasDim = settings["atlasDim"].get_array();
int index = 0;
for (auto value : atliasDim)
{
atlasDim[index++] = static_cast<int>(value.get_int64());
if (index >= 2)
break;
}
auto fontAtlas = new FontAtlas(font, atlasDim[0], atlasDim[1], AX_CONTENT_SCALE_FACTOR());
try
{
fontAtlas->initWithSettings(&settings);
outAtlasMap.emplace(atlasName, fontAtlas);
}
catch (std::exception& ex)
{
fontAtlas->release();
throw ex; // rethrow
}
}
catch (std::exception& ex)
{
ax::print("Load fontatils %s fail due to exception occured: %s", fontatlasFile.data(), ex.what());
}
}
FontAtlas::FontAtlas(Font* theFont)
: FontAtlas(theFont, CacheTextureWidth, CacheTextureHeight, AX_CONTENT_SCALE_FACTOR())
{}
FontAtlas::FontAtlas(Font* theFont, int atlasWidth, int atlasHeight, float scaleFactor)
: _font(theFont), _width(atlasWidth), _height(atlasHeight), _scaleFactor(scaleFactor)
2019-11-23 20:27:39 +08:00
{
_font->retain();
_fontFreeType = dynamic_cast<FontFreeType*>(_font);
if (_fontFreeType)
{
2021-12-25 10:04:45 +08:00
_lineHeight = (float)_font->getFontMaxHeight();
_fontAscender = _fontFreeType->getFontAscender();
2019-11-23 20:27:39 +08:00
_letterEdgeExtend = 2;
auto outlineSize = _fontFreeType->getOutlineSize();
if (outlineSize > 0)
{
_strideShift = 1;
_pixelFormat = AX_GLES_PROFILE != 200 ? backend::PixelFormat::RG8 : backend::PixelFormat::LA8;
_currentPageDataSize = _width * _height << _strideShift;
2019-11-23 20:27:39 +08:00
_lineHeight += 2 * outlineSize;
}
else
{
_strideShift = 0;
_pixelFormat = AX_GLES_PROFILE != 200 ? backend::PixelFormat::R8 : backend::PixelFormat::A8;
_currentPageDataSize = _width * _height;
}
if (_fontFreeType->isDistanceFieldEnabled())
{
_letterPadding += 2 * FontFreeType::DistanceMapSpread;
}
2019-11-23 20:27:39 +08:00
2022-07-16 10:43:05 +08:00
#if AX_ENABLE_CACHE_TEXTURE_DATA
2019-11-23 20:27:39 +08:00
auto eventDispatcher = Director::getInstance()->getEventDispatcher();
2021-12-25 10:04:45 +08:00
_rendererRecreatedListener = EventListenerCustom::create(
2022-07-16 10:43:05 +08:00
EVENT_RENDERER_RECREATED, AX_CALLBACK_1(FontAtlas::listenRendererRecreated, this));
2019-11-23 20:27:39 +08:00
eventDispatcher->addEventListenerWithFixedPriority(_rendererRecreatedListener, 1);
#endif
}
}
void FontAtlas::reinit()
{
if (!_currentPageData)
_currentPageData = new uint8_t[_currentPageDataSize];
_currentPage = -1;
2021-12-25 10:04:45 +08:00
addNewPage();
2019-11-23 20:27:39 +08:00
}
2019-11-23 20:27:39 +08:00
FontAtlas::~FontAtlas()
{
2022-07-16 10:43:05 +08:00
#if AX_ENABLE_CACHE_TEXTURE_DATA
2019-11-23 20:27:39 +08:00
if (_fontFreeType && _rendererRecreatedListener)
{
auto eventDispatcher = Director::getInstance()->getEventDispatcher();
eventDispatcher->removeEventListener(_rendererRecreatedListener);
_rendererRecreatedListener = nullptr;
}
#endif
_font->release();
releaseTextures();
2022-07-16 10:43:05 +08:00
AX_SAFE_DELETE_ARRAY(_currentPageData);
2019-11-23 20:27:39 +08:00
}
void FontAtlas::initWithSettings(void* opaque /*simdjson::ondemand::document*/)
{
if (!_currentPageData)
_currentPageData = new uint8_t[_currentPageDataSize];
_currentPage = -1;
simdjson::ondemand::document& settings = *(simdjson::ondemand::document*)opaque;
// pages
for (auto page : settings["pages"].get_array())
{
auto comprData = utils::base64Decode(page);
auto uncomprData = ZipUtils::decompressGZ(std::span{comprData}, _currentPageDataSize);
addNewPageWithData(uncomprData.data(), uncomprData.size());
}
_currentPageOrigX = static_cast<float>(settings["pageX"].get_double());
_currentPageOrigY = static_cast<float>(settings["pageY"].get_double());
// letters
FontLetterDefinition tempDef;
tempDef.rotated = false;
tempDef.validDefinition = true;
std::string strCharCode;
for (auto field : settings["letters"].get_object())
{
strCharCode = static_cast<std::string_view>(field.unescaped_key());
auto letterInfo = field.value();
tempDef.U = static_cast<float>(letterInfo["U"].get_double());
tempDef.V = static_cast<float>(letterInfo["V"].get_double());
tempDef.xAdvance = static_cast<float>(letterInfo["advance"].get_double());
tempDef.width = static_cast<float>(letterInfo["width"].get_double());
tempDef.height = static_cast<float>(letterInfo["height"].get_double());
tempDef.offsetX = static_cast<float>(letterInfo["offsetX"].get_double());
tempDef.offsetY = static_cast<float>(letterInfo["offsetY"].get_double());
tempDef.textureID = letterInfo["page"].get_int64();
auto charCode = atoi(strCharCode.c_str());
tempDef.U /= _scaleFactor;
tempDef.V /= _scaleFactor;
tempDef.width /= _scaleFactor;
tempDef.height /= _scaleFactor;
_letterDefinitions.emplace(charCode, tempDef);
}
}
2019-11-23 20:27:39 +08:00
void FontAtlas::reset()
{
releaseTextures();
2021-12-25 10:04:45 +08:00
_currLineHeight = 0;
2019-11-23 20:27:39 +08:00
_currentPageOrigX = 0;
_currentPageOrigY = 0;
_letterDefinitions.clear();
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
reinit();
}
void FontAtlas::releaseTextures()
{
for (auto&& item : _atlasTextures)
2019-11-23 20:27:39 +08:00
{
item.second->release();
}
_atlasTextures.clear();
}
void FontAtlas::purgeTexturesAtlas()
{
if (_fontFreeType)
{
reset();
auto eventDispatcher = Director::getInstance()->getEventDispatcher();
2021-12-25 10:04:45 +08:00
eventDispatcher->dispatchCustomEvent(CMD_PURGE_FONTATLAS, this);
eventDispatcher->dispatchCustomEvent(CMD_RESET_FONTATLAS, this);
2019-11-23 20:27:39 +08:00
}
}
2021-12-25 10:04:45 +08:00
void FontAtlas::listenRendererRecreated(EventCustom* /*event*/)
2019-11-23 20:27:39 +08:00
{
purgeTexturesAtlas();
}
2021-12-25 10:04:45 +08:00
void FontAtlas::addLetterDefinition(char32_t utf32Char, const FontLetterDefinition& letterDefinition)
2019-11-23 20:27:39 +08:00
{
_letterDefinitions[utf32Char] = letterDefinition;
}
void FontAtlas::scaleFontLetterDefinition(float scaleFactor)
{
2021-12-25 10:04:45 +08:00
for (auto&& fontDefinition : _letterDefinitions)
{
2019-11-23 20:27:39 +08:00
auto& letterDefinition = fontDefinition.second;
letterDefinition.width *= scaleFactor;
letterDefinition.height *= scaleFactor;
letterDefinition.offsetX *= scaleFactor;
letterDefinition.offsetY *= scaleFactor;
letterDefinition.xAdvance = (int)(letterDefinition.xAdvance * scaleFactor);
}
}
2021-12-25 10:04:45 +08:00
bool FontAtlas::getLetterDefinitionForChar(char32_t utf32Char, FontLetterDefinition& letterDefinition)
2019-11-23 20:27:39 +08:00
{
auto outIterator = _letterDefinitions.find(utf32Char);
if (outIterator != _letterDefinitions.end())
{
letterDefinition = (*outIterator).second;
return letterDefinition.validDefinition;
}
else
{
return false;
}
}
void FontAtlas::findNewCharacters(const std::u32string& u32Text, std::unordered_set<char32_t>& charset)
2019-11-23 20:27:39 +08:00
{
if (_letterDefinitions.empty())
{
std::copy(u32Text.begin(), u32Text.end(), std::inserter(charset, charset.end()));
2019-11-23 20:27:39 +08:00
}
else
{
for (auto&& charCode : u32Text)
if (_letterDefinitions.find(charCode) == _letterDefinitions.end())
charset.insert(charCode);
2019-11-23 20:27:39 +08:00
}
}
bool FontAtlas::prepareLetterDefinitions(const std::u32string& utf32Text)
{
if (_fontFreeType == nullptr)
{
return false;
}
if (!_currentPageData)
2021-12-25 10:04:45 +08:00
reinit();
std::unordered_set<char32_t> charCodeSet;
findNewCharacters(utf32Text, charCodeSet);
if (charCodeSet.empty())
2019-11-23 20:27:39 +08:00
{
return false;
}
int adjustForDistanceMap = _letterPadding / 2;
2021-12-25 10:04:45 +08:00
int adjustForExtend = _letterEdgeExtend / 2;
int bitmapWidth = 0;
int bitmapHeight = 0;
2019-11-23 20:27:39 +08:00
int glyphHeight;
Rect tempRect;
FontLetterDefinition tempDef;
auto pixelFormat = _pixelFormat;
2019-11-23 20:27:39 +08:00
int startY = (int)_currentPageOrigY;
for (auto&& charCode : charCodeSet)
2019-11-23 20:27:39 +08:00
{
auto bitmap = _fontFreeType->getGlyphBitmap(charCode, bitmapWidth, bitmapHeight, tempRect, tempDef.xAdvance);
2019-11-23 20:27:39 +08:00
if (bitmap && bitmapWidth > 0 && bitmapHeight > 0)
{
tempDef.validDefinition = true;
2021-12-25 10:04:45 +08:00
tempDef.width = tempRect.size.width + _letterPadding + _letterEdgeExtend;
tempDef.height = tempRect.size.height + _letterPadding + _letterEdgeExtend;
tempDef.offsetX = tempRect.origin.x - adjustForDistanceMap - adjustForExtend;
tempDef.offsetY = _fontAscender + tempRect.origin.y - adjustForDistanceMap - adjustForExtend;
2019-11-23 20:27:39 +08:00
if (_currentPageOrigX + tempDef.width > _width)
2019-11-23 20:27:39 +08:00
{
_currentPageOrigY += _currLineHeight;
2021-12-25 10:04:45 +08:00
_currLineHeight = 0;
2019-11-23 20:27:39 +08:00
_currentPageOrigX = 0;
if (_currentPageOrigY + _lineHeight + _letterPadding + _letterEdgeExtend >= _height)
2019-11-23 20:27:39 +08:00
{
updateTextureContent(pixelFormat, startY);
startY = 0;
addNewPage();
2019-11-23 20:27:39 +08:00
}
}
glyphHeight = static_cast<int>(bitmapHeight) + _letterPadding + _letterEdgeExtend;
if (glyphHeight > _currLineHeight)
{
_currLineHeight = glyphHeight;
}
2021-12-25 10:04:45 +08:00
_fontFreeType->renderCharAt(_currentPageData, (int)_currentPageOrigX + adjustForExtend,
(int)_currentPageOrigY + adjustForExtend, bitmap, bitmapWidth, bitmapHeight,
_width, _height);
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
tempDef.U = _currentPageOrigX;
tempDef.V = _currentPageOrigY;
2019-11-23 20:27:39 +08:00
tempDef.textureID = _currentPage;
_currentPageOrigX += tempDef.width + 1;
// take from pixels to points
tempDef.width = tempDef.width / _scaleFactor;
tempDef.height = tempDef.height / _scaleFactor;
tempDef.U = tempDef.U / _scaleFactor;
tempDef.V = tempDef.V / _scaleFactor;
tempDef.rotated = false;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
else
{
2021-12-25 10:04:45 +08:00
if (bitmap)
2019-11-23 20:27:39 +08:00
delete[] bitmap;
tempDef.validDefinition = !!tempDef.xAdvance;
tempDef.width = 0;
tempDef.height = 0;
tempDef.U = 0;
tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
tempDef.rotated = false;
2019-11-23 20:27:39 +08:00
_currentPageOrigX += 1;
}
_letterDefinitions[charCode] = tempDef;
2019-11-23 20:27:39 +08:00
}
updateTextureContent(pixelFormat, startY);
2019-11-23 20:27:39 +08:00
return true;
}
void FontAtlas::updateTextureContent(backend::PixelFormat format, int startY)
{
auto data = _currentPageData + (_width * (int)startY << _strideShift);
_atlasTextures[_currentPage]->updateWithSubData(data, 0, startY, _width,
(int)_currentPageOrigY - startY + _currLineHeight);
}
void FontAtlas::addNewPage()
{
memset(_currentPageData, 0, _currentPageDataSize);
addNewPageWithData(_currentPageData, _currentPageDataSize);
_currentPageOrigY = 0;
}
void FontAtlas::addNewPageWithData(const uint8_t* data, size_t size)
{
assert(_currentPageDataSize == size);
auto texture = new Texture2D();
texture->initWithData(data, _currentPageDataSize, _pixelFormat, _width, _height);
if (_antialiasEnabled)
texture->setAntiAliasTexParameters();
else
texture->setAliasTexParameters();
setTexture(++_currentPage, texture);
texture->release();
2019-11-23 20:27:39 +08:00
}
void FontAtlas::setTexture(unsigned int slot, Texture2D* texture)
2019-11-23 20:27:39 +08:00
{
texture->retain();
_atlasTextures[slot] = texture;
}
Texture2D* FontAtlas::getTexture(int slot)
{
return _atlasTextures[slot];
}
void FontAtlas::setLineHeight(float newHeight)
{
_lineHeight = newHeight;
}
std::string_view FontAtlas::getFontName() const
2019-11-23 20:27:39 +08:00
{
std::string_view fontName = _fontFreeType ? _fontFreeType->getFontName() : ""sv;
2021-12-25 10:04:45 +08:00
if (fontName.empty())
return fontName;
2019-11-23 20:27:39 +08:00
auto idx = fontName.rfind('/');
2021-12-25 10:04:45 +08:00
if (idx != std::string::npos)
{
return fontName.substr(idx + 1);
}
2019-11-23 20:27:39 +08:00
idx = fontName.rfind('\\');
2021-12-25 10:04:45 +08:00
if (idx != std::string::npos)
{
return fontName.substr(idx + 1);
}
2019-11-23 20:27:39 +08:00
return fontName;
}
void FontAtlas::setAliasTexParameters()
{
if (_antialiasEnabled)
{
_antialiasEnabled = false;
2021-12-25 10:04:45 +08:00
for (const auto& tex : _atlasTextures)
2019-11-23 20:27:39 +08:00
{
tex.second->setAliasTexParameters();
}
}
}
void FontAtlas::setAntiAliasTexParameters()
{
2021-12-25 10:04:45 +08:00
if (!_antialiasEnabled)
2019-11-23 20:27:39 +08:00
{
_antialiasEnabled = true;
2021-12-25 10:04:45 +08:00
for (const auto& tex : _atlasTextures)
2019-11-23 20:27:39 +08:00
{
tex.second->setAntiAliasTexParameters();
}
}
}
NS_AX_END