BsTextData.h 13 KB

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