UIElement.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "HashSet.h"
  26. #include "Log.h"
  27. #include "ResourceCache.h"
  28. #include "Sort.h"
  29. #include "StringUtils.h"
  30. #include "UI.h"
  31. #include "UIElement.h"
  32. #include "UIEvents.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. static const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. 0
  42. };
  43. static const char* verticalAlignments[] =
  44. {
  45. "Top",
  46. "Center",
  47. "Bottom",
  48. 0
  49. };
  50. static const char* focusModes[] =
  51. {
  52. "NotFocusable",
  53. "ResetFocus",
  54. "Focusable",
  55. "FocusableDefocusable",
  56. 0
  57. };
  58. static const char* dragDropModes[] =
  59. {
  60. "Disabled",
  61. "Source",
  62. "Target",
  63. "SourceAndTarget",
  64. 0
  65. };
  66. static const char* layoutModes[] =
  67. {
  68. "Free",
  69. "Horizontal",
  70. "Vertical",
  71. 0
  72. };
  73. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  74. {
  75. return lhs->GetPriority() < rhs->GetPriority();
  76. }
  77. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  78. {
  79. return (HorizontalAlignment)GetInt();
  80. }
  81. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  82. {
  83. return (VerticalAlignment)GetInt();
  84. }
  85. template<> FocusMode Variant::Get<FocusMode>() const
  86. {
  87. return (FocusMode)GetInt();
  88. }
  89. template<> LayoutMode Variant::Get<LayoutMode>() const
  90. {
  91. return (LayoutMode)GetInt();
  92. }
  93. OBJECTTYPESTATIC(UIElement);
  94. UIElement::UIElement(Context* context) :
  95. Serializable(context),
  96. parent_(0),
  97. clipBorder_(IntRect::ZERO),
  98. priority_(0),
  99. bringToFront_(false),
  100. bringToBack_(true),
  101. clipChildren_(false),
  102. sortChildren_(true),
  103. active_(false),
  104. selected_(false),
  105. visible_(true),
  106. hovering_(false),
  107. internal_(false),
  108. focusMode_(FM_NOTFOCUSABLE),
  109. dragDropMode_(DD_DISABLED),
  110. layoutMode_(LM_FREE),
  111. layoutSpacing_(0),
  112. layoutBorder_(IntRect::ZERO),
  113. resizeNestingLevel_(0),
  114. layoutNestingLevel_(0),
  115. layoutMinSize_(0),
  116. position_(IntVector2::ZERO),
  117. size_(IntVector2::ZERO),
  118. minSize_(IntVector2::ZERO),
  119. maxSize_(M_MAX_INT, M_MAX_INT),
  120. childOffset_(IntVector2::ZERO),
  121. horizontalAlignment_(HA_LEFT),
  122. verticalAlignment_(VA_TOP),
  123. opacity_(1.0f),
  124. positionDirty_(true),
  125. opacityDirty_(true),
  126. derivedColorDirty_(true),
  127. sortOrderDirty_(false),
  128. colorGradient_(false)
  129. {
  130. }
  131. UIElement::~UIElement()
  132. {
  133. // If child elements have outside references, detach them
  134. while (children_.Size())
  135. {
  136. const SharedPtr<UIElement>& element = children_.Back();
  137. if (element.Refs() > 1)
  138. {
  139. element->parent_ = 0;
  140. element->MarkDirty();
  141. }
  142. children_.Pop();
  143. }
  144. }
  145. void UIElement::RegisterObject(Context* context)
  146. {
  147. context->RegisterFactory<UIElement>();
  148. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String(), AM_FILE);
  149. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  150. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  151. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  152. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2::ZERO, AM_FILE);
  153. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  154. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  155. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  156. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  157. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  158. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  159. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  160. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  161. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  162. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Active", IsActive, SetActive, bool, false, AM_FILE);
  163. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  167. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  168. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  169. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  170. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  171. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  172. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  173. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE);
  174. }
  175. void UIElement::ApplyAttributes()
  176. {
  177. colorGradient_ = false;
  178. derivedColorDirty_ = true;
  179. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  180. {
  181. if (color_[i] != color_[0])
  182. colorGradient_ = true;
  183. }
  184. }
  185. bool UIElement::LoadXML(const XMLElement& source)
  186. {
  187. return LoadXML(source, 0);
  188. }
  189. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  190. {
  191. // Apply the style first, but only for non-internal elements
  192. if (!internal_ && styleFile)
  193. {
  194. // Use style override if defined, otherwise type name
  195. String styleName = source.GetAttribute("style");
  196. if (styleName.Empty())
  197. styleName = GetTypeName();
  198. SetStyle(styleFile, styleName);
  199. }
  200. // Then load rest of the attributes from the source
  201. if (!Serializable::LoadXML(source))
  202. return false;
  203. unsigned nextInternalChild = 0;
  204. // Load child elements. Internal elements are not to be created as they already exist
  205. XMLElement childElem = source.GetChild("element");
  206. while (childElem)
  207. {
  208. bool internalElem = childElem.GetBool("internal");
  209. String typeName = childElem.GetAttribute("type");
  210. if (typeName.Empty())
  211. typeName = "UIElement";
  212. UIElement* child = 0;
  213. if (!internalElem)
  214. child = CreateChild(ShortStringHash(typeName));
  215. else
  216. {
  217. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  218. {
  219. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  220. {
  221. child = children_[i];
  222. nextInternalChild = i + 1;
  223. break;
  224. }
  225. }
  226. if (!child)
  227. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  228. }
  229. if (child)
  230. {
  231. if (!child->LoadXML(childElem, styleFile))
  232. return false;
  233. }
  234. childElem = childElem.GetNext("element");
  235. }
  236. ApplyAttributes();
  237. return true;
  238. }
  239. bool UIElement::SaveXML(XMLElement& dest)
  240. {
  241. // Write type and internal flag
  242. if (!dest.SetString("type", GetTypeName()))
  243. return false;
  244. if (internal_)
  245. {
  246. if (!dest.SetBool("internal", internal_))
  247. return false;
  248. }
  249. // Write attributes
  250. if (!Serializable::SaveXML(dest))
  251. return false;
  252. // Write child elements
  253. for (unsigned i = 0; i < children_.Size(); ++i)
  254. {
  255. UIElement* element = children_[i];
  256. XMLElement childElem = dest.CreateChild("element");
  257. if (!element->SaveXML(childElem))
  258. return false;
  259. }
  260. return true;
  261. }
  262. void UIElement::Update(float timeStep)
  263. {
  264. }
  265. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  266. {
  267. // Reset hovering for next frame
  268. hovering_ = false;
  269. }
  270. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  271. {
  272. hovering_ = true;
  273. }
  274. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  275. {
  276. }
  277. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  278. {
  279. }
  280. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  281. {
  282. }
  283. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  284. {
  285. }
  286. bool UIElement::OnDragDropTest(UIElement* source)
  287. {
  288. return true;
  289. }
  290. bool UIElement::OnDragDropFinish(UIElement* source)
  291. {
  292. return true;
  293. }
  294. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  295. {
  296. }
  297. void UIElement::OnKey(int key, int buttons, int qualifiers)
  298. {
  299. }
  300. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  301. {
  302. }
  303. void UIElement::OnResize()
  304. {
  305. }
  306. bool UIElement::LoadXML(Deserializer& source)
  307. {
  308. SharedPtr<XMLFile> xml(new XMLFile(context_));
  309. if (!xml->Load(source))
  310. return false;
  311. return LoadXML(xml->GetRoot());
  312. }
  313. bool UIElement::SaveXML(Serializer& dest)
  314. {
  315. SharedPtr<XMLFile> xml(new XMLFile(context_));
  316. XMLElement rootElem = xml->CreateRoot("element");
  317. if (!SaveXML(rootElem))
  318. return false;
  319. return xml->Save(dest);
  320. }
  321. void UIElement::SetName(const String& name)
  322. {
  323. name_ = name;
  324. }
  325. void UIElement::SetPosition(const IntVector2& position)
  326. {
  327. if (position != position_)
  328. {
  329. position_ = position;
  330. MarkDirty();
  331. }
  332. }
  333. void UIElement::SetPosition(int x, int y)
  334. {
  335. SetPosition(IntVector2(x, y));
  336. }
  337. void UIElement::SetSize(const IntVector2& size)
  338. {
  339. ++resizeNestingLevel_;
  340. IntVector2 validatedSize;
  341. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  342. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  343. if (validatedSize != size_)
  344. {
  345. size_ = validatedSize;
  346. if (resizeNestingLevel_ == 1)
  347. {
  348. // Check if parent element's layout needs to be updated first
  349. if (parent_)
  350. parent_->UpdateLayout();
  351. MarkDirty();
  352. OnResize();
  353. UpdateLayout();
  354. using namespace Resized;
  355. VariantMap eventData;
  356. eventData[P_ELEMENT] = (void*)this;
  357. eventData[P_WIDTH] = size_.x_;
  358. eventData[P_HEIGHT] = size_.y_;
  359. SendEvent(E_RESIZED, eventData);
  360. }
  361. }
  362. --resizeNestingLevel_;
  363. }
  364. void UIElement::SetSize(int width, int height)
  365. {
  366. SetSize(IntVector2(width, height));
  367. }
  368. void UIElement::SetWidth(int width)
  369. {
  370. SetSize(IntVector2(width, size_.y_));
  371. }
  372. void UIElement::SetHeight(int height)
  373. {
  374. SetSize(IntVector2(size_.x_, height));
  375. }
  376. void UIElement::SetMinSize(const IntVector2& minSize)
  377. {
  378. minSize_.x_ = Max(minSize.x_, 0);
  379. minSize_.y_ = Max(minSize.y_, 0);
  380. SetSize(size_);
  381. }
  382. void UIElement::SetMinSize(int width, int height)
  383. {
  384. SetMinSize(IntVector2(width, height));
  385. }
  386. void UIElement::SetMinWidth(int width)
  387. {
  388. SetMinSize(IntVector2(width, minSize_.y_));
  389. }
  390. void UIElement::SetMinHeight(int height)
  391. {
  392. SetMinSize(IntVector2(minSize_.x_, height));
  393. }
  394. void UIElement::SetMaxSize(const IntVector2& maxSize)
  395. {
  396. maxSize_.x_ = Max(maxSize.x_, 0);
  397. maxSize_.y_ = Max(maxSize.y_, 0);
  398. SetSize(size_);
  399. }
  400. void UIElement::SetMaxSize(int width, int height)
  401. {
  402. SetMaxSize(IntVector2(width, height));
  403. }
  404. void UIElement::SetMaxWidth(int width)
  405. {
  406. SetMaxSize(IntVector2(width, maxSize_.y_));
  407. }
  408. void UIElement::SetMaxHeight(int height)
  409. {
  410. SetMaxSize(IntVector2(maxSize_.x_, height));
  411. }
  412. void UIElement::SetFixedSize(const IntVector2& size)
  413. {
  414. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  415. SetSize(size);
  416. }
  417. void UIElement::SetFixedSize(int width, int height)
  418. {
  419. SetFixedSize(IntVector2(width, height));
  420. }
  421. void UIElement::SetFixedWidth(int width)
  422. {
  423. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  424. SetWidth(width);
  425. }
  426. void UIElement::SetFixedHeight(int height)
  427. {
  428. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  429. SetHeight(height);
  430. }
  431. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  432. {
  433. horizontalAlignment_ = hAlign;
  434. verticalAlignment_ = vAlign;
  435. MarkDirty();
  436. }
  437. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  438. {
  439. horizontalAlignment_ = align;
  440. MarkDirty();
  441. }
  442. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  443. {
  444. verticalAlignment_ = align;
  445. MarkDirty();
  446. }
  447. void UIElement::SetClipBorder(const IntRect& rect)
  448. {
  449. clipBorder_.left_ = Max(rect.left_, 0);
  450. clipBorder_.top_ = Max(rect.top_, 0);
  451. clipBorder_.right_ = Max(rect.right_, 0);
  452. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  453. }
  454. void UIElement::SetColor(const Color& color)
  455. {
  456. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  457. color_[i] = color;
  458. colorGradient_ = false;
  459. derivedColorDirty_ = true;
  460. }
  461. void UIElement::SetColor(Corner corner, const Color& color)
  462. {
  463. color_[corner] = color;
  464. colorGradient_ = false;
  465. derivedColorDirty_ = true;
  466. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  467. {
  468. if (i != corner && color_[i] != color_[corner])
  469. colorGradient_ = true;
  470. }
  471. }
  472. void UIElement::SetPriority(int priority)
  473. {
  474. priority_ = priority;
  475. if (parent_)
  476. parent_->sortOrderDirty_ = true;
  477. }
  478. void UIElement::SetOpacity(float opacity)
  479. {
  480. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  481. MarkDirty();
  482. }
  483. void UIElement::SetBringToFront(bool enable)
  484. {
  485. bringToFront_ = enable;
  486. }
  487. void UIElement::SetBringToBack(bool enable)
  488. {
  489. bringToBack_ = enable;
  490. }
  491. void UIElement::SetClipChildren(bool enable)
  492. {
  493. clipChildren_ = enable;
  494. }
  495. void UIElement::SetSortChildren(bool enable)
  496. {
  497. if (!sortChildren_ && enable)
  498. sortOrderDirty_ = true;
  499. sortChildren_ = enable;
  500. }
  501. void UIElement::SetActive(bool enable)
  502. {
  503. active_ = enable;
  504. }
  505. void UIElement::SetFocusMode(FocusMode mode)
  506. {
  507. focusMode_ = mode;
  508. }
  509. void UIElement::SetFocus(bool enable)
  510. {
  511. if (focusMode_ < FM_FOCUSABLE)
  512. enable = false;
  513. UI* ui = GetSubsystem<UI>();
  514. if (!ui)
  515. return;
  516. if (enable)
  517. {
  518. if (ui->GetFocusElement() != this)
  519. ui->SetFocusElement(this);
  520. }
  521. else
  522. {
  523. if (ui->GetFocusElement() == this)
  524. ui->SetFocusElement(0);
  525. }
  526. }
  527. void UIElement::SetSelected(bool enable)
  528. {
  529. selected_ = enable;
  530. }
  531. void UIElement::SetVisible(bool enable)
  532. {
  533. if (enable != visible_)
  534. {
  535. visible_ = enable;
  536. // Parent's layout may change as a result of visibility change
  537. if (parent_)
  538. parent_->UpdateLayout();
  539. using namespace VisibleChanged;
  540. VariantMap eventData;
  541. eventData[P_ELEMENT] = (void*)this;
  542. eventData[P_VISIBLE] = visible_;
  543. SendEvent(E_VISIBLECHANGED, eventData);
  544. }
  545. }
  546. void UIElement::SetDragDropMode(unsigned mode)
  547. {
  548. dragDropMode_ = mode;
  549. }
  550. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  551. {
  552. if (!file)
  553. return;
  554. XMLElement rootElem = file->GetRoot();
  555. XMLElement childElem = rootElem.GetChild("element");
  556. while (childElem)
  557. {
  558. if (typeName == childElem.GetAttribute("type"))
  559. {
  560. SetStyle(childElem);
  561. return;
  562. }
  563. childElem = childElem.GetNext("element");
  564. }
  565. }
  566. void UIElement::SetStyle(const XMLElement& element)
  567. {
  568. LoadXML(element);
  569. }
  570. void UIElement::SetStyleAuto(XMLFile* file)
  571. {
  572. SetStyle(file, GetTypeName());
  573. }
  574. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  575. {
  576. layoutMode_ = mode;
  577. layoutSpacing_ = Max(spacing, 0);
  578. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  579. UpdateLayout();
  580. }
  581. void UIElement::SetLayoutMode(LayoutMode mode)
  582. {
  583. layoutMode_ = mode;
  584. UpdateLayout();
  585. }
  586. void UIElement::SetLayoutSpacing(int spacing)
  587. {
  588. layoutSpacing_ = Max(spacing, 0);
  589. UpdateLayout();
  590. }
  591. void UIElement::SetLayoutBorder(const IntRect& border)
  592. {
  593. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  594. UpdateLayout();
  595. }
  596. void UIElement::UpdateLayout()
  597. {
  598. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  599. return;
  600. // Prevent further updates while this update happens
  601. DisableLayoutUpdate();
  602. PODVector<int> positions;
  603. PODVector<int> sizes;
  604. PODVector<int> minSizes;
  605. PODVector<int> maxSizes;
  606. if (layoutMode_ == LM_HORIZONTAL)
  607. {
  608. int minChildHeight = 0;
  609. for (unsigned i = 0; i < children_.Size(); ++i)
  610. {
  611. if (!children_[i]->IsVisible())
  612. continue;
  613. positions.Push(0);
  614. sizes.Push(children_[i]->GetWidth());
  615. minSizes.Push(children_[i]->GetMinWidth());
  616. maxSizes.Push(children_[i]->GetMaxWidth());
  617. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  618. }
  619. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  620. layoutSpacing_);
  621. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  622. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  623. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  624. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  625. // Respect fixed size if already set
  626. if (minSize_.x_ != maxSize_.x_)
  627. minSize_.x_ = minWidth;
  628. if (minSize_.y_ != maxSize_.y_)
  629. minSize_.y_ = minHeight;
  630. SetSize(width, height);
  631. // Validate the size before resizing child elements, in case of min/max limits
  632. width = size_.x_;
  633. height = size_.y_;
  634. unsigned j = 0;
  635. for (unsigned i = 0; i < children_.Size(); ++i)
  636. {
  637. if (!children_[i]->IsVisible())
  638. continue;
  639. children_[i]->SetHorizontalAlignment(HA_LEFT);
  640. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  641. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  642. ++j;
  643. }
  644. }
  645. if (layoutMode_ == LM_VERTICAL)
  646. {
  647. int minChildWidth = 0;
  648. for (unsigned i = 0; i < children_.Size(); ++i)
  649. {
  650. if (!children_[i]->IsVisible())
  651. continue;
  652. positions.Push(0);
  653. sizes.Push(children_[i]->GetHeight());
  654. minSizes.Push(children_[i]->GetMinHeight());
  655. maxSizes.Push(children_[i]->GetMaxHeight());
  656. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  657. }
  658. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  659. layoutSpacing_);
  660. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  661. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  662. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  663. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  664. if (minSize_.x_ != maxSize_.x_)
  665. minSize_.x_ = minWidth;
  666. if (minSize_.y_ != maxSize_.y_)
  667. minSize_.y_ = minHeight;
  668. SetSize(width, height);
  669. width = size_.x_;
  670. height = size_.y_;
  671. unsigned j = 0;
  672. for (unsigned i = 0; i < children_.Size(); ++i)
  673. {
  674. if (!children_[i]->IsVisible())
  675. continue;
  676. children_[i]->SetVerticalAlignment(VA_TOP);
  677. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  678. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  679. ++j;
  680. }
  681. }
  682. EnableLayoutUpdate();
  683. }
  684. void UIElement::DisableLayoutUpdate()
  685. {
  686. ++layoutNestingLevel_;
  687. }
  688. void UIElement::EnableLayoutUpdate()
  689. {
  690. --layoutNestingLevel_;
  691. }
  692. void UIElement::BringToFront()
  693. {
  694. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  695. UIElement* root = GetRoot();
  696. UIElement* ptr = this;
  697. while (ptr && ptr->GetParent() != root)
  698. ptr = ptr->GetParent();
  699. if (!ptr || !ptr->GetBringToFront())
  700. return;
  701. // Get the highest priority used by all other top level elements, assign that to the new front element
  702. // and decrease others' priority where necessary. However, take into account only active (enabled)
  703. // elements and those which have the BringToBack flag set
  704. HashSet<int> usedPriorities;
  705. int maxPriority = M_MIN_INT;
  706. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  707. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  708. {
  709. UIElement* other = *i;
  710. if (other->IsActive() && other->bringToBack_ && other != ptr)
  711. {
  712. int priority = other->GetPriority();
  713. usedPriorities.Insert(priority);
  714. maxPriority = Max(priority, maxPriority);
  715. }
  716. }
  717. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  718. {
  719. ptr->SetPriority(maxPriority);
  720. int minPriority = maxPriority;
  721. while (usedPriorities.Contains(minPriority))
  722. --minPriority;
  723. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  724. {
  725. UIElement* other = *i;
  726. int priority = other->GetPriority();
  727. if (other->IsActive() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  728. other->SetPriority(priority - 1);
  729. }
  730. }
  731. }
  732. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name)
  733. {
  734. // Check that creation succeeds and that the object in fact is a UI element
  735. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  736. if (!newElement)
  737. {
  738. LOGERROR("Could not create unknown UI element type " + type.ToString());
  739. return 0;
  740. }
  741. newElement->SetName(name);
  742. AddChild(newElement);
  743. return newElement;
  744. }
  745. void UIElement::AddChild(UIElement* element)
  746. {
  747. InsertChild(children_.Size(), element);
  748. }
  749. void UIElement::InsertChild(unsigned index, UIElement* element)
  750. {
  751. // Check for illegal or redundant parent assignment
  752. if (!element || element == this || element->parent_ == this)
  753. return;
  754. // Check for possible cyclic parent assignment
  755. UIElement* parent = parent_;
  756. while (parent)
  757. {
  758. if (parent == element)
  759. return;
  760. parent = parent->parent_;
  761. }
  762. // Add first, then remove from old parent, to ensure the element does not get deleted
  763. if (index >= children_.Size())
  764. children_.Push(SharedPtr<UIElement>(element));
  765. else
  766. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  767. if (element->parent_)
  768. element->parent_->RemoveChild(element);
  769. if (sortChildren_)
  770. sortOrderDirty_ = true;
  771. element->parent_ = this;
  772. element->MarkDirty();
  773. UpdateLayout();
  774. }
  775. void UIElement::RemoveChild(UIElement* element)
  776. {
  777. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  778. {
  779. if (*i == element)
  780. {
  781. element->parent_ = 0;
  782. element->MarkDirty();
  783. children_.Erase(i);
  784. UpdateLayout();
  785. return;
  786. }
  787. }
  788. }
  789. void UIElement::RemoveAllChildren()
  790. {
  791. while (children_.Size())
  792. {
  793. const SharedPtr<UIElement>& element = children_.Back();
  794. element->parent_ = 0;
  795. element->MarkDirty();
  796. children_.Pop();
  797. }
  798. }
  799. void UIElement::Remove()
  800. {
  801. if (parent_)
  802. parent_->RemoveChild(this);
  803. }
  804. void UIElement::SetParent(UIElement* parent)
  805. {
  806. if (parent)
  807. parent->AddChild(this);
  808. }
  809. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  810. {
  811. vars_[key] = value;
  812. }
  813. void UIElement::SetInternal(bool enable)
  814. {
  815. internal_ = enable;
  816. }
  817. IntVector2 UIElement::GetScreenPosition()
  818. {
  819. if (positionDirty_)
  820. {
  821. IntVector2 pos = position_;
  822. const UIElement* parent = parent_;
  823. const UIElement* current = this;
  824. while (parent)
  825. {
  826. switch (current->horizontalAlignment_)
  827. {
  828. case HA_LEFT:
  829. pos.x_ += parent->position_.x_;
  830. break;
  831. case HA_CENTER:
  832. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  833. break;
  834. case HA_RIGHT:
  835. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  836. break;
  837. }
  838. switch (current->verticalAlignment_)
  839. {
  840. case VA_TOP:
  841. pos.y_ += parent->position_.y_;
  842. break;
  843. case VA_CENTER:
  844. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  845. break;
  846. case VA_BOTTOM:
  847. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  848. break;
  849. }
  850. pos += parent->childOffset_;
  851. current = parent;
  852. parent = parent->parent_;
  853. }
  854. screenPosition_ = pos;
  855. positionDirty_ = false;
  856. }
  857. return screenPosition_;
  858. }
  859. float UIElement::GetDerivedOpacity()
  860. {
  861. if (opacityDirty_)
  862. {
  863. float opacity = opacity_;
  864. const UIElement* parent = parent_;
  865. while (parent)
  866. {
  867. opacity *= parent->opacity_;
  868. parent = parent->parent_;
  869. }
  870. derivedOpacity_ = opacity;
  871. opacityDirty_ = false;
  872. }
  873. return derivedOpacity_;
  874. }
  875. bool UIElement::HasFocus() const
  876. {
  877. UI* ui = GetSubsystem<UI>();
  878. if (!ui)
  879. return false;
  880. else
  881. return ui->GetFocusElement() == this;
  882. }
  883. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  884. {
  885. dest.Clear();
  886. if (!recursive)
  887. {
  888. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  889. dest.Push(*i);
  890. }
  891. else
  892. GetChildrenRecursive(dest);
  893. }
  894. unsigned UIElement::GetNumChildren(bool recursive) const
  895. {
  896. if (!recursive)
  897. return children_.Size();
  898. else
  899. {
  900. unsigned allChildren = children_.Size();
  901. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  902. allChildren += (*i)->GetNumChildren(true);
  903. return allChildren;
  904. }
  905. }
  906. UIElement* UIElement::GetChild(unsigned index) const
  907. {
  908. return index < children_.Size() ? children_[index] : (UIElement*)0;
  909. }
  910. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  911. {
  912. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  913. {
  914. if ((*i)->name_ == name)
  915. return *i;
  916. if (recursive)
  917. {
  918. UIElement* element = (*i)->GetChild(name, true);
  919. if (element)
  920. return element;
  921. }
  922. }
  923. return 0;
  924. }
  925. UIElement* UIElement::GetRoot() const
  926. {
  927. UIElement* root = parent_;
  928. if (!root)
  929. return 0;
  930. while (root->GetParent())
  931. root = root->GetParent();
  932. return root;
  933. }
  934. unsigned UIElement::GetUIntColor()
  935. {
  936. if (derivedColorDirty_)
  937. {
  938. Color color = color_[C_TOPLEFT];
  939. color.a_ *= GetDerivedOpacity();
  940. uintColor_ = color.ToUInt();
  941. derivedColorDirty_ = false;
  942. }
  943. return uintColor_;
  944. }
  945. const Variant& UIElement::GetVar(ShortStringHash key) const
  946. {
  947. VariantMap::ConstIterator i = vars_.Find(key);
  948. if (i != vars_.End())
  949. return i->second_;
  950. else
  951. return Variant::EMPTY;
  952. }
  953. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  954. {
  955. return screenPosition - GetScreenPosition();
  956. }
  957. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  958. {
  959. return position + GetScreenPosition();
  960. }
  961. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  962. {
  963. if (isScreen)
  964. position = ScreenToElement(position);
  965. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  966. }
  967. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  968. {
  969. // If child elements are clipped, no need to expand the rect
  970. if (clipChildren_)
  971. return IsInside(position, isScreen);
  972. if (!isScreen)
  973. position = ElementToScreen(position);
  974. IntRect combined = GetCombinedScreenRect();
  975. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  976. position.y_ < combined.bottom_;
  977. }
  978. IntRect UIElement::GetCombinedScreenRect()
  979. {
  980. IntVector2 screenPosition(GetScreenPosition());
  981. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  982. if (!clipChildren_)
  983. {
  984. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  985. {
  986. IntVector2 childPos = (*i)->GetScreenPosition();
  987. const IntVector2& childSize = (*i)->GetSize();
  988. if (childPos.x_ < combined.left_)
  989. combined.left_ = childPos.x_;
  990. if (childPos.y_ < combined.top_)
  991. combined.top_ = childPos.y_;
  992. if (childPos.x_ + childSize.x_ > combined.right_)
  993. combined.right_ = childPos.x_ + childSize.x_;
  994. if (childPos.y_ + childSize.y_ > combined.bottom_)
  995. combined.bottom_ = childPos.y_ + childSize.y_;
  996. }
  997. }
  998. return combined;
  999. }
  1000. void UIElement::SortChildren()
  1001. {
  1002. if (sortChildren_ && sortOrderDirty_)
  1003. {
  1004. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1005. sortOrderDirty_ = false;
  1006. }
  1007. }
  1008. void UIElement::SetChildOffset(const IntVector2& offset)
  1009. {
  1010. if (offset != childOffset_)
  1011. {
  1012. childOffset_ = offset;
  1013. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1014. (*i)->MarkDirty();
  1015. }
  1016. }
  1017. void UIElement::SetHovering(bool enable)
  1018. {
  1019. hovering_ = enable;
  1020. }
  1021. void UIElement::SetTempVisible(bool enable)
  1022. {
  1023. visible_ = enable;
  1024. }
  1025. void UIElement::AdjustScissor(IntRect& currentScissor)
  1026. {
  1027. if (clipChildren_)
  1028. {
  1029. IntVector2 screenPos = GetScreenPosition();
  1030. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1031. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1032. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1033. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1034. if (currentScissor.right_ < currentScissor.left_)
  1035. currentScissor.right_ = currentScissor.left_;
  1036. if (currentScissor.bottom_ < currentScissor.top_)
  1037. currentScissor.bottom_ = currentScissor.top_;
  1038. }
  1039. }
  1040. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  1041. currentScissor)
  1042. {
  1043. unsigned initialSize = quads.Size();
  1044. GetBatches(batches, quads, currentScissor);
  1045. for (unsigned i = initialSize; i < quads.Size(); ++i)
  1046. {
  1047. quads[i].left_ += offset.x_;
  1048. quads[i].top_ += offset.y_;
  1049. quads[i].right_ += offset.x_;
  1050. quads[i].bottom_ += offset.y_;
  1051. }
  1052. AdjustScissor(currentScissor);
  1053. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1054. {
  1055. if ((*i)->IsVisible())
  1056. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  1057. }
  1058. }
  1059. void UIElement::MarkDirty()
  1060. {
  1061. positionDirty_ = true;
  1062. opacityDirty_ = true;
  1063. derivedColorDirty_ = true;
  1064. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1065. (*i)->MarkDirty();
  1066. }
  1067. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1068. {
  1069. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1070. {
  1071. UIElement* element = *i;
  1072. dest.Push(element);
  1073. if (!element->children_.Empty())
  1074. element->GetChildrenRecursive(dest);
  1075. }
  1076. }
  1077. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1078. {
  1079. int width = begin + end;
  1080. for (unsigned i = 0; i < sizes.Size(); ++i)
  1081. {
  1082. // If calculating maximum size, and the default is specified, do not overflow it
  1083. if (sizes[i] == M_MAX_INT)
  1084. return M_MAX_INT;
  1085. width += sizes[i];
  1086. if (i < sizes.Size() - 1)
  1087. width += spacing;
  1088. }
  1089. return width;
  1090. }
  1091. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1092. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1093. {
  1094. int numChildren = sizes.Size();
  1095. if (!numChildren)
  1096. return;
  1097. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1098. if (targetTotalSize < 0)
  1099. targetTotalSize = 0;
  1100. int targetChildSize = targetTotalSize / numChildren;
  1101. int remainder = targetTotalSize % numChildren;
  1102. float add = (float)remainder / numChildren;
  1103. float acc = 0.0f;
  1104. // Initial pass
  1105. for (int i = 0; i < numChildren; ++i)
  1106. {
  1107. int targetSize = targetChildSize;
  1108. if (remainder)
  1109. {
  1110. acc += add;
  1111. if (acc >= 0.5f)
  1112. {
  1113. acc -= 1.0f;
  1114. ++targetSize;
  1115. --remainder;
  1116. }
  1117. }
  1118. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1119. }
  1120. // Error correction passes
  1121. for (;;)
  1122. {
  1123. int actualTotalSize = 0;
  1124. for (int i = 0; i < numChildren; ++i)
  1125. actualTotalSize += sizes[i];
  1126. int error = targetTotalSize - actualTotalSize;
  1127. // Break if no error
  1128. if (!error)
  1129. break;
  1130. // Check which of the children can be resized to correct the error. If none, must break
  1131. PODVector<unsigned> resizable;
  1132. for (int i = 0; i < numChildren; ++i)
  1133. {
  1134. if (error < 0 && sizes[i] > minSizes[i])
  1135. resizable.Push(i);
  1136. else if (error > 0 && sizes[i] < maxSizes[i])
  1137. resizable.Push(i);
  1138. }
  1139. if (resizable.Empty())
  1140. break;
  1141. int numResizable = resizable.Size();
  1142. int errorPerChild = error / numResizable;
  1143. remainder = (abs(error)) % numResizable;
  1144. add = (float)remainder / numResizable;
  1145. acc = 0.0f;
  1146. for (int i = 0; i < numResizable; ++i)
  1147. {
  1148. unsigned index = resizable[i];
  1149. int targetSize = sizes[index] + errorPerChild;
  1150. if (remainder)
  1151. {
  1152. acc += add;
  1153. if (acc >= 0.5f)
  1154. {
  1155. acc -= 1.0f;
  1156. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1157. --remainder;
  1158. }
  1159. }
  1160. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1161. }
  1162. }
  1163. // Calculate final positions and store the minimum child element size
  1164. layoutMinSize_ = M_MAX_INT;
  1165. int position = begin;
  1166. for (int i = 0; i < numChildren; ++i)
  1167. {
  1168. positions[i] = position;
  1169. position += sizes[i];
  1170. position += spacing;
  1171. if (sizes[i] < layoutMinSize_)
  1172. layoutMinSize_ = sizes[i];
  1173. }
  1174. }
  1175. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1176. {
  1177. IntVector2 ret(IntVector2::ZERO);
  1178. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1179. switch (ha)
  1180. {
  1181. case HA_LEFT:
  1182. ret.x_ = layoutBorder_.left_;
  1183. break;
  1184. case HA_RIGHT:
  1185. ret.x_ = -layoutBorder_.right_;
  1186. break;
  1187. }
  1188. VerticalAlignment va = child->GetVerticalAlignment();
  1189. switch (va)
  1190. {
  1191. case VA_TOP:
  1192. ret.y_ = layoutBorder_.top_;
  1193. break;
  1194. case VA_BOTTOM:
  1195. ret.y_ = -layoutBorder_.bottom_;
  1196. break;
  1197. }
  1198. return ret;
  1199. }
  1200. }