CBitmapFont.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * CBitmapFont.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CBitmapFont.h"
  12. #include "SDL_Extensions.h"
  13. #include "../CGameInfo.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../render/Colors.h"
  16. #include "../render/IScreenHandler.h"
  17. #include "../../lib/CConfigHandler.h"
  18. #include "../../lib/Rect.h"
  19. #include "../../lib/VCMI_Lib.h"
  20. #include "../../lib/filesystem/Filesystem.h"
  21. #include "../../lib/modding/CModHandler.h"
  22. #include "../../lib/texts/Languages.h"
  23. #include "../../lib/texts/TextOperations.h"
  24. #include "../../lib/vcmi_endian.h"
  25. #include <SDL_surface.h>
  26. #include <SDL_image.h>
  27. struct AtlasLayout
  28. {
  29. Point dimensions;
  30. std::map<int, Rect> images;
  31. };
  32. /// Attempts to pack provided list of images into 2d box of specified size
  33. /// Returns resulting layout on success and empty optional on failure
  34. static std::optional<AtlasLayout> tryAtlasPacking(Point dimensions, const std::map<int, Point> & images)
  35. {
  36. // Simple atlas packing algorithm. Can be extended if needed, however optimal solution is NP-complete problem, so 'perfect' solution is too costly
  37. AtlasLayout result;
  38. result.dimensions = dimensions;
  39. // a little interval to prevent potential 'bleeding' into adjacent symbols
  40. // should be unnecessary for base game, but may be needed for upscaled filters
  41. constexpr int interval = 1;
  42. int currentHeight = 0;
  43. int nextHeight = 0;
  44. int currentWidth = 0;
  45. for (auto const & image : images)
  46. {
  47. int nextWidth = currentWidth + image.second.x + interval;
  48. if (nextWidth > dimensions.x)
  49. {
  50. currentHeight = nextHeight;
  51. currentWidth = 0;
  52. nextWidth = currentWidth + image.second.x + interval;
  53. }
  54. nextHeight = std::max(nextHeight, currentHeight + image.second.y + interval);
  55. if (nextHeight > dimensions.y)
  56. return std::nullopt; // failure - ran out of space
  57. result.images[image.first] = Rect(Point(currentWidth, currentHeight), image.second);
  58. currentWidth = nextWidth;
  59. }
  60. return result;
  61. }
  62. /// Arranges images to fit into texture atlas with automatic selection of image size
  63. /// Returns images arranged into 2d box
  64. static AtlasLayout doAtlasPacking(const std::map<int, Point> & images)
  65. {
  66. // initial size of an atlas. Smaller size won't even fit tiniest H3 font
  67. Point dimensions(128, 128);
  68. for (;;)
  69. {
  70. auto result = tryAtlasPacking(dimensions, images);
  71. if (result)
  72. return *result;
  73. // else - packing failed. Increase atlas size and try again
  74. // increase width and height in alternating form: (64,64) -> (128,64) -> (128,128) ...
  75. if (dimensions.x > dimensions.y)
  76. dimensions.y *= 2;
  77. else
  78. dimensions.x *= 2;
  79. }
  80. }
  81. void CBitmapFont::loadFont(const ResourcePath & resource, std::unordered_map<CodePoint, EntryFNT> & loadedChars)
  82. {
  83. auto data = CResourceHandler::get()->load(resource)->readAll();
  84. std::string modEncoding = VLC->modh->findResourceEncoding(resource);
  85. height = data.first[5];
  86. constexpr size_t symbolsInFile = 0x100;
  87. constexpr size_t baseIndex = 32;
  88. constexpr size_t offsetIndex = baseIndex + symbolsInFile*12;
  89. constexpr size_t dataIndex = offsetIndex + symbolsInFile*4;
  90. for (uint32_t charIndex = 0; charIndex < symbolsInFile; ++charIndex)
  91. {
  92. CodePoint codepoint = TextOperations::getUnicodeCodepoint(static_cast<char>(charIndex), modEncoding);
  93. EntryFNT symbol;
  94. symbol.leftOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 0);
  95. symbol.width = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 4);
  96. symbol.rightOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 8);
  97. symbol.height = height;
  98. uint32_t pixelDataOffset = read_le_u32(data.first.get() + offsetIndex + charIndex * 4);
  99. uint32_t pixelsCount = height * symbol.width;
  100. symbol.pixels.resize(pixelsCount);
  101. uint8_t * pixelData = data.first.get() + dataIndex + pixelDataOffset;
  102. std::copy_n(pixelData, pixelsCount, symbol.pixels.data() );
  103. loadedChars[codepoint] = symbol;
  104. }
  105. // Try to use symbol 'L' to detect font 'ascent' - number of pixels above text baseline
  106. const auto & symbolL = loadedChars['L'];
  107. uint32_t lastNonEmptyRow = 0;
  108. for (uint32_t row = 0; row < symbolL.height; ++row)
  109. {
  110. for (uint32_t col = 0; col < symbolL.width; ++col)
  111. if (symbolL.pixels.at(row * symbolL.width + col) == 255)
  112. lastNonEmptyRow = std::max(lastNonEmptyRow, row);
  113. }
  114. ascent = lastNonEmptyRow + 1;
  115. }
  116. CBitmapFont::CBitmapFont(const std::string & filename):
  117. height(0)
  118. {
  119. ResourcePath resource("data/" + filename, EResType::BMP_FONT);
  120. std::unordered_map<CodePoint, EntryFNT> loadedChars;
  121. loadFont(resource, loadedChars);
  122. std::map<int, Point> atlasSymbol;
  123. for (auto const & symbol : loadedChars)
  124. atlasSymbol[symbol.first] = Point(symbol.second.width, symbol.second.height);
  125. auto atlas = doAtlasPacking(atlasSymbol);
  126. atlasImage = SDL_CreateRGBSurface(0, atlas.dimensions.x, atlas.dimensions.y, 8, 0, 0, 0, 0);
  127. assert(atlasImage->format->palette != nullptr);
  128. assert(atlasImage->format->palette->ncolors == 256);
  129. atlasImage->format->palette->colors[0] = { 0, 255, 255, SDL_ALPHA_OPAQUE }; // transparency
  130. atlasImage->format->palette->colors[1] = { 0, 0, 0, SDL_ALPHA_OPAQUE }; // black shadow
  131. CSDL_Ext::fillSurface(atlasImage, CSDL_Ext::toSDL(Colors::CYAN));
  132. CSDL_Ext::setColorKey(atlasImage, CSDL_Ext::toSDL(Colors::CYAN));
  133. for (size_t i = 2; i < atlasImage->format->palette->ncolors; ++i)
  134. atlasImage->format->palette->colors[i] = { 255, 255, 255, SDL_ALPHA_OPAQUE };
  135. for (auto const & symbol : loadedChars)
  136. {
  137. BitmapChar storedEntry;
  138. storedEntry.leftOffset = symbol.second.leftOffset;
  139. storedEntry.rightOffset = symbol.second.rightOffset;
  140. storedEntry.positionInAtlas = atlas.images.at(symbol.first);
  141. // Copy pixel data to atlas
  142. uint8_t *dstPixels = static_cast<uint8_t*>(atlasImage->pixels);
  143. uint8_t *dstLine = dstPixels + storedEntry.positionInAtlas.y * atlasImage->pitch;
  144. uint8_t *dst = dstLine + storedEntry.positionInAtlas.x;
  145. for (size_t i = 0; i < storedEntry.positionInAtlas.h; ++i)
  146. {
  147. const uint8_t *srcPtr = symbol.second.pixels.data() + i * storedEntry.positionInAtlas.w;
  148. uint8_t * dstPtr = dst + i * atlasImage->pitch;
  149. std::copy_n(srcPtr, storedEntry.positionInAtlas.w, dstPtr);
  150. }
  151. chars[symbol.first] = storedEntry;
  152. }
  153. if (GH.screenHandler().getScalingFactor() != 1)
  154. {
  155. static const std::map<std::string, EScalingAlgorithm> filterNameToEnum = {
  156. { "nearest", EScalingAlgorithm::NEAREST},
  157. { "bilinear", EScalingAlgorithm::BILINEAR},
  158. { "xbrz", EScalingAlgorithm::XBRZ_ALPHA}
  159. };
  160. auto filterName = settings["video"]["fontUpscalingFilter"].String();
  161. EScalingAlgorithm algorithm = filterNameToEnum.at(filterName);
  162. auto scaledSurface = CSDL_Ext::scaleSurfaceIntegerFactor(atlasImage, GH.screenHandler().getScalingFactor(), algorithm);
  163. SDL_FreeSurface(atlasImage);
  164. atlasImage = scaledSurface;
  165. }
  166. logGlobal->debug("Loaded BMP font: '%s', height %d, ascent %d",
  167. filename,
  168. getLineHeightScaled(),
  169. getFontAscentScaled()
  170. );
  171. }
  172. CBitmapFont::~CBitmapFont()
  173. {
  174. SDL_FreeSurface(atlasImage);
  175. }
  176. size_t CBitmapFont::getLineHeightScaled() const
  177. {
  178. return height * getScalingFactor();
  179. }
  180. size_t CBitmapFont::getGlyphWidthScaled(const char * data) const
  181. {
  182. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  183. auto iter = chars.find(localChar);
  184. if (iter == chars.end())
  185. return 0;
  186. return (iter->second.leftOffset + iter->second.positionInAtlas.w + iter->second.rightOffset) * getScalingFactor();
  187. }
  188. size_t CBitmapFont::getFontAscentScaled() const
  189. {
  190. return ascent * getScalingFactor();
  191. }
  192. bool CBitmapFont::canRepresentCharacter(const char *data) const
  193. {
  194. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  195. auto iter = chars.find(localChar);
  196. return iter != chars.end();
  197. }
  198. bool CBitmapFont::canRepresentString(const std::string & data) const
  199. {
  200. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  201. if (!canRepresentCharacter(data.data() + i))
  202. return false;
  203. return true;
  204. }
  205. void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const ColorRGBA & color, int &posX, int &posY) const
  206. {
  207. int scalingFactor = GH.screenHandler().getScalingFactor();
  208. posX += character.leftOffset * scalingFactor;
  209. auto sdlColor = CSDL_Ext::toSDL(color);
  210. if (atlasImage->format->palette)
  211. SDL_SetPaletteColors(atlasImage->format->palette, &sdlColor, 255, 1);
  212. else
  213. SDL_SetSurfaceColorMod(atlasImage, color.r, color.g, color.b);
  214. CSDL_Ext::blitSurface(atlasImage, character.positionInAtlas * scalingFactor, surface, Point(posX, posY));
  215. posX += character.positionInAtlas.w * scalingFactor;
  216. posX += character.rightOffset * scalingFactor;
  217. }
  218. void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const
  219. {
  220. if (data.empty())
  221. return;
  222. assert(surface);
  223. int posX = pos.x;
  224. int posY = pos.y;
  225. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  226. {
  227. CodePoint codepoint = TextOperations::getUnicodeCodepoint(data.data() + i, data.size() - i);
  228. auto iter = chars.find(codepoint);
  229. if (iter != chars.end())
  230. renderCharacter(surface, iter->second, color, posX, posY);
  231. }
  232. }