Text.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Texture2D.h"
  26. #include "../IO/Log.h"
  27. #include "../Resource/ResourceCache.h"
  28. #include "../UI/Font.h"
  29. #include "../UI/FontFace.h"
  30. #include "../UI/Text.h"
  31. #include "../Resource/Localization.h"
  32. #include "../Resource/ResourceEvents.h"
  33. #include "../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. const char* textEffects[] =
  37. {
  38. "None",
  39. "Shadow",
  40. "Stroke",
  41. 0
  42. };
  43. static const float MIN_ROW_SPACING = 0.5f;
  44. extern const char* horizontalAlignments[];
  45. extern const char* UI_CATEGORY;
  46. Text::Text(Context* context) :
  47. UIElement(context),
  48. fontSize_(DEFAULT_FONT_SIZE),
  49. textAlignment_(HA_LEFT),
  50. rowSpacing_(1.0f),
  51. wordWrap_(false),
  52. autoLocalizable_(false),
  53. charLocationsDirty_(true),
  54. selectionStart_(0),
  55. selectionLength_(0),
  56. selectionColor_(Color::TRANSPARENT),
  57. hoverColor_(Color::TRANSPARENT),
  58. textEffect_(TE_NONE),
  59. shadowOffset_(IntVector2(1, 1)),
  60. strokeThickness_(1),
  61. roundStroke_(false),
  62. effectColor_(Color::BLACK),
  63. effectDepthBias_(0.0f),
  64. rowHeight_(0)
  65. {
  66. // By default Text does not derive opacity from parent elements
  67. useDerivedOpacity_ = false;
  68. }
  69. Text::~Text()
  70. {
  71. }
  72. void Text::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<Text>(UI_CATEGORY);
  75. URHO3D_COPY_BASE_ATTRIBUTES(UIElement);
  76. URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Use Derived Opacity", false);
  77. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Font", GetFontAttr, SetFontAttr, ResourceRef, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  78. URHO3D_ATTRIBUTE("Font Size", float, fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  79. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Text", GetTextAttr, SetTextAttr, String, String::EMPTY, AM_FILE);
  80. URHO3D_ENUM_ATTRIBUTE("Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  81. URHO3D_ATTRIBUTE("Row Spacing", float, rowSpacing_, 1.0f, AM_FILE);
  82. URHO3D_ATTRIBUTE("Word Wrap", bool, wordWrap_, false, AM_FILE);
  83. URHO3D_ACCESSOR_ATTRIBUTE("Auto Localizable", GetAutoLocalizable, SetAutoLocalizable, bool, false, AM_FILE);
  84. URHO3D_ACCESSOR_ATTRIBUTE("Selection Color", GetSelectionColor, SetSelectionColor, Color, Color::TRANSPARENT, AM_FILE);
  85. URHO3D_ACCESSOR_ATTRIBUTE("Hover Color", GetHoverColor, SetHoverColor, Color, Color::TRANSPARENT, AM_FILE);
  86. URHO3D_ENUM_ATTRIBUTE("Text Effect", textEffect_, textEffects, TE_NONE, AM_FILE);
  87. URHO3D_ATTRIBUTE("Shadow Offset", IntVector2, shadowOffset_, IntVector2(1, 1), AM_FILE);
  88. URHO3D_ATTRIBUTE("Stroke Thickness", int, strokeThickness_, 1, AM_FILE);
  89. URHO3D_ATTRIBUTE("Round Stroke", bool, roundStroke_, false, AM_FILE);
  90. URHO3D_ACCESSOR_ATTRIBUTE("Effect Color", GetEffectColor, SetEffectColor, Color, Color::BLACK, AM_FILE);
  91. // Change the default value for UseDerivedOpacity
  92. context->GetAttribute<Text>("Use Derived Opacity")->defaultValue_ = false;
  93. }
  94. void Text::ApplyAttributes()
  95. {
  96. UIElement::ApplyAttributes();
  97. // Localize now if attributes were loaded out-of-order
  98. if (autoLocalizable_ && stringId_.Length())
  99. {
  100. Localization* l10n = GetSubsystem<Localization>();
  101. text_ = l10n->Get(stringId_);
  102. }
  103. DecodeToUnicode();
  104. fontSize_ = Max(fontSize_, 1);
  105. strokeThickness_ = Abs(strokeThickness_);
  106. ValidateSelection();
  107. UpdateText();
  108. }
  109. void Text::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  110. {
  111. FontFace* face = font_ ? font_->GetFace(fontSize_) : (FontFace*)0;
  112. if (!face)
  113. {
  114. hovering_ = false;
  115. return;
  116. }
  117. // If face has changed or char locations are not valid anymore, update before rendering
  118. if (charLocationsDirty_ || !fontFace_ || face != fontFace_)
  119. UpdateCharLocations();
  120. // If face uses mutable glyphs mechanism, reacquire glyphs before rendering to make sure they are in the texture
  121. else if (face->HasMutableGlyphs())
  122. {
  123. for (unsigned i = 0; i < printText_.Size(); ++i)
  124. face->GetGlyph(printText_[i]);
  125. }
  126. // Hovering and/or whole selection batch
  127. if ((hovering_ && hoverColor_.a_ > 0.0) || (selected_ && selectionColor_.a_ > 0.0f))
  128. {
  129. bool both = hovering_ && selected_ && hoverColor_.a_ > 0.0 && selectionColor_.a_ > 0.0f;
  130. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  131. batch.SetColor(both ? selectionColor_.Lerp(hoverColor_, 0.5f) :
  132. (selected_ && selectionColor_.a_ > 0.0f ? selectionColor_ : hoverColor_));
  133. batch.AddQuad(0, 0, GetWidth(), GetHeight(), 0, 0);
  134. UIBatch::AddOrMerge(batch, batches);
  135. }
  136. // Partial selection batch
  137. if (!selected_ && selectionLength_ && charLocations_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  138. {
  139. UIBatch batch(this, BLEND_ALPHA, currentScissor, 0, &vertexData);
  140. batch.SetColor(selectionColor_);
  141. Vector2 currentStart = charLocations_[selectionStart_].position_;
  142. Vector2 currentEnd = currentStart;
  143. for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  144. {
  145. // Check if row changes, and start a new quad in that case
  146. if (charLocations_[i].size_ != Vector2::ZERO)
  147. {
  148. if (charLocations_[i].position_.y_ != currentStart.y_)
  149. {
  150. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_,
  151. currentEnd.y_ - currentStart.y_, 0, 0);
  152. currentStart = charLocations_[i].position_;
  153. currentEnd = currentStart + charLocations_[i].size_;
  154. }
  155. else
  156. {
  157. currentEnd.x_ += charLocations_[i].size_.x_;
  158. currentEnd.y_ = Max(currentStart.y_ + charLocations_[i].size_.y_, currentEnd.y_);
  159. }
  160. }
  161. }
  162. if (currentEnd != currentStart)
  163. {
  164. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_, 0, 0);
  165. }
  166. UIBatch::AddOrMerge(batch, batches);
  167. }
  168. // Text batch
  169. TextEffect textEffect = font_->IsSDFFont() ? TE_NONE : textEffect_;
  170. const Vector<SharedPtr<Texture2D> >& textures = face->GetTextures();
  171. for (unsigned n = 0; n < textures.Size() && n < pageGlyphLocations_.Size(); ++n)
  172. {
  173. // One batch per texture/page
  174. UIBatch pageBatch(this, BLEND_ALPHA, currentScissor, textures[n], &vertexData);
  175. const PODVector<GlyphLocation>& pageGlyphLocation = pageGlyphLocations_[n];
  176. switch (textEffect)
  177. {
  178. case TE_NONE:
  179. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  180. break;
  181. case TE_SHADOW:
  182. ConstructBatch(pageBatch, pageGlyphLocation, shadowOffset_.x_, shadowOffset_.y_, &effectColor_, effectDepthBias_);
  183. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  184. break;
  185. case TE_STROKE:
  186. if (roundStroke_)
  187. {
  188. // Samples should be even or glyph may be redrawn in wrong x y pos making stroke corners rough
  189. // Adding to thickness helps with thickness of 1 not having enought samples for this formula
  190. // or certain fonts with reflex corners requiring more glyph samples for a smooth stroke when large
  191. int thickness = Min(strokeThickness_, fontSize_);
  192. int samples = thickness * thickness + (thickness % 2 == 0 ? 4 : 3);
  193. float angle = 360.f / samples;
  194. float floatThickness = (float)thickness;
  195. for (int i = 0; i < samples; ++i)
  196. {
  197. float x = Cos(angle * i) * floatThickness;
  198. float y = Sin(angle * i) * floatThickness;
  199. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  200. }
  201. }
  202. else
  203. {
  204. int thickness = Min(strokeThickness_, fontSize_);
  205. int x, y;
  206. for (x = -thickness; x <= thickness; ++x)
  207. {
  208. for (y = -thickness; y <= thickness; ++y)
  209. {
  210. // Don't draw glyphs that aren't on the edges
  211. if (x > -thickness && x < thickness &&
  212. y > -thickness && y < thickness)
  213. continue;
  214. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  215. }
  216. }
  217. }
  218. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  219. break;
  220. }
  221. UIBatch::AddOrMerge(pageBatch, batches);
  222. }
  223. // Reset hovering for next frame
  224. hovering_ = false;
  225. }
  226. void Text::OnResize(const IntVector2& newSize, const IntVector2& delta)
  227. {
  228. if (wordWrap_)
  229. UpdateText(true);
  230. else
  231. charLocationsDirty_ = true;
  232. }
  233. void Text::OnIndentSet()
  234. {
  235. charLocationsDirty_ = true;
  236. }
  237. bool Text::SetFont(const String& fontName, int size)
  238. {
  239. ResourceCache* cache = GetSubsystem<ResourceCache>();
  240. return SetFont(cache->GetResource<Font>(fontName), size);
  241. }
  242. bool Text::SetFont(Font* font, float size)
  243. {
  244. if (!font)
  245. {
  246. URHO3D_LOGERROR("Null font for Text");
  247. return false;
  248. }
  249. if (font != font_ || size != fontSize_)
  250. {
  251. font_ = font;
  252. fontSize_ = Max(size, 1);
  253. UpdateText();
  254. }
  255. return true;
  256. }
  257. bool Text::SetFontSize(float size)
  258. {
  259. // Initial font must be set
  260. if (!font_)
  261. return false;
  262. else
  263. return SetFont(font_, size);
  264. }
  265. void Text::DecodeToUnicode()
  266. {
  267. unicodeText_.Clear();
  268. for (unsigned i = 0; i < text_.Length();)
  269. unicodeText_.Push(text_.NextUTF8Char(i));
  270. }
  271. void Text::SetText(const String& text)
  272. {
  273. if (autoLocalizable_)
  274. {
  275. stringId_ = text;
  276. Localization* l10n = GetSubsystem<Localization>();
  277. text_ = l10n->Get(stringId_);
  278. }
  279. else
  280. {
  281. text_ = text;
  282. }
  283. DecodeToUnicode();
  284. ValidateSelection();
  285. UpdateText();
  286. }
  287. void Text::SetTextAlignment(HorizontalAlignment align)
  288. {
  289. if (align != textAlignment_)
  290. {
  291. textAlignment_ = align;
  292. charLocationsDirty_ = true;
  293. }
  294. }
  295. void Text::SetRowSpacing(float spacing)
  296. {
  297. if (spacing != rowSpacing_)
  298. {
  299. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  300. UpdateText();
  301. }
  302. }
  303. void Text::SetWordwrap(bool enable)
  304. {
  305. if (enable != wordWrap_)
  306. {
  307. wordWrap_ = enable;
  308. UpdateText();
  309. }
  310. }
  311. void Text::SetAutoLocalizable(bool enable)
  312. {
  313. if (enable != autoLocalizable_)
  314. {
  315. autoLocalizable_ = enable;
  316. if (enable)
  317. {
  318. stringId_ = text_;
  319. Localization* l10n = GetSubsystem<Localization>();
  320. text_ = l10n->Get(stringId_);
  321. SubscribeToEvent(E_CHANGELANGUAGE, URHO3D_HANDLER(Text, HandleChangeLanguage));
  322. }
  323. else
  324. {
  325. text_ = stringId_;
  326. stringId_ = "";
  327. UnsubscribeFromEvent(E_CHANGELANGUAGE);
  328. }
  329. DecodeToUnicode();
  330. ValidateSelection();
  331. UpdateText();
  332. }
  333. }
  334. void Text::HandleChangeLanguage(StringHash eventType, VariantMap& eventData)
  335. {
  336. Localization* l10n = GetSubsystem<Localization>();
  337. text_ = l10n->Get(stringId_);
  338. DecodeToUnicode();
  339. ValidateSelection();
  340. UpdateText();
  341. }
  342. void Text::SetSelection(unsigned start, unsigned length)
  343. {
  344. selectionStart_ = start;
  345. selectionLength_ = length;
  346. ValidateSelection();
  347. }
  348. void Text::ClearSelection()
  349. {
  350. selectionStart_ = 0;
  351. selectionLength_ = 0;
  352. }
  353. void Text::SetSelectionColor(const Color& color)
  354. {
  355. selectionColor_ = color;
  356. }
  357. void Text::SetHoverColor(const Color& color)
  358. {
  359. hoverColor_ = color;
  360. }
  361. void Text::SetTextEffect(TextEffect textEffect)
  362. {
  363. textEffect_ = textEffect;
  364. }
  365. void Text::SetEffectShadowOffset(const IntVector2& offset)
  366. {
  367. shadowOffset_ = offset;
  368. }
  369. void Text::SetEffectStrokeThickness(int thickness)
  370. {
  371. strokeThickness_ = Abs(thickness);
  372. }
  373. void Text::SetEffectRoundStroke(bool roundStroke)
  374. {
  375. roundStroke_ = roundStroke;
  376. }
  377. void Text::SetEffectColor(const Color& effectColor)
  378. {
  379. effectColor_ = effectColor;
  380. }
  381. void Text::SetEffectDepthBias(float bias)
  382. {
  383. effectDepthBias_ = bias;
  384. }
  385. float Text::GetRowWidth(unsigned index) const
  386. {
  387. return index < rowWidths_.Size() ? rowWidths_[index] : 0;
  388. }
  389. Vector2 Text::GetCharPosition(unsigned index)
  390. {
  391. if (charLocationsDirty_)
  392. UpdateCharLocations();
  393. if (charLocations_.Empty())
  394. return Vector2::ZERO;
  395. // For convenience, return the position of the text ending if index exceeded
  396. if (index > charLocations_.Size() - 1)
  397. index = charLocations_.Size() - 1;
  398. return charLocations_[index].position_;
  399. }
  400. Vector2 Text::GetCharSize(unsigned index)
  401. {
  402. if (charLocationsDirty_)
  403. UpdateCharLocations();
  404. if (charLocations_.Size() < 2)
  405. return Vector2::ZERO;
  406. // For convenience, return the size of the last char if index exceeded (last size entry is zero)
  407. if (index > charLocations_.Size() - 2)
  408. index = charLocations_.Size() - 2;
  409. return charLocations_[index].size_;
  410. }
  411. void Text::SetFontAttr(const ResourceRef& value)
  412. {
  413. ResourceCache* cache = GetSubsystem<ResourceCache>();
  414. font_ = cache->GetResource<Font>(value.name_);
  415. }
  416. ResourceRef Text::GetFontAttr() const
  417. {
  418. return GetResourceRef(font_, Font::GetTypeStatic());
  419. }
  420. void Text::SetTextAttr(const String& value)
  421. {
  422. text_ = value;
  423. if (autoLocalizable_)
  424. stringId_ = value;
  425. }
  426. String Text::GetTextAttr() const
  427. {
  428. if (autoLocalizable_ && stringId_.Length())
  429. return stringId_;
  430. else
  431. return text_;
  432. }
  433. bool Text::FilterImplicitAttributes(XMLElement& dest) const
  434. {
  435. if (!UIElement::FilterImplicitAttributes(dest))
  436. return false;
  437. if (!IsFixedWidth())
  438. {
  439. if (!RemoveChildXML(dest, "Size"))
  440. return false;
  441. if (!RemoveChildXML(dest, "Min Size"))
  442. return false;
  443. if (!RemoveChildXML(dest, "Max Size"))
  444. return false;
  445. }
  446. return true;
  447. }
  448. void Text::UpdateText(bool onResize)
  449. {
  450. rowWidths_.Clear();
  451. printText_.Clear();
  452. if (font_)
  453. {
  454. FontFace* face = font_->GetFace(fontSize_);
  455. if (!face)
  456. return;
  457. rowHeight_ = face->GetRowHeight();
  458. int width = 0;
  459. int height = 0;
  460. int rowWidth = 0;
  461. int rowHeight = (int)(rowSpacing_ * rowHeight_ + 0.5f);
  462. // First see if the text must be split up
  463. if (!wordWrap_)
  464. {
  465. printText_ = unicodeText_;
  466. printToText_.Resize(printText_.Size());
  467. for (unsigned i = 0; i < printText_.Size(); ++i)
  468. printToText_[i] = i;
  469. }
  470. else
  471. {
  472. int maxWidth = GetWidth();
  473. unsigned nextBreak = 0;
  474. unsigned lineStart = 0;
  475. printToText_.Clear();
  476. for (unsigned i = 0; i < unicodeText_.Size(); ++i)
  477. {
  478. unsigned j;
  479. unsigned c = unicodeText_[i];
  480. if (c != '\n')
  481. {
  482. bool ok = true;
  483. if (nextBreak <= i)
  484. {
  485. int futureRowWidth = rowWidth;
  486. for (j = i; j < unicodeText_.Size(); ++j)
  487. {
  488. unsigned d = unicodeText_[j];
  489. if (d == ' ' || d == '\n')
  490. {
  491. nextBreak = j;
  492. break;
  493. }
  494. const FontGlyph* glyph = face->GetGlyph(d);
  495. if (glyph)
  496. {
  497. futureRowWidth += glyph->advanceX_;
  498. if (j < unicodeText_.Size() - 1)
  499. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  500. }
  501. if (d == '-' && futureRowWidth <= maxWidth)
  502. {
  503. nextBreak = j + 1;
  504. break;
  505. }
  506. if (futureRowWidth > maxWidth)
  507. {
  508. ok = false;
  509. break;
  510. }
  511. }
  512. }
  513. if (!ok)
  514. {
  515. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  516. if (nextBreak == lineStart)
  517. {
  518. while (i < j)
  519. {
  520. printText_.Push(unicodeText_[i]);
  521. printToText_.Push(i);
  522. ++i;
  523. }
  524. }
  525. // Eliminate spaces that have been copied before the forced break
  526. while (printText_.Size() && printText_.Back() == ' ')
  527. {
  528. printText_.Pop();
  529. printToText_.Pop();
  530. }
  531. printText_.Push('\n');
  532. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  533. rowWidth = 0;
  534. nextBreak = lineStart = i;
  535. }
  536. if (i < unicodeText_.Size())
  537. {
  538. // When copying a space, position is allowed to be over row width
  539. c = unicodeText_[i];
  540. const FontGlyph* glyph = face->GetGlyph(c);
  541. if (glyph)
  542. {
  543. rowWidth += glyph->advanceX_;
  544. if (i < unicodeText_.Size() - 1)
  545. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  546. }
  547. if (rowWidth <= maxWidth)
  548. {
  549. printText_.Push(c);
  550. printToText_.Push(i);
  551. }
  552. }
  553. }
  554. else
  555. {
  556. printText_.Push('\n');
  557. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  558. rowWidth = 0;
  559. nextBreak = lineStart = i;
  560. }
  561. }
  562. }
  563. rowWidth = 0;
  564. for (unsigned i = 0; i < printText_.Size(); ++i)
  565. {
  566. unsigned c = printText_[i];
  567. if (c != '\n')
  568. {
  569. const FontGlyph* glyph = face->GetGlyph(c);
  570. if (glyph)
  571. {
  572. rowWidth += glyph->advanceX_;
  573. if (i < printText_.Size() - 1)
  574. rowWidth += face->GetKerning(c, printText_[i + 1]);
  575. }
  576. }
  577. else
  578. {
  579. width = Max(width, rowWidth);
  580. height += rowHeight;
  581. rowWidths_.Push(rowWidth);
  582. rowWidth = 0;
  583. }
  584. }
  585. if (rowWidth)
  586. {
  587. width = Max(width, rowWidth);
  588. height += rowHeight;
  589. rowWidths_.Push(rowWidth);
  590. }
  591. // Set at least one row height even if text is empty
  592. if (!height)
  593. height = rowHeight;
  594. // Set minimum and current size according to the text size, but respect fixed width if set
  595. if (!IsFixedWidth())
  596. {
  597. SetMinWidth(wordWrap_ ? 0 : width);
  598. SetWidth(width);
  599. }
  600. SetFixedHeight(height);
  601. charLocationsDirty_ = true;
  602. }
  603. else
  604. {
  605. // No font, nothing to render
  606. pageGlyphLocations_.Clear();
  607. }
  608. // If wordwrap is on, parent may need layout update to correct for overshoot in size. However, do not do this when the
  609. // update is a response to resize, as that could cause infinite recursion
  610. if (wordWrap_ && !onResize)
  611. {
  612. UIElement* parent = GetParent();
  613. if (parent && parent->GetLayoutMode() != LM_FREE)
  614. parent->UpdateLayout();
  615. }
  616. }
  617. void Text::UpdateCharLocations()
  618. {
  619. // Remember the font face to see if it's still valid when it's time to render
  620. FontFace* face = font_ ? font_->GetFace(fontSize_) : (FontFace*)0;
  621. if (!face)
  622. return;
  623. fontFace_ = face;
  624. int rowHeight = (int)(rowSpacing_ * rowHeight_ + 0.5f);
  625. // Store position & size of each character, and locations per texture page
  626. unsigned numChars = unicodeText_.Size();
  627. charLocations_.Resize(numChars + 1);
  628. pageGlyphLocations_.Resize(face->GetTextures().Size());
  629. for (unsigned i = 0; i < pageGlyphLocations_.Size(); ++i)
  630. pageGlyphLocations_[i].Clear();
  631. IntVector2 offset = font_->GetTotalGlyphOffset(fontSize_);
  632. unsigned rowIndex = 0;
  633. unsigned lastFilled = 0;
  634. float x = floor(GetRowStartPosition(rowIndex) + offset.x_ + 0.5f);
  635. float y = floor(offset.y_ + 0.5f);
  636. for (unsigned i = 0; i < printText_.Size(); ++i)
  637. {
  638. CharLocation loc;
  639. loc.position_ = Vector2(x, y);
  640. unsigned c = printText_[i];
  641. if (c != '\n')
  642. {
  643. const FontGlyph* glyph = face->GetGlyph(c);
  644. loc.size_ = Vector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  645. if (glyph)
  646. {
  647. // Store glyph's location for rendering. Verify that glyph page is valid
  648. if (glyph->page_ < pageGlyphLocations_.Size())
  649. pageGlyphLocations_[glyph->page_].Push(GlyphLocation(x, y, glyph));
  650. x += glyph->advanceX_;
  651. if (i < printText_.Size() - 1)
  652. x += face->GetKerning(c, printText_[i + 1]);
  653. }
  654. }
  655. else
  656. {
  657. loc.size_ = Vector2::ZERO;
  658. x = GetRowStartPosition(++rowIndex);
  659. y += rowHeight;
  660. }
  661. if (lastFilled > printToText_[i])
  662. lastFilled = printToText_[i];
  663. // Fill gaps in case characters were skipped from printing
  664. for (unsigned j = lastFilled; j <= printToText_[i]; ++j)
  665. charLocations_[j] = loc;
  666. lastFilled = printToText_[i] + 1;
  667. }
  668. // Store the ending position
  669. charLocations_[numChars].position_ = Vector2(x, y);
  670. charLocations_[numChars].size_ = Vector2::ZERO;
  671. charLocationsDirty_ = false;
  672. }
  673. void Text::ValidateSelection()
  674. {
  675. unsigned textLength = unicodeText_.Size();
  676. if (textLength)
  677. {
  678. if (selectionStart_ >= textLength)
  679. selectionStart_ = textLength - 1;
  680. if (selectionStart_ + selectionLength_ > textLength)
  681. selectionLength_ = textLength - selectionStart_;
  682. }
  683. else
  684. {
  685. selectionStart_ = 0;
  686. selectionLength_ = 0;
  687. }
  688. }
  689. int Text::GetRowStartPosition(unsigned rowIndex) const
  690. {
  691. float rowWidth = 0;
  692. if (rowIndex < rowWidths_.Size())
  693. rowWidth = rowWidths_[rowIndex];
  694. int ret = GetIndentWidth();
  695. switch (textAlignment_)
  696. {
  697. case HA_LEFT:
  698. break;
  699. case HA_CENTER:
  700. ret += (GetSize().x_ - rowWidth) / 2;
  701. break;
  702. case HA_RIGHT:
  703. ret += GetSize().x_ - rowWidth;
  704. break;
  705. }
  706. return ret;
  707. }
  708. void Text::ConstructBatch(UIBatch& pageBatch, const PODVector<GlyphLocation>& pageGlyphLocation, float dx, float dy, Color* color,
  709. float depthBias)
  710. {
  711. unsigned startDataSize = pageBatch.vertexData_->Size();
  712. if (!color)
  713. pageBatch.SetDefaultColor();
  714. else
  715. pageBatch.SetColor(*color);
  716. for (unsigned i = 0; i < pageGlyphLocation.Size(); ++i)
  717. {
  718. const GlyphLocation& glyphLocation = pageGlyphLocation[i];
  719. const FontGlyph& glyph = *glyphLocation.glyph_;
  720. pageBatch.AddQuad(dx + glyphLocation.x_ + glyph.offsetX_, dy + glyphLocation.y_ + glyph.offsetY_, glyph.width_,
  721. glyph.height_, glyph.x_, glyph.y_);
  722. }
  723. if (depthBias != 0.0f)
  724. {
  725. unsigned dataSize = pageBatch.vertexData_->Size();
  726. for (unsigned i = startDataSize; i < dataSize; i += UI_VERTEX_SIZE)
  727. pageBatch.vertexData_->At(i + 2) += depthBias;
  728. }
  729. }
  730. }