CBitmapFont.cpp 9.2 KB

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