2
0

CBitmapFont.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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/Rect.h"
  18. #include "../../lib/filesystem/Filesystem.h"
  19. #include "../../lib/modding/CModHandler.h"
  20. #include "../../lib/texts/Languages.h"
  21. #include "../../lib/texts/TextOperations.h"
  22. #include "../../lib/vcmi_endian.h"
  23. #include "../../lib/VCMI_Lib.h"
  24. #include <SDL_surface.h>
  25. struct AtlasLayout
  26. {
  27. Point dimensions;
  28. std::map<int, Rect> images;
  29. };
  30. /// Attempts to pack provided list of images into 2d box of specified size
  31. /// Returns resulting layout on success and empty optional on failure
  32. static std::optional<AtlasLayout> tryAtlasPacking(Point dimensions, std::map<int, Point> images)
  33. {
  34. // Simple atlas packing algorithm. Can be extended if needed, however optimal solution is NP-complete problem, so 'perfect' solution is too costly
  35. AtlasLayout result;
  36. result.dimensions = dimensions;
  37. // a little interval to prevent potential 'bleeding' into adjacent symbols
  38. // should be unnecessary for base game, but may be needed for upscaled filters
  39. constexpr int interval = 1;
  40. int currentHeight = 0;
  41. int nextHeight = 0;
  42. int currentWidth = 0;
  43. for (auto const & image : images)
  44. {
  45. int nextWidth = currentWidth + image.second.x + interval;
  46. if (nextWidth > dimensions.x)
  47. {
  48. currentHeight = nextHeight;
  49. currentWidth = 0;
  50. nextWidth = currentWidth + image.second.x + interval;
  51. }
  52. nextHeight = std::max(nextHeight, currentHeight + image.second.y + interval);
  53. if (nextHeight > dimensions.y)
  54. return std::nullopt; // failure - ran out of space
  55. result.images[image.first] = Rect(Point(currentWidth, currentHeight), image.second);
  56. currentWidth = nextWidth;
  57. }
  58. return result;
  59. }
  60. /// Arranges images to fit into texture atlas with automatic selection of iamge size
  61. /// Returns images arranged into 2d box
  62. static AtlasLayout doAtlasPacking(std::map<int, Point> images)
  63. {
  64. // initial size of an atlas. Smaller size won't even fit tiniest H3 font
  65. Point dimensions(128, 128);
  66. for (;;)
  67. {
  68. auto result = tryAtlasPacking(dimensions, images);
  69. if (result)
  70. return *result;
  71. // else - packing failed. Increase atlas size and try again
  72. // increase width and height in alternating form: (64,64) -> (128,64) -> (128,128) ...
  73. if (dimensions.x > dimensions.y)
  74. dimensions.y *= 2;
  75. else
  76. dimensions.x *= 2;
  77. }
  78. }
  79. void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & resource, std::unordered_map<CodePoint, EntryFNT> & loadedChars)
  80. {
  81. if (!CResourceHandler::get(modName)->existsResource(resource))
  82. {
  83. logGlobal->error("Failed to load font %s from mod %s", resource.getName(), modName);
  84. return;
  85. }
  86. auto data = CResourceHandler::get(modName)->load(resource)->readAll();
  87. std::string modLanguage = CGI->modh->getModLanguage(modName);
  88. std::string modEncoding = Languages::getLanguageOptions(modLanguage).encoding;
  89. uint32_t dataHeight = data.first[5];
  90. maxHeight = std::max(maxHeight, dataHeight);
  91. constexpr size_t symbolsInFile = 0x100;
  92. constexpr size_t baseIndex = 32;
  93. constexpr size_t offsetIndex = baseIndex + symbolsInFile*12;
  94. constexpr size_t dataIndex = offsetIndex + symbolsInFile*4;
  95. for (uint32_t charIndex = 0; charIndex < symbolsInFile; ++charIndex)
  96. {
  97. CodePoint codepoint = TextOperations::getUnicodeCodepoint(static_cast<char>(charIndex), modEncoding);
  98. EntryFNT symbol;
  99. symbol.leftOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 0);
  100. symbol.width = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 4);
  101. symbol.rightOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 8);
  102. symbol.height = dataHeight;
  103. uint32_t pixelDataOffset = read_le_u32(data.first.get() + offsetIndex + charIndex * 4);
  104. uint32_t pixelsCount = dataHeight * symbol.width;
  105. symbol.pixels.resize(pixelsCount);
  106. uint8_t * pixelData = data.first.get() + dataIndex + pixelDataOffset;
  107. std::copy_n(pixelData, pixelsCount, symbol.pixels.data() );
  108. loadedChars[codepoint] = symbol;
  109. }
  110. }
  111. CBitmapFont::CBitmapFont(const std::string & filename):
  112. maxHeight(0)
  113. {
  114. ResourcePath resource("data/" + filename, EResType::BMP_FONT);
  115. std::unordered_map<CodePoint, EntryFNT> loadedChars;
  116. loadModFont("core", resource, loadedChars);
  117. for(const auto & modName : VLC->modh->getActiveMods())
  118. {
  119. if (CResourceHandler::get(modName)->existsResource(resource))
  120. loadModFont(modName, resource, loadedChars);
  121. }
  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. {
  142. // Copy pixel data to atlas
  143. uint8_t *dstPixels = (uint8_t*)atlasImage->pixels;
  144. uint8_t *dstLine = dstPixels + storedEntry.positionInAtlas.y * atlasImage->pitch;
  145. uint8_t *dst = dstLine + storedEntry.positionInAtlas.x;
  146. for (size_t i = 0; i < storedEntry.positionInAtlas.h; ++i)
  147. {
  148. const uint8_t *srcPtr = symbol.second.pixels.data() + i * storedEntry.positionInAtlas.w;
  149. uint8_t * dstPtr = dst + i * atlasImage->pitch;
  150. std::copy_n(srcPtr, storedEntry.positionInAtlas.w, dstPtr);
  151. }
  152. }
  153. chars[symbol.first] = storedEntry;
  154. }
  155. if (GH.screenHandler().getScalingFactor() != 1)
  156. {
  157. auto scaledSurface = CSDL_Ext::scaleSurfaceIntegerFactor(atlasImage, GH.screenHandler().getScalingFactor());
  158. SDL_FreeSurface(atlasImage);
  159. atlasImage = scaledSurface;
  160. }
  161. }
  162. CBitmapFont::~CBitmapFont()
  163. {
  164. SDL_FreeSurface(atlasImage);
  165. }
  166. size_t CBitmapFont::getLineHeight() const
  167. {
  168. return maxHeight;
  169. }
  170. size_t CBitmapFont::getGlyphWidth(const char * data) const
  171. {
  172. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  173. auto iter = chars.find(localChar);
  174. if (iter == chars.end())
  175. return 0;
  176. return iter->second.leftOffset + iter->second.positionInAtlas.w + iter->second.rightOffset;
  177. }
  178. bool CBitmapFont::canRepresentCharacter(const char *data) const
  179. {
  180. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  181. auto iter = chars.find(localChar);
  182. return iter != chars.end();
  183. }
  184. bool CBitmapFont::canRepresentString(const std::string & data) const
  185. {
  186. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  187. if (!canRepresentCharacter(data.data() + i))
  188. return false;
  189. return true;
  190. }
  191. void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const ColorRGBA & color, int &posX, int &posY) const
  192. {
  193. int scalingFactor = GH.screenHandler().getScalingFactor();
  194. posX += character.leftOffset * scalingFactor;
  195. auto sdlColor = CSDL_Ext::toSDL(color);
  196. if (atlasImage->format->palette)
  197. SDL_SetPaletteColors(atlasImage->format->palette, &sdlColor, 255, 1);
  198. // atlasImage->format->palette->colors[255] = CSDL_Ext::toSDL(color);
  199. else
  200. SDL_SetSurfaceColorMod(atlasImage, color.r, color.g, color.b);
  201. CSDL_Ext::blitSurface(atlasImage, character.positionInAtlas * scalingFactor, surface, Point(posX, posY));
  202. posX += character.positionInAtlas.w * scalingFactor;
  203. posX += character.rightOffset * scalingFactor;
  204. }
  205. void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const
  206. {
  207. if (data.empty())
  208. return;
  209. assert(surface);
  210. int posX = pos.x;
  211. int posY = pos.y;
  212. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  213. {
  214. CodePoint codepoint = TextOperations::getUnicodeCodepoint(data.data() + i, data.size() - i);
  215. auto iter = chars.find(codepoint);
  216. if (iter != chars.end())
  217. renderCharacter(surface, iter->second, color, posX, posY);
  218. }
  219. }