BsTextData.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsFontDesc.h"
  6. #include "BsVector2I.h"
  7. namespace BansheeEngine
  8. {
  9. /** @cond INTERNAL */
  10. /** @addtogroup Implementation
  11. * @{
  12. */
  13. /**
  14. * This object takes as input a string, a font and optionally some constraints (like word wrap) and outputs a set of
  15. * character data you may use for rendering or metrics.
  16. */
  17. class TextDataBase
  18. {
  19. protected:
  20. /**
  21. * Represents a single word as a set of characters, or optionally just a blank space of a certain length.
  22. *
  23. * @note Due to the way allocation is handled, this class is not allowed to have a destructor.
  24. */
  25. class TextWord
  26. {
  27. public:
  28. /**
  29. * Initializes the word and signals if it just a space (or multiple spaces), or an actual word with letters.
  30. */
  31. void init(bool spacer);
  32. /**
  33. * Appends a new character to the word.
  34. *
  35. * @param[in] charIdx Sequential index of the character in the original string.
  36. * @param[in] desc Character description from the font.
  37. * @return How many pixels did the added character expand the word by.
  38. */
  39. UINT32 addChar(UINT32 charIdx, const CHAR_DESC& desc);
  40. /** Adds a space to the word. Word must have previously have been declared as a "spacer". */
  41. void addSpace(UINT32 spaceWidth);
  42. /** Returns the width of the word in pixels. */
  43. UINT32 getWidth() const { return mWidth; }
  44. /** Returns height of the word in pixels. */
  45. UINT32 getHeight() const { return mHeight; }
  46. /**
  47. * Calculates new width of the word if we were to add the provided character, without actually adding it.
  48. *
  49. * @param[in] desc Character description from the font.
  50. * @return Width of the word in pixels with the character appended to it.
  51. */
  52. UINT32 calcWidthWithChar(const CHAR_DESC& desc);
  53. /**
  54. * Returns true if word is a spacer. Spacers contain just a space of a certain length with no actual characters.
  55. */
  56. bool isSpacer() const { return mSpacer; }
  57. /** Returns the number of characters in the word. */
  58. UINT32 getNumChars() const { return mLastChar == nullptr ? 0 : (mCharsEnd - mCharsStart + 1); }
  59. /** Returns the index of the starting character in the word. */
  60. UINT32 getCharsStart() const { return mCharsStart; }
  61. /** Returns the index of the last character in the word. */
  62. UINT32 getCharsEnd() const { return mCharsEnd; }
  63. /**
  64. * Calculates width of the character by which it would expand the width of the word if it was added to it.
  65. *
  66. * @param[in] prevDesc Descriptor of the character preceding the one we need the width for. Can be null.
  67. * @param[in] desc Character description from the font.
  68. * @return How many pixels would the added character expand the word by.
  69. */
  70. static UINT32 calcCharWidth(const CHAR_DESC* prevDesc, const CHAR_DESC& desc);
  71. private:
  72. UINT32 mCharsStart, mCharsEnd;
  73. UINT32 mWidth;
  74. UINT32 mHeight;
  75. const CHAR_DESC* mLastChar;
  76. bool mSpacer;
  77. UINT32 mSpaceWidth;
  78. };
  79. /**
  80. * Contains information about a single texture page that contains rendered character data.
  81. *
  82. * @note Due to the way allocation is handled, this class is not allowed to have a destructor.
  83. */
  84. struct PageInfo
  85. {
  86. UINT32 numQuads;
  87. HTexture texture;
  88. };
  89. public:
  90. /**
  91. * Represents a single line as a set of words.
  92. *
  93. * @note Due to the way allocation is handled, this class is not allowed to have a destructor.
  94. */
  95. class BS_CORE_EXPORT TextLine
  96. {
  97. public:
  98. /** Returns width of the line in pixels. */
  99. UINT32 getWidth() const { return mWidth; }
  100. /** Returns height of the line in pixels. */
  101. UINT32 getHeight() const { return mHeight; }
  102. /** Returns an offset used to separate two lines. */
  103. UINT32 getYOffset() const { return mTextData->getLineHeight(); }
  104. /**
  105. * Calculates new width of the line if we were to add the provided character, without actually adding it.
  106. *
  107. * @param[in] desc Character description from the font.
  108. * @return Width of the line in pixels with the character appended to it.
  109. */
  110. UINT32 calcWidthWithChar(const CHAR_DESC& desc);
  111. /**
  112. * Fills the vertex/uv/index buffers for the specified page, with all the character data needed for rendering.
  113. *
  114. * @param[in] page The page.
  115. * @param[out] vertices Pre-allocated array where character vertices will be written.
  116. * @param[out] uvs Pre-allocated array where character uv coordinates will be written.
  117. * @param[out] indexes Pre-allocated array where character indices will be written.
  118. * @param[in] offset Offsets the location at which the method writes to the buffers. Counted as number
  119. * of quads.
  120. * @param[in] size Total number of quads that can fit into the specified buffers.
  121. * @return Number of quads that were written.
  122. */
  123. UINT32 fillBuffer(UINT32 page, Vector2* vertices, Vector2* uvs, UINT32* indexes, UINT32 offset, UINT32 size) const;
  124. /** Checks are we at a word boundary (i.e. next added character will start a new word). */
  125. bool isAtWordBoundary() const;
  126. /** Returns the total number of characters on this line. */
  127. UINT32 getNumChars() const;
  128. /**
  129. * Query if this line was created explicitly due to a newline character. As opposed to a line that was created
  130. * because a word couldn't fit on the previous line.
  131. */
  132. bool hasNewlineChar() const { return mHasNewline; }
  133. private:
  134. friend class TextDataBase;
  135. /**
  136. * Appends a new character to the line.
  137. *
  138. * @param[in] charIdx Sequential index of the character in the original string.
  139. * @param[in] desc Character description from the font.
  140. */
  141. void add(UINT32 charIdx, const CHAR_DESC& charDesc);
  142. /** Appends a space to the line. */
  143. void addSpace(UINT32 spaceWidth);
  144. /**
  145. * Adds a new word to the line.
  146. *
  147. * @param[in] wordIdx Sequential index of the word in the original string. Spaces are counted as words as
  148. * well.
  149. * @param[in] word Description of the word.
  150. */
  151. void addWord(UINT32 wordIdx, const TextWord& word);
  152. /** Initializes the line. Must be called after construction. */
  153. void init(TextDataBase* textData);
  154. /**
  155. * Finalizes the line. Do not add new characters/words after a line has been finalized.
  156. *
  157. * @param[in] hasNewlineChar Set to true if line was create due to an explicit newline char. As opposed to a
  158. * line that was created because a word couldn't fit on the previous line.
  159. */
  160. void finalize(bool hasNewlineChar);
  161. /** Returns true if the line contains no words. */
  162. bool isEmpty() const { return mIsEmpty; }
  163. /** Removes last word from the line and returns its sequential index. */
  164. UINT32 removeLastWord();
  165. /** Calculates the line width and height in pixels. */
  166. void calculateBounds();
  167. private:
  168. TextDataBase* mTextData;
  169. UINT32 mWordsStart, mWordsEnd;
  170. UINT32 mWidth;
  171. UINT32 mHeight;
  172. bool mIsEmpty;
  173. bool mHasNewline;
  174. };
  175. public:
  176. /**
  177. * Initializes a new text data using the specified string and font. Text will attempt to fit into the provided area.
  178. * If enabled it will wrap words to new line when they don't fit. Individual words will be broken into multiple
  179. * pieces if they don't fit on a single line when word break is enabled, otherwise they will be clipped. If the
  180. * specified area is zero size then the text will not be clipped or word wrapped in any way.
  181. *
  182. * After this object is constructed you may call various getter methods to get needed information.
  183. */
  184. BS_CORE_EXPORT TextDataBase(const WString& text, const HFont& font, UINT32 fontSize,
  185. UINT32 width = 0, UINT32 height = 0, bool wordWrap = false, bool wordBreak = true);
  186. BS_CORE_EXPORT virtual ~TextDataBase() { }
  187. /** Returns the number of lines that were generated. */
  188. BS_CORE_EXPORT UINT32 getNumLines() const { return mNumLines; }
  189. /** Returns the number of font pages references by the used characters. */
  190. BS_CORE_EXPORT UINT32 getNumPages() const { return mNumPageInfos; }
  191. /** Returns the height of a line in pixels. */
  192. BS_CORE_EXPORT UINT32 getLineHeight() const;
  193. /** Gets information describing a single line at the specified index. */
  194. BS_CORE_EXPORT const TextLine& getLine(UINT32 idx) const { return mLines[idx]; }
  195. /** Returns font texture for the provided page index. */
  196. BS_CORE_EXPORT const HTexture& getTextureForPage(UINT32 page) const;
  197. /** Returns the number of quads used by all the characters in the provided page. */
  198. BS_CORE_EXPORT UINT32 getNumQuadsForPage(UINT32 page) const { return mPageInfos[page].numQuads; }
  199. /** Returns the width of the actual text in pixels. */
  200. BS_CORE_EXPORT UINT32 getWidth() const;
  201. /** Returns the height of the actual text in pixels. */
  202. BS_CORE_EXPORT UINT32 getHeight() const;
  203. protected:
  204. /**
  205. * Copies internally stored data in temporary buffers to a persistent buffer.
  206. *
  207. * @param[in] text Text originally used for creating the internal temporary buffer data.
  208. * @param[in] buffer Memory location to copy the data to. If null then no data will be copied and the
  209. * parameter @p size will contain the required buffer size.
  210. * @param[in] size Size of the provided memory buffer, or if the buffer is null, this will contain the
  211. * required buffer size after method exists.
  212. * @param[in] freeTemporary If true the internal temporary data will be freed after copying.
  213. *
  214. * @note Must be called after text data has been constructed and is in the temporary buffers.
  215. */
  216. BS_CORE_EXPORT void generatePersistentData(const WString& text, UINT8* buffer, UINT32& size, bool freeTemporary = true);
  217. private:
  218. friend class TextLine;
  219. /** Returns Y offset that determines the line on which the characters are placed. In pixels. */
  220. INT32 getBaselineOffset() const;
  221. /** Returns the width of a single space in pixels. */
  222. UINT32 getSpaceWidth() const;
  223. /** Gets a description of a single character referenced by its sequential index based on the original string. */
  224. const CHAR_DESC& getChar(UINT32 idx) const { return *mChars[idx]; }
  225. /** Gets a description of a single word referenced by its sequential index based on the original string. */
  226. const TextWord& getWord(UINT32 idx) const { return mWords[idx]; }
  227. protected:
  228. const CHAR_DESC** mChars;
  229. UINT32 mNumChars;
  230. TextWord* mWords;
  231. UINT32 mNumWords;
  232. TextLine* mLines;
  233. UINT32 mNumLines;
  234. PageInfo* mPageInfos;
  235. UINT32 mNumPageInfos;
  236. HFont mFont;
  237. SPtr<const FontBitmap> mFontData;
  238. // Static buffers used to reduce runtime memory allocation
  239. protected:
  240. /** Stores per-thread memory buffers used to reduce memory allocation. */
  241. // Note: I could replace this with the global frame allocator to avoid the extra logic
  242. struct BufferData
  243. {
  244. BufferData();
  245. ~BufferData();
  246. /**
  247. * Allocates a new word and adds it to the buffer. Returns index of the word in the word buffer.
  248. *
  249. * @param[in] spacer Specify true if the word is only to contain spaces. (Spaces are considered a special
  250. * type of word).
  251. */
  252. UINT32 allocWord(bool spacer);
  253. /** Allocates a new line and adds it to the buffer. Returns index of the line in the line buffer. */
  254. UINT32 allocLine(TextDataBase* textData);
  255. /**
  256. * Increments the count of characters for the referenced page, and optionally creates page info if it doesn't
  257. * already exist.
  258. */
  259. void addCharToPage(UINT32 page, const FontBitmap& fontData);
  260. /** Resets all allocation counters, but doesn't actually release memory. */
  261. void deallocAll();
  262. TextWord* WordBuffer;
  263. UINT32 WordBufferSize;
  264. UINT32 NextFreeWord;
  265. TextLine* LineBuffer;
  266. UINT32 LineBufferSize;
  267. UINT32 NextFreeLine;
  268. PageInfo* PageBuffer;
  269. UINT32 PageBufferSize;
  270. UINT32 NextFreePageInfo;
  271. };
  272. static BS_THREADLOCAL BufferData* MemBuffer;
  273. /** Allocates an initial set of buffers that will be reused while parsing text data. */
  274. static void initAlloc();
  275. };
  276. /** @} */
  277. /** @addtogroup Text
  278. * @{
  279. */
  280. /** @copydoc TextDataBase */
  281. template<class Alloc = GenAlloc>
  282. class TextData : public TextDataBase
  283. {
  284. public:
  285. /** @copydoc TextDataBase::TextDataBase */
  286. TextData(const WString& text, const HFont& font, UINT32 fontSize,
  287. UINT32 width = 0, UINT32 height = 0, bool wordWrap = false, bool wordBreak = true)
  288. :TextDataBase(text, font, fontSize, width, height, wordWrap, wordBreak), mData(nullptr)
  289. {
  290. UINT32 totalBufferSize = 0;
  291. generatePersistentData(text, nullptr, totalBufferSize);
  292. mData = (UINT8*)bs_alloc<Alloc>(totalBufferSize);
  293. generatePersistentData(text, (UINT8*)mData, totalBufferSize);
  294. }
  295. ~TextData()
  296. {
  297. if (mData != nullptr)
  298. bs_free<Alloc>(mData);
  299. }
  300. private:
  301. UINT8* mData;
  302. };
  303. /** @} */
  304. /** @endcond */
  305. }