CBitmapFont.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*
  2. * Fonts.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 "Fonts.h"
  12. #include <SDL_ttf.h>
  13. #include "SDL_Extensions.h"
  14. #include "../../lib/JsonNode.h"
  15. #include "../../lib/vcmi_endian.h"
  16. #include "../../lib/filesystem/Filesystem.h"
  17. #include "../../lib/CGeneralTextHandler.h"
  18. size_t IFont::getStringWidth(const std::string & data) const
  19. {
  20. size_t width = 0;
  21. for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
  22. {
  23. width += getGlyphWidth(data.data() + i);
  24. }
  25. return width;
  26. }
  27. void IFont::renderTextLeft(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  28. {
  29. renderText(surface, data, color, pos);
  30. }
  31. void IFont::renderTextRight(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  32. {
  33. Point size((int)getStringWidth(data), (int)getLineHeight());
  34. renderText(surface, data, color, pos - size);
  35. }
  36. void IFont::renderTextCenter(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  37. {
  38. Point size((int)getStringWidth(data), (int)getLineHeight());
  39. renderText(surface, data, color, pos - size / 2);
  40. }
  41. void IFont::renderTextLinesLeft(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
  42. {
  43. Point currPos = pos;
  44. for(const std::string & line : data)
  45. {
  46. renderTextLeft(surface, line, color, currPos);
  47. currPos.y += (int)getLineHeight();
  48. }
  49. }
  50. void IFont::renderTextLinesRight(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
  51. {
  52. Point currPos = pos;
  53. currPos.y -= (int)data.size() * (int)getLineHeight();
  54. for(const std::string & line : data)
  55. {
  56. renderTextRight(surface, line, color, currPos);
  57. currPos.y += (int)getLineHeight();
  58. }
  59. }
  60. void IFont::renderTextLinesCenter(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
  61. {
  62. Point currPos = pos;
  63. currPos.y -= (int)data.size() * (int)getLineHeight() / 2;
  64. for(const std::string & line : data)
  65. {
  66. renderTextCenter(surface, line, color, currPos);
  67. currPos.y += (int)getLineHeight();
  68. }
  69. }
  70. std::array<CBitmapFont::BitmapChar, CBitmapFont::totalChars> CBitmapFont::loadChars() const
  71. {
  72. std::array<BitmapChar, totalChars> ret;
  73. size_t offset = 32;
  74. for (auto & elem : ret)
  75. {
  76. elem.leftOffset = read_le_u32(data.first.get() + offset); offset+=4;
  77. elem.width = read_le_u32(data.first.get() + offset); offset+=4;
  78. elem.rightOffset = read_le_u32(data.first.get() + offset); offset+=4;
  79. }
  80. for (auto & elem : ret)
  81. {
  82. int pixelOffset = read_le_u32(data.first.get() + offset); offset+=4;
  83. elem.pixels = data.first.get() + 4128 + pixelOffset;
  84. assert(pixelOffset + 4128 < data.second);
  85. }
  86. return ret;
  87. }
  88. CBitmapFont::CBitmapFont(const std::string & filename):
  89. data(CResourceHandler::get()->load(ResourceID("data/" + filename, EResType::BMP_FONT))->readAll()),
  90. chars(loadChars()),
  91. height(data.first.get()[5])
  92. {}
  93. size_t CBitmapFont::getLineHeight() const
  94. {
  95. return height;
  96. }
  97. size_t CBitmapFont::getGlyphWidth(const char * data) const
  98. {
  99. std::string localChar = Unicode::fromUnicode(std::string(data, Unicode::getCharacterSize(data[0])));
  100. if (localChar.size() == 1)
  101. {
  102. const BitmapChar & ch = chars[ui8(localChar[0])];
  103. return ch.leftOffset + ch.width + ch.rightOffset;
  104. }
  105. return 0;
  106. }
  107. void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const SDL_Color & color, int &posX, int &posY) const
  108. {
  109. Rect clipRect;
  110. CSDL_Ext::getClipRect(surface, clipRect);
  111. posX += character.leftOffset;
  112. CSDL_Ext::TColorPutter colorPutter = CSDL_Ext::getPutterFor(surface, 0);
  113. uint8_t bpp = surface->format->BytesPerPixel;
  114. // start of line, may differ from 0 due to end of surface or clipped surface
  115. int lineBegin = std::max<int>(0, clipRect.y - posY);
  116. int lineEnd = std::min<int>(height, clipRect.y + clipRect.h - posY - 1);
  117. // start end end of each row, may differ from 0
  118. int rowBegin = std::max<int>(0, clipRect.x - posX);
  119. int rowEnd = std::min<int>(character.width, clipRect.x + clipRect.w - posX - 1);
  120. //for each line in symbol
  121. for(int dy = lineBegin; dy <lineEnd; dy++)
  122. {
  123. uint8_t *dstLine = (uint8_t*)surface->pixels;
  124. uint8_t *srcLine = character.pixels;
  125. // shift source\destination pixels to current position
  126. dstLine += (posY+dy) * surface->pitch + posX * bpp;
  127. srcLine += dy * character.width;
  128. //for each column in line
  129. for(int dx = rowBegin; dx < rowEnd; dx++)
  130. {
  131. uint8_t* dstPixel = dstLine + dx*bpp;
  132. switch(srcLine[dx])
  133. {
  134. case 1: //black "shadow"
  135. colorPutter(dstPixel, 0, 0, 0);
  136. break;
  137. case 255: //text colour
  138. colorPutter(dstPixel, color.r, color.g, color.b);
  139. break;
  140. default :
  141. break; //transparency
  142. }
  143. }
  144. }
  145. posX += character.width;
  146. posX += character.rightOffset;
  147. }
  148. void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  149. {
  150. if (data.empty())
  151. return;
  152. assert(surface);
  153. int posX = pos.x;
  154. int posY = pos.y;
  155. // Should be used to detect incorrect text parsing. Disabled right now due to some old UI code (mostly pregame and battles)
  156. //assert(data[0] != '{');
  157. //assert(data[data.size()-1] != '}');
  158. SDL_LockSurface(surface);
  159. for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
  160. {
  161. std::string localChar = Unicode::fromUnicode(data.substr(i, Unicode::getCharacterSize(data[i])));
  162. if (localChar.size() == 1)
  163. renderCharacter(surface, chars[ui8(localChar[0])], color, posX, posY);
  164. }
  165. SDL_UnlockSurface(surface);
  166. }
  167. std::pair<std::unique_ptr<ui8[]>, ui64> CTrueTypeFont::loadData(const JsonNode & config)
  168. {
  169. std::string filename = "Data/" + config["file"].String();
  170. return CResourceHandler::get()->load(ResourceID(filename, EResType::TTF_FONT))->readAll();
  171. }
  172. TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config)
  173. {
  174. int pointSize = static_cast<int>(config["size"].Float());
  175. if(!TTF_WasInit() && TTF_Init()==-1)
  176. throw std::runtime_error(std::string("Failed to initialize true type support: ") + TTF_GetError() + "\n");
  177. return TTF_OpenFontRW(SDL_RWFromConstMem(data.first.get(), (int)data.second), 1, pointSize);
  178. }
  179. int CTrueTypeFont::getFontStyle(const JsonNode &config)
  180. {
  181. const JsonVector & names = config["style"].Vector();
  182. int ret = 0;
  183. for(const JsonNode & node : names)
  184. {
  185. if (node.String() == "bold")
  186. ret |= TTF_STYLE_BOLD;
  187. else if (node.String() == "italic")
  188. ret |= TTF_STYLE_ITALIC;
  189. }
  190. return ret;
  191. }
  192. CTrueTypeFont::CTrueTypeFont(const JsonNode & fontConfig):
  193. data(loadData(fontConfig)),
  194. font(loadFont(fontConfig), TTF_CloseFont),
  195. blended(fontConfig["blend"].Bool())
  196. {
  197. assert(font);
  198. TTF_SetFontStyle(font.get(), getFontStyle(fontConfig));
  199. }
  200. size_t CTrueTypeFont::getLineHeight() const
  201. {
  202. return TTF_FontHeight(font.get());
  203. }
  204. size_t CTrueTypeFont::getGlyphWidth(const char *data) const
  205. {
  206. return getStringWidth(std::string(data, Unicode::getCharacterSize(*data)));
  207. /*
  208. int advance;
  209. TTF_GlyphMetrics(font.get(), *data, nullptr, nullptr, nullptr, nullptr, &advance);
  210. return advance;
  211. */
  212. }
  213. size_t CTrueTypeFont::getStringWidth(const std::string & data) const
  214. {
  215. int width;
  216. TTF_SizeUTF8(font.get(), data.c_str(), &width, nullptr);
  217. return width;
  218. }
  219. void CTrueTypeFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  220. {
  221. if (color.r != 0 && color.g != 0 && color.b != 0) // not black - add shadow
  222. renderText(surface, data, Colors::BLACK, pos + Point(1,1));
  223. if (!data.empty())
  224. {
  225. SDL_Surface * rendered;
  226. if (blended)
  227. rendered = TTF_RenderUTF8_Blended(font.get(), data.c_str(), color);
  228. else
  229. rendered = TTF_RenderUTF8_Solid(font.get(), data.c_str(), color);
  230. assert(rendered);
  231. CSDL_Ext::blitSurface(rendered, surface, pos);
  232. SDL_FreeSurface(rendered);
  233. }
  234. }
  235. size_t CBitmapHanFont::getCharacterDataOffset(size_t index) const
  236. {
  237. size_t rowSize = (size + 7) / 8; // 1 bit per pixel, rounded up
  238. size_t charSize = rowSize * size; // glyph contains "size" rows
  239. return index * charSize;
  240. }
  241. size_t CBitmapHanFont::getCharacterIndex(ui8 first, ui8 second) const
  242. {
  243. if (second > 0x7f )
  244. second--;
  245. return (first - 0x81) * (12*16 - 2) + (second - 0x40);
  246. }
  247. void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex, const SDL_Color & color, int &posX, int &posY) const
  248. {
  249. //TODO: somewhat duplicated with CBitmapFont::renderCharacter();
  250. Rect clipRect;
  251. CSDL_Ext::getClipRect(surface, clipRect);
  252. CSDL_Ext::TColorPutter colorPutter = CSDL_Ext::getPutterFor(surface, 0);
  253. uint8_t bpp = surface->format->BytesPerPixel;
  254. // start of line, may differ from 0 due to end of surface or clipped surface
  255. int lineBegin = std::max<int>(0, clipRect.y - posY);
  256. int lineEnd = std::min((int)size, clipRect.y + clipRect.h - posY);
  257. // start end end of each row, may differ from 0
  258. int rowBegin = std::max<int>(0, clipRect.x - posX);
  259. int rowEnd = std::min<int>((int)size, clipRect.x + clipRect.w - posX);
  260. //for each line in symbol
  261. for(int dy = lineBegin; dy <lineEnd; dy++)
  262. {
  263. uint8_t *dstLine = (uint8_t*)surface->pixels;
  264. uint8_t *source = data.first.get() + getCharacterDataOffset(characterIndex);
  265. // shift source\destination pixels to current position
  266. dstLine += (posY+dy) * surface->pitch + posX * bpp;
  267. source += ((size + 7) / 8) * dy;
  268. //for each column in line
  269. for(int dx = rowBegin; dx < rowEnd; dx++)
  270. {
  271. // select current bit in bitmap
  272. int bit = (source[dx / 8] << (dx % 8)) & 0x80;
  273. uint8_t* dstPixel = dstLine + dx*bpp;
  274. if (bit != 0)
  275. colorPutter(dstPixel, color.r, color.g, color.b);
  276. }
  277. }
  278. posX += (int)size + 1;
  279. }
  280. void CBitmapHanFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  281. {
  282. int posX = pos.x;
  283. int posY = pos.y;
  284. SDL_LockSurface(surface);
  285. for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
  286. {
  287. std::string localChar = Unicode::fromUnicode(data.substr(i, Unicode::getCharacterSize(data[i])));
  288. if (localChar.size() == 1)
  289. fallback->renderCharacter(surface, fallback->chars[ui8(localChar[0])], color, posX, posY);
  290. if (localChar.size() == 2)
  291. renderCharacter(surface, (int)getCharacterIndex(localChar[0], localChar[1]), color, posX, posY);
  292. }
  293. SDL_UnlockSurface(surface);
  294. }
  295. CBitmapHanFont::CBitmapHanFont(const JsonNode &config):
  296. fallback(new CBitmapFont(config["fallback"].String())),
  297. data(CResourceHandler::get()->load(ResourceID("data/" + config["name"].String(), EResType::OTHER))->readAll()),
  298. size((size_t)config["size"].Float())
  299. {
  300. // basic tests to make sure that fonts are OK
  301. // 1) fonts must contain 190 "sections", 126 symbols each.
  302. assert(getCharacterIndex(0xfe, 0xff) == 190*126);
  303. // 2) ensure that font size is correct - enough to fit all possible symbols
  304. assert(getCharacterDataOffset(getCharacterIndex(0xfe, 0xff)) == data.second);
  305. }
  306. size_t CBitmapHanFont::getLineHeight() const
  307. {
  308. return std::max(size + 1, fallback->getLineHeight());
  309. }
  310. size_t CBitmapHanFont::getGlyphWidth(const char * data) const
  311. {
  312. std::string localChar = Unicode::fromUnicode(std::string(data, Unicode::getCharacterSize(data[0])));
  313. if (localChar.size() == 1)
  314. return fallback->getGlyphWidth(data);
  315. if (localChar.size() == 2)
  316. return size + 1;
  317. return 0;
  318. }