UI.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. //
  2. // Copyright (c) 2008-2022 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/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Container/Sort.h"
  27. #include "../Graphics/Graphics.h"
  28. #include "../Graphics/GraphicsEvents.h"
  29. #include "../Graphics/Shader.h"
  30. #include "../Graphics/ShaderVariation.h"
  31. #include "../Graphics/Texture2D.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../Graphics/Octree.h"
  34. #include "../Graphics/Viewport.h"
  35. #include "../Graphics/Camera.h"
  36. #include "../Graphics/Technique.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Input/Input.h"
  39. #include "../Input/InputEvents.h"
  40. #include "../IO/Log.h"
  41. #include "../Math/Matrix3x4.h"
  42. #include "../Resource/ResourceCache.h"
  43. #include "../UI/CheckBox.h"
  44. #include "../UI/Cursor.h"
  45. #include "../UI/DropDownList.h"
  46. #include "../UI/FileSelector.h"
  47. #include "../UI/Font.h"
  48. #include "../UI/LineEdit.h"
  49. #include "../UI/ListView.h"
  50. #include "../UI/MessageBox.h"
  51. #include "../UI/ProgressBar.h"
  52. #include "../UI/ScrollBar.h"
  53. #include "../UI/Slider.h"
  54. #include "../UI/Sprite.h"
  55. #include "../UI/Text.h"
  56. #include "../UI/Text3D.h"
  57. #include "../UI/ToolTip.h"
  58. #include "../UI/UI.h"
  59. #include "../UI/UIEvents.h"
  60. #include "../UI/Window.h"
  61. #include "../UI/View3D.h"
  62. #include "../UI/UIComponent.h"
  63. #include <cassert>
  64. #include <SDL/SDL.h>
  65. #include "../DebugNew.h"
  66. namespace Urho3D
  67. {
  68. static MouseButton MakeTouchIDMask(int id)
  69. {
  70. return static_cast<MouseButton>(1u << static_cast<MouseButtonFlags::Integer>(id)); // NOLINT(misc-misplaced-widening-cast)
  71. }
  72. StringHash VAR_ORIGIN("Origin");
  73. const StringHash VAR_ORIGINAL_PARENT("OriginalParent");
  74. const StringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex");
  75. const StringHash VAR_PARENT_CHANGED("ParentChanged");
  76. const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f;
  77. const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f;
  78. const float DEFAULT_TOOLTIP_DELAY = 0.5f;
  79. const int DEFAULT_DRAGBEGIN_DISTANCE = 5;
  80. const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048;
  81. const char* UI_CATEGORY = "UI";
  82. UI::UI(Context* context) :
  83. Object(context),
  84. rootElement_(new UIElement(context)),
  85. rootModalElement_(new UIElement(context)),
  86. doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL),
  87. dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL),
  88. defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY),
  89. dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE),
  90. mouseButtons_(0),
  91. lastMouseButtons_(0),
  92. maxDoubleClickDist_(M_LARGE_VALUE),
  93. qualifiers_(0),
  94. maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE),
  95. initialized_(false),
  96. usingTouchInput_(false),
  97. #ifdef _WIN32
  98. nonFocusedMouseWheel_(false), // Default MS Windows behaviour
  99. #else
  100. nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
  101. #endif
  102. useSystemClipboard_(false),
  103. #if defined(__ANDROID__) || defined(IOS) || defined(TVOS)
  104. useScreenKeyboard_(true),
  105. #else
  106. useScreenKeyboard_(false),
  107. #endif
  108. useMutableGlyphs_(false),
  109. forceAutoHint_(false),
  110. fontHintLevel_(FONT_HINT_LEVEL_NORMAL),
  111. fontSubpixelThreshold_(12),
  112. fontOversampling_(2),
  113. uiRendered_(false),
  114. nonModalBatchSize_(0),
  115. dragElementsCount_(0),
  116. dragConfirmedCount_(0),
  117. uiScale_(1.0f),
  118. customSize_(IntVector2::ZERO)
  119. {
  120. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  121. rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
  122. // Register UI library object factories
  123. RegisterUILibrary(context_);
  124. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(UI, HandleScreenMode));
  125. SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(UI, HandleMouseButtonDown));
  126. SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(UI, HandleMouseButtonUp));
  127. SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(UI, HandleMouseMove));
  128. SubscribeToEvent(E_MOUSEWHEEL, URHO3D_HANDLER(UI, HandleMouseWheel));
  129. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(UI, HandleTouchBegin));
  130. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(UI, HandleTouchEnd));
  131. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(UI, HandleTouchMove));
  132. SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(UI, HandleKeyDown));
  133. SubscribeToEvent(E_TEXTINPUT, URHO3D_HANDLER(UI, HandleTextInput));
  134. SubscribeToEvent(E_DROPFILE, URHO3D_HANDLER(UI, HandleDropFile));
  135. // Try to initialize right now, but skip if screen mode is not yet set
  136. Initialize();
  137. }
  138. UI::~UI() = default;
  139. void UI::SetCursor(Cursor* cursor)
  140. {
  141. if (cursor_ == cursor)
  142. return;
  143. // Remove old cursor (if any) and set new
  144. if (cursor_)
  145. {
  146. rootElement_->RemoveChild(cursor_);
  147. cursor_.Reset();
  148. }
  149. if (cursor)
  150. {
  151. rootElement_->AddChild(cursor);
  152. cursor_ = cursor;
  153. IntVector2 pos = cursor_->GetPosition();
  154. const IntVector2& rootSize = rootElement_->GetSize();
  155. const IntVector2& rootPos = rootElement_->GetPosition();
  156. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  157. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  158. cursor_->SetPosition(pos);
  159. }
  160. }
  161. void UI::SetFocusElement(UIElement* element, bool byKey)
  162. {
  163. using namespace FocusChanged;
  164. UIElement* originalElement = element;
  165. if (element)
  166. {
  167. // Return if already has focus
  168. if (focusElement_ == element)
  169. return;
  170. // Only allow child elements of the modal element to receive focus
  171. if (HasModalElement())
  172. {
  173. UIElement* topLevel = element->GetParent();
  174. while (topLevel && topLevel->GetParent() != rootElement_)
  175. topLevel = topLevel->GetParent();
  176. if (topLevel) // If parented to non-modal root then ignore
  177. return;
  178. }
  179. // Search for an element in the hierarchy that can alter focus. If none found, exit
  180. element = GetFocusableElement(element);
  181. if (!element)
  182. return;
  183. }
  184. // Remove focus from the old element
  185. if (focusElement_)
  186. {
  187. UIElement* oldFocusElement = focusElement_;
  188. focusElement_.Reset();
  189. VariantMap& focusEventData = GetEventDataMap();
  190. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  191. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  192. }
  193. // Then set focus to the new
  194. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  195. {
  196. focusElement_ = element;
  197. VariantMap& focusEventData = GetEventDataMap();
  198. focusEventData[Focused::P_ELEMENT] = element;
  199. focusEventData[Focused::P_BYKEY] = byKey;
  200. element->SendEvent(E_FOCUSED, focusEventData);
  201. }
  202. VariantMap& eventData = GetEventDataMap();
  203. eventData[P_CLICKEDELEMENT] = originalElement;
  204. eventData[P_ELEMENT] = element;
  205. SendEvent(E_FOCUSCHANGED, eventData);
  206. }
  207. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  208. {
  209. if (!modalElement)
  210. return false;
  211. // Currently only allow modal window
  212. if (modalElement->GetType() != Window::GetTypeStatic())
  213. return false;
  214. assert(rootModalElement_);
  215. UIElement* currParent = modalElement->GetParent();
  216. if (enable)
  217. {
  218. // Make sure it is not already the child of the root modal element
  219. if (currParent == rootModalElement_)
  220. return false;
  221. // Adopt modal root as parent
  222. modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent);
  223. modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED);
  224. modalElement->SetParent(rootModalElement_);
  225. // If it is a popup element, bring along its top-level parent
  226. auto* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  227. if (originElement)
  228. {
  229. UIElement* element = originElement;
  230. while (element && element->GetParent() != rootElement_)
  231. element = element->GetParent();
  232. if (element)
  233. {
  234. originElement->SetVar(VAR_PARENT_CHANGED, element);
  235. UIElement* oriParent = element->GetParent();
  236. element->SetVar(VAR_ORIGINAL_PARENT, oriParent);
  237. element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED);
  238. element->SetParent(rootModalElement_);
  239. }
  240. }
  241. return true;
  242. }
  243. else
  244. {
  245. // Only the modal element can disable itself
  246. if (currParent != rootModalElement_)
  247. return false;
  248. // Revert back to original parent
  249. modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  250. modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  251. auto& vars = const_cast<VariantMap&>(modalElement->GetVars());
  252. vars.Erase(VAR_ORIGINAL_PARENT);
  253. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  254. // If it is a popup element, revert back its top-level parent
  255. auto* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  256. if (originElement)
  257. {
  258. auto* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
  259. if (element)
  260. {
  261. const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
  262. element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  263. element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  264. vars = const_cast<VariantMap&>(element->GetVars());
  265. vars.Erase(VAR_ORIGINAL_PARENT);
  266. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  267. }
  268. }
  269. return true;
  270. }
  271. }
  272. void UI::Clear()
  273. {
  274. rootElement_->RemoveAllChildren();
  275. rootModalElement_->RemoveAllChildren();
  276. if (cursor_)
  277. rootElement_->AddChild(cursor_);
  278. }
  279. void UI::Update(float timeStep)
  280. {
  281. assert(rootElement_ && rootModalElement_);
  282. URHO3D_PROFILE(UpdateUI);
  283. // Expire hovers
  284. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End(); ++i)
  285. i->second_ = false;
  286. auto* input = GetSubsystem<Input>();
  287. bool mouseGrabbed = input->IsMouseGrabbed();
  288. IntVector2 cursorPos;
  289. bool cursorVisible;
  290. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  291. // Drag begin based on time
  292. if (dragElementsCount_ > 0 && !mouseGrabbed)
  293. {
  294. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  295. {
  296. WeakPtr<UIElement> dragElement = i->first_;
  297. UI::DragData* dragData = i->second_;
  298. if (!dragElement)
  299. {
  300. i = DragElementErase(i);
  301. continue;
  302. }
  303. if (!dragData->dragBeginPending)
  304. {
  305. ++i;
  306. continue;
  307. }
  308. if (dragData->dragBeginTimer.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000))
  309. {
  310. dragData->dragBeginPending = false;
  311. IntVector2 beginSendPos = dragData->dragBeginSumPos / dragData->numDragButtons;
  312. dragConfirmedCount_++;
  313. if (!usingTouchInput_)
  314. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons,
  315. qualifiers_, cursor_);
  316. else
  317. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, QUAL_NONE, nullptr);
  318. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  319. }
  320. ++i;
  321. }
  322. }
  323. // Mouse hover
  324. if (!mouseGrabbed && !input->GetTouchEmulation())
  325. {
  326. if (!usingTouchInput_ && cursorVisible)
  327. ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_);
  328. }
  329. // Touch hover
  330. unsigned numTouches = input->GetNumTouches();
  331. for (unsigned i = 0; i < numTouches; ++i)
  332. {
  333. TouchState* touch = input->GetTouch(i);
  334. IntVector2 touchPos = touch->position_;
  335. touchPos = ConvertSystemToUI(touchPos);
  336. ProcessHover(touchPos, MakeTouchIDMask(touch->touchID_), QUAL_NONE, nullptr);
  337. }
  338. // End hovers that expired without refreshing
  339. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End();)
  340. {
  341. if (i->first_.Expired() || !i->second_)
  342. {
  343. UIElement* element = i->first_;
  344. if (element)
  345. {
  346. using namespace HoverEnd;
  347. VariantMap& eventData = GetEventDataMap();
  348. eventData[P_ELEMENT] = element;
  349. element->SendEvent(E_HOVEREND, eventData);
  350. }
  351. i = hoveredElements_.Erase(i);
  352. }
  353. else
  354. ++i;
  355. }
  356. Update(timeStep, rootElement_);
  357. Update(timeStep, rootModalElement_);
  358. }
  359. void UI::RenderUpdate()
  360. {
  361. assert(rootElement_ && rootModalElement_ && graphics_);
  362. URHO3D_PROFILE(GetUIBatches);
  363. uiRendered_ = false;
  364. // If the OS cursor is visible, do not render the UI's own cursor
  365. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  366. // Get rendering batches from the non-modal UI elements
  367. batches_.Clear();
  368. vertexData_.Clear();
  369. const IntVector2& rootSize = rootElement_->GetSize();
  370. const IntVector2& rootPos = rootElement_->GetPosition();
  371. // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
  372. IntRect currentScissor = IntRect(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
  373. if (rootElement_->IsVisible())
  374. GetBatches(batches_, vertexData_, rootElement_, currentScissor);
  375. // Save the batch size of the non-modal batches for later use
  376. nonModalBatchSize_ = batches_.Size();
  377. // Get rendering batches from the modal UI elements
  378. GetBatches(batches_, vertexData_, rootModalElement_, currentScissor);
  379. // Get batches from the cursor (and its possible children) last to draw it on top of everything
  380. if (cursor_ && cursor_->IsVisible() && !osCursorVisible)
  381. {
  382. currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  383. cursor_->GetBatches(batches_, vertexData_, currentScissor);
  384. GetBatches(batches_, vertexData_, cursor_, currentScissor);
  385. }
  386. // Get batches for UI elements rendered into textures. Each element rendered into texture is treated as root element.
  387. for (auto it = renderToTexture_.Begin(); it != renderToTexture_.End();)
  388. {
  389. RenderToTextureData& data = it->second_;
  390. if (data.rootElement_.Expired())
  391. {
  392. it = renderToTexture_.Erase(it);
  393. continue;
  394. }
  395. if (data.rootElement_->IsEnabled())
  396. {
  397. data.batches_.Clear();
  398. data.vertexData_.Clear();
  399. UIElement* element = data.rootElement_;
  400. const IntVector2& size = element->GetSize();
  401. const IntVector2& pos = element->GetPosition();
  402. // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
  403. IntRect scissor = IntRect(pos.x_, pos.y_, pos.x_ + size.x_, pos.y_ + size.y_);
  404. GetBatches(data.batches_, data.vertexData_, element, scissor);
  405. // UIElement does not have anything to show. Insert dummy batch that will clear the texture.
  406. if (data.batches_.Empty())
  407. {
  408. UIBatch batch(element, BLEND_REPLACE, scissor, nullptr, &data.vertexData_);
  409. batch.SetColor(Color::BLACK);
  410. batch.AddQuad(scissor.left_, scissor.top_, scissor.right_, scissor.bottom_, 0, 0);
  411. data.batches_.Push(batch);
  412. }
  413. }
  414. ++it;
  415. }
  416. }
  417. void UI::Render(bool renderUICommand)
  418. {
  419. URHO3D_PROFILE(RenderUI);
  420. // If the OS cursor is visible, apply its shape now if changed
  421. if (!renderUICommand)
  422. {
  423. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  424. if (cursor_ && osCursorVisible)
  425. cursor_->ApplyOSCursorShape();
  426. }
  427. // Perform the default backbuffer render only if not rendered yet, or additional renders through RenderUI command
  428. if (renderUICommand || !uiRendered_)
  429. {
  430. SetVertexData(vertexBuffer_, vertexData_);
  431. SetVertexData(debugVertexBuffer_, debugVertexData_);
  432. if (!renderUICommand)
  433. graphics_->ResetRenderTargets();
  434. // Render non-modal batches
  435. Render(vertexBuffer_, batches_, 0, nonModalBatchSize_);
  436. // Render debug draw
  437. Render(debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size());
  438. // Render modal batches
  439. Render(vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size());
  440. }
  441. // Render to UIComponent textures. This is skipped when called from the RENDERUI command
  442. if (!renderUICommand)
  443. {
  444. for (auto& item : renderToTexture_)
  445. {
  446. RenderToTextureData& data = item.second_;
  447. if (data.rootElement_->IsEnabled())
  448. {
  449. SetVertexData(data.vertexBuffer_, data.vertexData_);
  450. SetVertexData(data.debugVertexBuffer_, data.debugVertexData_);
  451. RenderSurface* surface = data.texture_->GetRenderSurface();
  452. graphics_->SetDepthStencil(surface->GetLinkedDepthStencil());
  453. graphics_->SetRenderTarget(0, surface);
  454. graphics_->SetViewport(IntRect(0, 0, surface->GetWidth(), surface->GetHeight()));
  455. graphics_->Clear(Urho3D::CLEAR_COLOR);
  456. Render(data.vertexBuffer_, data.batches_, 0, data.batches_.Size());
  457. Render(data.debugVertexBuffer_, data.debugDrawBatches_, 0, data.debugDrawBatches_.Size());
  458. data.debugDrawBatches_.Clear();
  459. data.debugVertexData_.Clear();
  460. }
  461. }
  462. if (renderToTexture_.Size())
  463. graphics_->ResetRenderTargets();
  464. }
  465. // Clear the debug draw batches and data
  466. debugDrawBatches_.Clear();
  467. debugVertexData_.Clear();
  468. uiRendered_ = true;
  469. }
  470. void UI::DebugDraw(UIElement* element)
  471. {
  472. if (element)
  473. {
  474. UIElement* root = element->GetRoot();
  475. if (!root)
  476. root = element;
  477. const IntVector2& rootSize = root->GetSize();
  478. const IntVector2& rootPos = root->GetPosition();
  479. IntRect scissor(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
  480. if (root == rootElement_ || root == rootModalElement_)
  481. element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, scissor);
  482. else
  483. {
  484. for (auto& item : renderToTexture_)
  485. {
  486. RenderToTextureData& data = item.second_;
  487. if (!data.rootElement_.Expired() && data.rootElement_ == root && data.rootElement_->IsEnabled())
  488. {
  489. element->GetDebugDrawBatches(data.debugDrawBatches_, data.debugVertexData_, scissor);
  490. break;
  491. }
  492. }
  493. }
  494. }
  495. }
  496. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  497. {
  498. SharedPtr<XMLFile> xml(new XMLFile(context_));
  499. if (!xml->Load(source))
  500. return SharedPtr<UIElement>();
  501. else
  502. return LoadLayout(xml, styleFile);
  503. }
  504. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  505. {
  506. URHO3D_PROFILE(LoadUILayout);
  507. SharedPtr<UIElement> root;
  508. if (!file)
  509. {
  510. URHO3D_LOGERROR("Null UI layout XML file");
  511. return root;
  512. }
  513. URHO3D_LOGDEBUG("Loading UI layout " + file->GetName());
  514. XMLElement rootElem = file->GetRoot("element");
  515. if (!rootElem)
  516. {
  517. URHO3D_LOGERROR("No root UI element in " + file->GetName());
  518. return root;
  519. }
  520. String typeName = rootElem.GetAttribute("type");
  521. if (typeName.Empty())
  522. typeName = "UIElement";
  523. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  524. if (!root)
  525. {
  526. URHO3D_LOGERROR("Could not create unknown UI element " + typeName);
  527. return root;
  528. }
  529. // Use default style file of the root element if it has one
  530. if (!styleFile)
  531. styleFile = rootElement_->GetDefaultStyle(false);
  532. // Set it as default for later use by children elements
  533. if (styleFile)
  534. root->SetDefaultStyle(styleFile);
  535. root->LoadXML(rootElem, styleFile);
  536. return root;
  537. }
  538. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  539. {
  540. URHO3D_PROFILE(SaveUILayout);
  541. return element && element->SaveXML(dest);
  542. }
  543. void UI::SetClipboardText(const String& text)
  544. {
  545. clipBoard_ = text;
  546. if (useSystemClipboard_)
  547. SDL_SetClipboardText(text.CString());
  548. }
  549. void UI::SetDoubleClickInterval(float interval)
  550. {
  551. doubleClickInterval_ = Max(interval, 0.0f);
  552. }
  553. void UI::SetMaxDoubleClickDistance(float distPixels)
  554. {
  555. maxDoubleClickDist_ = distPixels;
  556. }
  557. void UI::SetDragBeginInterval(float interval)
  558. {
  559. dragBeginInterval_ = Max(interval, 0.0f);
  560. }
  561. void UI::SetDragBeginDistance(int pixels)
  562. {
  563. dragBeginDistance_ = Max(pixels, 0);
  564. }
  565. void UI::SetDefaultToolTipDelay(float delay)
  566. {
  567. defaultToolTipDelay_ = Max(delay, 0.0f);
  568. }
  569. void UI::SetMaxFontTextureSize(int size)
  570. {
  571. if (IsPowerOfTwo((unsigned)size) && size >= FONT_TEXTURE_MIN_SIZE)
  572. {
  573. if (size != maxFontTextureSize_)
  574. {
  575. maxFontTextureSize_ = size;
  576. ReleaseFontFaces();
  577. }
  578. }
  579. }
  580. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  581. {
  582. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  583. }
  584. void UI::SetUseSystemClipboard(bool enable)
  585. {
  586. useSystemClipboard_ = enable;
  587. }
  588. void UI::SetUseScreenKeyboard(bool enable)
  589. {
  590. useScreenKeyboard_ = enable;
  591. }
  592. void UI::SetUseMutableGlyphs(bool enable)
  593. {
  594. if (enable != useMutableGlyphs_)
  595. {
  596. useMutableGlyphs_ = enable;
  597. ReleaseFontFaces();
  598. }
  599. }
  600. void UI::SetForceAutoHint(bool enable)
  601. {
  602. if (enable != forceAutoHint_)
  603. {
  604. forceAutoHint_ = enable;
  605. ReleaseFontFaces();
  606. }
  607. }
  608. void UI::SetFontHintLevel(FontHintLevel level)
  609. {
  610. if (level != fontHintLevel_)
  611. {
  612. fontHintLevel_ = level;
  613. ReleaseFontFaces();
  614. }
  615. }
  616. void UI::SetFontSubpixelThreshold(float threshold)
  617. {
  618. assert(threshold >= 0);
  619. if (threshold != fontSubpixelThreshold_)
  620. {
  621. fontSubpixelThreshold_ = threshold;
  622. ReleaseFontFaces();
  623. }
  624. }
  625. void UI::SetFontOversampling(int oversampling)
  626. {
  627. assert(oversampling >= 1);
  628. oversampling = Clamp(oversampling, 1, 8);
  629. if (oversampling != fontOversampling_)
  630. {
  631. fontOversampling_ = oversampling;
  632. ReleaseFontFaces();
  633. }
  634. }
  635. void UI::SetScale(float scale)
  636. {
  637. uiScale_ = Max(scale, M_EPSILON);
  638. ResizeRootElement();
  639. }
  640. void UI::SetWidth(float width)
  641. {
  642. IntVector2 size = GetEffectiveRootElementSize(false);
  643. SetScale((float)size.x_ / width);
  644. }
  645. void UI::SetHeight(float height)
  646. {
  647. IntVector2 size = GetEffectiveRootElementSize(false);
  648. SetScale((float)size.y_ / height);
  649. }
  650. void UI::SetCustomSize(const IntVector2& size)
  651. {
  652. customSize_ = IntVector2(Max(0, size.x_), Max(0, size.y_));
  653. ResizeRootElement();
  654. }
  655. void UI::SetCustomSize(int width, int height)
  656. {
  657. customSize_ = IntVector2(Max(0, width), Max(0, height));
  658. ResizeRootElement();
  659. }
  660. IntVector2 UI::GetCursorPosition() const
  661. {
  662. if (cursor_)
  663. return cursor_->GetPosition();
  664. return ConvertSystemToUI(GetSubsystem<Input>()->GetMousePosition());
  665. }
  666. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly, IntVector2* elementScreenPosition)
  667. {
  668. UIElement* result = nullptr;
  669. if (HasModalElement())
  670. result = GetElementAt(rootModalElement_, position, enabledOnly);
  671. if (!result)
  672. result = GetElementAt(rootElement_, position, enabledOnly);
  673. // Mouse was not hovering UI element. Check elements rendered on 3D objects.
  674. if (!result && renderToTexture_.Size())
  675. {
  676. for (auto& item : renderToTexture_)
  677. {
  678. RenderToTextureData& data = item.second_;
  679. if (data.rootElement_.Expired() || !data.rootElement_->IsEnabled())
  680. continue;
  681. IntVector2 screenPosition = data.rootElement_->ScreenToElement(position);
  682. if (data.rootElement_->GetCombinedScreenRect().IsInside(screenPosition) == INSIDE)
  683. {
  684. result = GetElementAt(data.rootElement_, screenPosition, enabledOnly);
  685. if (result)
  686. {
  687. if (elementScreenPosition)
  688. *elementScreenPosition = screenPosition;
  689. break;
  690. }
  691. }
  692. }
  693. }
  694. else if (elementScreenPosition)
  695. *elementScreenPosition = position;
  696. return result;
  697. }
  698. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  699. {
  700. return GetElementAt(position, enabledOnly, nullptr);
  701. }
  702. UIElement* UI::GetElementAt(UIElement* root, const IntVector2& position, bool enabledOnly)
  703. {
  704. IntVector2 positionCopy(position);
  705. const IntVector2& rootSize = root->GetSize();
  706. const IntVector2& rootPos = root->GetPosition();
  707. // If position is out of bounds of root element return null.
  708. if (position.x_ < rootPos.x_ || position.x_ > rootPos.x_ + rootSize.x_)
  709. return nullptr;
  710. if (position.y_ < rootPos.y_ || position.y_ > rootPos.y_ + rootSize.y_)
  711. return nullptr;
  712. // If UI is smaller than the screen, wrap if necessary
  713. if (rootSize.x_ > 0 && rootSize.y_ > 0)
  714. {
  715. if (positionCopy.x_ >= rootPos.x_ + rootSize.x_)
  716. positionCopy.x_ = rootPos.x_ + ((positionCopy.x_ - rootPos.x_) % rootSize.x_);
  717. if (positionCopy.y_ >= rootPos.y_ + rootSize.y_)
  718. positionCopy.y_ = rootPos.y_ + ((positionCopy.y_ - rootPos.y_) % rootSize.y_);
  719. }
  720. UIElement* result = nullptr;
  721. GetElementAt(result, root, positionCopy, enabledOnly);
  722. return result;
  723. }
  724. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  725. {
  726. return GetElementAt(IntVector2(x, y), enabledOnly);
  727. }
  728. IntVector2 UI::ConvertSystemToUI(const IntVector2& systemPos) const
  729. {
  730. return VectorFloorToInt(static_cast<Vector2>(systemPos) / GetScale());
  731. }
  732. IntVector2 UI::ConvertUIToSystem(const IntVector2& uiPos) const
  733. {
  734. return VectorFloorToInt(static_cast<Vector2>(uiPos) * GetScale());
  735. }
  736. UIElement* UI::GetFrontElement() const
  737. {
  738. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  739. int maxPriority = M_MIN_INT;
  740. UIElement* front = nullptr;
  741. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  742. {
  743. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  744. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  745. continue;
  746. int priority = rootChildren[i]->GetPriority();
  747. if (priority > maxPriority)
  748. {
  749. maxPriority = priority;
  750. front = rootChildren[i];
  751. }
  752. }
  753. return front;
  754. }
  755. const Vector<UIElement*> UI::GetDragElements()
  756. {
  757. // Do not return the element until drag begin event has actually been posted
  758. if (!dragElementsConfirmed_.Empty())
  759. return dragElementsConfirmed_;
  760. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  761. {
  762. WeakPtr<UIElement> dragElement = i->first_;
  763. UI::DragData* dragData = i->second_;
  764. if (!dragElement)
  765. {
  766. i = DragElementErase(i);
  767. continue;
  768. }
  769. if (!dragData->dragBeginPending)
  770. dragElementsConfirmed_.Push(dragElement);
  771. ++i;
  772. }
  773. return dragElementsConfirmed_;
  774. }
  775. UIElement* UI::GetDragElement(unsigned index)
  776. {
  777. GetDragElements();
  778. if (index >= dragElementsConfirmed_.Size())
  779. return nullptr;
  780. return dragElementsConfirmed_[index];
  781. }
  782. const String& UI::GetClipboardText() const
  783. {
  784. if (useSystemClipboard_)
  785. {
  786. char* text = SDL_GetClipboardText();
  787. clipBoard_ = String(text);
  788. if (text)
  789. SDL_free(text);
  790. }
  791. return clipBoard_;
  792. }
  793. bool UI::HasModalElement() const
  794. {
  795. return rootModalElement_->GetNumChildren() > 0;
  796. }
  797. void UI::Initialize()
  798. {
  799. auto* graphics = GetSubsystem<Graphics>();
  800. if (!graphics || !graphics->IsInitialized())
  801. return;
  802. URHO3D_PROFILE(InitUI);
  803. graphics_ = graphics;
  804. UIBatch::posAdjust = Vector3(Graphics::GetPixelUVOffset(), 0.0f);
  805. // Set initial root element size
  806. ResizeRootElement();
  807. vertexBuffer_ = new VertexBuffer(context_);
  808. debugVertexBuffer_ = new VertexBuffer(context_);
  809. initialized_ = true;
  810. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(UI, HandleBeginFrame));
  811. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UI, HandlePostUpdate));
  812. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(UI, HandleRenderUpdate));
  813. URHO3D_LOGINFO("Initialized user interface");
  814. }
  815. void UI::Update(float timeStep, UIElement* element)
  816. {
  817. // Keep a weak pointer to the element in case it destroys itself on update
  818. WeakPtr<UIElement> elementWeak(element);
  819. element->Update(timeStep);
  820. if (elementWeak.Expired())
  821. return;
  822. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  823. // Update of an element may modify its child vector. Use just index-based iteration to be safe
  824. for (unsigned i = 0; i < children.Size(); ++i)
  825. Update(timeStep, children[i]);
  826. }
  827. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  828. {
  829. if (vertexData.Empty())
  830. return;
  831. // Update quad geometry into the vertex buffer
  832. // Resize the vertex buffer first if too small or much too large
  833. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  834. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  835. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  836. dest->SetData(&vertexData[0]);
  837. }
  838. void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  839. {
  840. // Engine does not render when window is closed or device is lost
  841. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  842. if (batches.Empty())
  843. return;
  844. unsigned alphaFormat = Graphics::GetAlphaFormat();
  845. RenderSurface* surface = graphics_->GetRenderTarget(0);
  846. IntVector2 viewSize = graphics_->GetViewport().Size();
  847. Vector2 invScreenSize(1.0f / (float)viewSize.x_, 1.0f / (float)viewSize.y_);
  848. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  849. Vector2 offset(-1.0f, 1.0f);
  850. if (surface)
  851. {
  852. #ifdef URHO3D_OPENGL
  853. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the
  854. // same way as a render texture produced on Direct3D.
  855. offset.y_ = -offset.y_;
  856. scale.y_ = -scale.y_;
  857. #endif
  858. }
  859. Matrix4 projection(Matrix4::IDENTITY);
  860. projection.m00_ = scale.x_ * uiScale_;
  861. projection.m03_ = offset.x_;
  862. projection.m11_ = scale.y_ * uiScale_;
  863. projection.m13_ = offset.y_;
  864. projection.m22_ = 1.0f;
  865. projection.m23_ = 0.0f;
  866. projection.m33_ = 1.0f;
  867. graphics_->ClearParameterSources();
  868. graphics_->SetColorWrite(true);
  869. #ifdef URHO3D_OPENGL
  870. // Reverse winding if rendering to texture on OpenGL
  871. if (surface)
  872. graphics_->SetCullMode(CULL_CW);
  873. else
  874. #endif
  875. graphics_->SetCullMode(CULL_CCW);
  876. graphics_->SetDepthTest(CMP_ALWAYS);
  877. graphics_->SetDepthWrite(false);
  878. graphics_->SetFillMode(FILL_SOLID);
  879. graphics_->SetStencilTest(false);
  880. graphics_->SetVertexBuffer(buffer);
  881. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  882. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  883. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  884. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  885. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  886. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  887. for (unsigned i = batchStart; i < batchEnd; ++i)
  888. {
  889. const UIBatch& batch = batches[i];
  890. if (batch.vertexStart_ == batch.vertexEnd_)
  891. continue;
  892. ShaderVariation* ps;
  893. ShaderVariation* vs;
  894. if (!batch.customMaterial_)
  895. {
  896. if (!batch.texture_)
  897. {
  898. ps = noTexturePS;
  899. vs = noTextureVS;
  900. } else
  901. {
  902. // If texture contains only an alpha channel, use alpha shader (for fonts)
  903. vs = diffTextureVS;
  904. if (batch.texture_->GetFormat() == alphaFormat)
  905. ps = alphaTexturePS;
  906. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  907. ps = diffMaskTexturePS;
  908. else
  909. ps = diffTexturePS;
  910. }
  911. } else
  912. {
  913. vs = diffTextureVS;
  914. ps = diffTexturePS;
  915. Technique* technique = batch.customMaterial_->GetTechnique(0);
  916. if (technique)
  917. {
  918. Pass* pass = nullptr;
  919. for (int i = 0; i < technique->GetNumPasses(); ++i)
  920. {
  921. pass = technique->GetPass(i);
  922. if (pass)
  923. {
  924. vs = graphics_->GetShader(VS, pass->GetVertexShader(), batch.customMaterial_->GetVertexShaderDefines());
  925. ps = graphics_->GetShader(PS, pass->GetPixelShader(), batch.customMaterial_->GetPixelShaderDefines());
  926. break;
  927. }
  928. }
  929. }
  930. }
  931. graphics_->SetShaders(vs, ps);
  932. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  933. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  934. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  935. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  936. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  937. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  938. float elapsedTime = GetSubsystem<Time>()->GetElapsedTime();
  939. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  940. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  941. IntRect scissor = batch.scissor_;
  942. scissor.left_ = (int)(scissor.left_ * uiScale_);
  943. scissor.top_ = (int)(scissor.top_ * uiScale_);
  944. scissor.right_ = (int)(scissor.right_ * uiScale_);
  945. scissor.bottom_ = (int)(scissor.bottom_ * uiScale_);
  946. // Flip scissor vertically if using OpenGL texture rendering
  947. #ifdef URHO3D_OPENGL
  948. if (surface)
  949. {
  950. int top = scissor.top_;
  951. int bottom = scissor.bottom_;
  952. scissor.top_ = viewSize.y_ - bottom;
  953. scissor.bottom_ = viewSize.y_ - top;
  954. }
  955. #endif
  956. graphics_->SetBlendMode(batch.blendMode_);
  957. graphics_->SetScissorTest(true, scissor);
  958. if (!batch.customMaterial_)
  959. {
  960. graphics_->SetTexture(0, batch.texture_);
  961. } else
  962. {
  963. // Update custom shader parameters if needed
  964. if (graphics_->NeedParameterUpdate(SP_MATERIAL, reinterpret_cast<const void*>(batch.customMaterial_->GetShaderParameterHash())))
  965. {
  966. auto shader_parameters = batch.customMaterial_->GetShaderParameters();
  967. for (auto it = shader_parameters.Begin(); it != shader_parameters.End(); ++it)
  968. {
  969. graphics_->SetShaderParameter(it->second_.name_, it->second_.value_);
  970. }
  971. }
  972. // Apply custom shader textures
  973. auto textures = batch.customMaterial_->GetTextures();
  974. for (auto it = textures.Begin(); it != textures.End(); ++it)
  975. {
  976. graphics_->SetTexture(it->first_, it->second_);
  977. }
  978. }
  979. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE,
  980. (batch.vertexEnd_ - batch.vertexStart_) / UI_VERTEX_SIZE);
  981. if (batch.customMaterial_)
  982. {
  983. // Reset textures used by the batch custom material
  984. auto textures = batch.customMaterial_->GetTextures();
  985. for (auto it = textures.Begin(); it != textures.End(); ++it)
  986. {
  987. graphics_->SetTexture(it->first_, 0);
  988. }
  989. }
  990. }
  991. }
  992. void UI::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, UIElement* element, IntRect currentScissor)
  993. {
  994. // Set clipping scissor for child elements. No need to draw if zero size
  995. element->AdjustScissor(currentScissor);
  996. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  997. return;
  998. element->SortChildren();
  999. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  1000. if (children.Empty())
  1001. return;
  1002. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  1003. // same renderstate
  1004. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  1005. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  1006. {
  1007. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  1008. while (i != children.End())
  1009. {
  1010. int currentPriority = (*i)->GetPriority();
  1011. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  1012. {
  1013. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  1014. (*j)->GetBatches(batches, vertexData, currentScissor);
  1015. ++j;
  1016. }
  1017. // Now recurse into the children
  1018. while (i != j)
  1019. {
  1020. if ((*i)->IsVisible() && (*i) != cursor_)
  1021. GetBatches(batches, vertexData, *i, currentScissor);
  1022. ++i;
  1023. }
  1024. }
  1025. }
  1026. // On the root level draw each element and its children immediately after to avoid artifacts
  1027. else
  1028. {
  1029. while (i != children.End())
  1030. {
  1031. if ((*i) != cursor_)
  1032. {
  1033. if ((*i)->IsWithinScissor(currentScissor))
  1034. (*i)->GetBatches(batches, vertexData, currentScissor);
  1035. if ((*i)->IsVisible())
  1036. GetBatches(batches, vertexData, *i, currentScissor);
  1037. }
  1038. ++i;
  1039. }
  1040. }
  1041. }
  1042. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  1043. {
  1044. if (!current)
  1045. return;
  1046. current->SortChildren();
  1047. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  1048. LayoutMode parentLayoutMode = current->GetLayoutMode();
  1049. for (unsigned i = 0; i < children.Size(); ++i)
  1050. {
  1051. UIElement* element = children[i];
  1052. bool hasChildren = element->GetNumChildren() > 0;
  1053. if (element != cursor_.Get() && element->IsVisible())
  1054. {
  1055. if (element->IsInside(position, true))
  1056. {
  1057. // Store the current result, then recurse into its children. Because children
  1058. // are sorted from lowest to highest priority, the topmost match should remain
  1059. if (element->IsEnabled() || !enabledOnly)
  1060. result = element;
  1061. if (hasChildren)
  1062. GetElementAt(result, element, position, enabledOnly);
  1063. // Layout optimization: if the element has no children, can break out after the first match
  1064. else if (parentLayoutMode != LM_FREE)
  1065. break;
  1066. }
  1067. else
  1068. {
  1069. if (hasChildren)
  1070. {
  1071. if (element->IsInsideCombined(position, true))
  1072. GetElementAt(result, element, position, enabledOnly);
  1073. }
  1074. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  1075. // or if we already passed all visible elements
  1076. else if (parentLayoutMode != LM_FREE)
  1077. {
  1078. if (!i)
  1079. {
  1080. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  1081. element->GetScreenPosition().y_;
  1082. int layoutMaxSize = current->GetLayoutElementMaxSize();
  1083. int spacing = current->GetLayoutSpacing();
  1084. if (screenPos < 0 && layoutMaxSize > 0)
  1085. {
  1086. auto toSkip = (unsigned)(-screenPos / (layoutMaxSize + spacing));
  1087. if (toSkip > 0)
  1088. i += (toSkip - 1);
  1089. }
  1090. }
  1091. // Note: we cannot check for the up / left limits of positioning, since the element may be off the visible
  1092. // screen but some of its layouted children will yet be visible. In down & right directions we can terminate
  1093. // the loop, since all further children will be further down or right.
  1094. else if (parentLayoutMode == LM_HORIZONTAL)
  1095. {
  1096. if (element->GetScreenPosition().x_ >= rootElement_->GetPosition().x_ + rootElement_->GetSize().x_)
  1097. break;
  1098. }
  1099. else if (parentLayoutMode == LM_VERTICAL)
  1100. {
  1101. if (element->GetScreenPosition().y_ >= rootElement_->GetPosition().y_ + rootElement_->GetSize().y_)
  1102. break;
  1103. }
  1104. }
  1105. }
  1106. }
  1107. }
  1108. }
  1109. UIElement* UI::GetFocusableElement(UIElement* element)
  1110. {
  1111. while (element)
  1112. {
  1113. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  1114. break;
  1115. element = element->GetParent();
  1116. }
  1117. return element;
  1118. }
  1119. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  1120. {
  1121. // Prefer software cursor then OS-specific cursor
  1122. if (cursor_ && cursor_->IsVisible())
  1123. {
  1124. pos = cursor_->GetPosition();
  1125. visible = true;
  1126. }
  1127. else if (GetSubsystem<Input>()->GetMouseMode() == MM_RELATIVE)
  1128. visible = true;
  1129. else
  1130. {
  1131. auto* input = GetSubsystem<Input>();
  1132. visible = input->IsMouseVisible();
  1133. if (!visible && cursor_)
  1134. {
  1135. pos = cursor_->GetPosition();
  1136. }
  1137. else
  1138. {
  1139. pos = input->GetMousePosition();
  1140. pos = ConvertSystemToUI(pos);
  1141. }
  1142. }
  1143. }
  1144. void UI::SetCursorShape(CursorShape shape)
  1145. {
  1146. if (cursor_)
  1147. cursor_->SetShape(shape);
  1148. }
  1149. void UI::ReleaseFontFaces()
  1150. {
  1151. URHO3D_LOGDEBUG("Reloading font faces");
  1152. PODVector<Font*> fonts;
  1153. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  1154. for (unsigned i = 0; i < fonts.Size(); ++i)
  1155. fonts[i]->ReleaseFaces();
  1156. }
  1157. void UI::ProcessHover(const IntVector2& windowCursorPos, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor)
  1158. {
  1159. IntVector2 cursorPos;
  1160. WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
  1161. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1162. {
  1163. WeakPtr<UIElement> dragElement = i->first_;
  1164. UI::DragData* dragData = i->second_;
  1165. if (!dragElement)
  1166. {
  1167. i = DragElementErase(i);
  1168. continue;
  1169. }
  1170. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE);
  1171. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET);
  1172. bool dragDropTest = dragSource && dragTarget && element != dragElement;
  1173. // If drag start event has not been posted yet, do not do drag handling here
  1174. if (dragData->dragBeginPending)
  1175. dragSource = dragTarget = dragDropTest = false;
  1176. // Hover effect
  1177. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  1178. if (element && element->IsEnabled())
  1179. {
  1180. if (dragElement == element || dragDropTest)
  1181. {
  1182. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  1183. // Begin hover event
  1184. if (!hoveredElements_.Contains(element))
  1185. {
  1186. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
  1187. // Exit if element is destroyed by the event handling
  1188. if (!element)
  1189. return;
  1190. }
  1191. hoveredElements_[element] = true;
  1192. }
  1193. }
  1194. // Drag and drop test
  1195. if (dragDropTest)
  1196. {
  1197. bool accept = element->OnDragDropTest(dragElement);
  1198. if (accept)
  1199. {
  1200. using namespace DragDropTest;
  1201. VariantMap& eventData = GetEventDataMap();
  1202. eventData[P_SOURCE] = dragElement.Get();
  1203. eventData[P_TARGET] = element.Get();
  1204. eventData[P_ACCEPT] = accept;
  1205. SendEvent(E_DRAGDROPTEST, eventData);
  1206. accept = eventData[P_ACCEPT].GetBool();
  1207. }
  1208. if (cursor)
  1209. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  1210. }
  1211. else if (dragSource && cursor)
  1212. cursor->SetShape(dragElement == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  1213. ++i;
  1214. }
  1215. // Hover effect
  1216. // If no drag is going on, transmit hover event.
  1217. if (element && element->IsEnabled())
  1218. {
  1219. if (dragElementsCount_ == 0)
  1220. {
  1221. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  1222. // Begin hover event
  1223. if (!hoveredElements_.Contains(element))
  1224. {
  1225. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
  1226. // Exit if element is destroyed by the event handling
  1227. if (!element)
  1228. return;
  1229. }
  1230. hoveredElements_[element] = true;
  1231. }
  1232. }
  1233. }
  1234. void UI::ProcessClickBegin(const IntVector2& windowCursorPos, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor, bool cursorVisible)
  1235. {
  1236. if (cursorVisible)
  1237. {
  1238. IntVector2 cursorPos;
  1239. WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
  1240. bool newButton;
  1241. if (usingTouchInput_)
  1242. newButton = (buttons & button) == MOUSEB_NONE;
  1243. else
  1244. newButton = true;
  1245. buttons |= button;
  1246. if (element)
  1247. SetFocusElement(element);
  1248. // Focus change events may destroy the element, check again.
  1249. if (element)
  1250. {
  1251. // Handle focusing & bringing to front
  1252. element->BringToFront();
  1253. // Handle click
  1254. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1255. SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
  1256. // Fire double click event if element matches and is in time and is within max distance from the original click
  1257. if (doubleClickElement_ && element == doubleClickElement_ &&
  1258. (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000)) && lastMouseButtons_ == buttons && (windowCursorPos - doubleClickFirstPos_).Length() < maxDoubleClickDist_)
  1259. {
  1260. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1261. doubleClickElement_.Reset();
  1262. SendDoubleClickEvent(nullptr, element, doubleClickFirstPos_, cursorPos, button, buttons, qualifiers);
  1263. }
  1264. else
  1265. {
  1266. doubleClickElement_ = element;
  1267. doubleClickFirstPos_ = windowCursorPos;
  1268. clickTimer_.Reset();
  1269. }
  1270. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  1271. bool dragElementsContain = dragElements_.Contains(element);
  1272. if (element && !dragElementsContain)
  1273. {
  1274. auto* dragData = new DragData();
  1275. dragElements_[element] = dragData;
  1276. dragData->dragBeginPending = true;
  1277. dragData->sumPos = cursorPos;
  1278. dragData->dragBeginSumPos = cursorPos;
  1279. dragData->dragBeginTimer.Reset();
  1280. dragData->dragButtons = button;
  1281. dragData->numDragButtons = CountSetBits((unsigned)dragData->dragButtons);
  1282. dragElementsCount_++;
  1283. dragElementsContain = dragElements_.Contains(element);
  1284. }
  1285. else if (element && dragElementsContain && newButton)
  1286. {
  1287. DragData* dragData = dragElements_[element];
  1288. dragData->sumPos += cursorPos;
  1289. dragData->dragBeginSumPos += cursorPos;
  1290. dragData->dragButtons |= button;
  1291. dragData->numDragButtons = CountSetBits((unsigned)dragData->dragButtons);
  1292. }
  1293. }
  1294. else
  1295. {
  1296. // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
  1297. if (!HasModalElement())
  1298. SetFocusElement(nullptr);
  1299. SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
  1300. if (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons && (windowCursorPos - doubleClickFirstPos_).Length() < maxDoubleClickDist_)
  1301. SendDoubleClickEvent(nullptr, element, doubleClickFirstPos_, cursorPos, button, buttons, qualifiers);
  1302. }
  1303. lastMouseButtons_ = buttons;
  1304. }
  1305. }
  1306. void UI::ProcessClickEnd(const IntVector2& windowCursorPos, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor, bool cursorVisible)
  1307. {
  1308. WeakPtr<UIElement> element;
  1309. IntVector2 cursorPos = windowCursorPos;
  1310. if (cursorVisible)
  1311. element = GetElementAt(cursorPos, true, &cursorPos);
  1312. // Handle end of drag
  1313. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1314. {
  1315. WeakPtr<UIElement> dragElement = i->first_;
  1316. UI::DragData* dragData = i->second_;
  1317. if (!dragElement || !cursorVisible)
  1318. {
  1319. i = DragElementErase(i);
  1320. continue;
  1321. }
  1322. if (dragData->dragButtons & button)
  1323. {
  1324. // Handle end of click
  1325. if (element)
  1326. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor,
  1327. dragElement);
  1328. SendClickEvent(E_UIMOUSECLICKEND, dragElement, element, cursorPos, button, buttons, qualifiers);
  1329. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1330. {
  1331. dragElement->OnDragEnd(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, buttons,
  1332. cursor);
  1333. SendDragOrHoverEvent(E_DRAGEND, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1334. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE);
  1335. if (dragSource)
  1336. {
  1337. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET);
  1338. bool dragDropFinish = dragSource && dragTarget && element != dragElement;
  1339. if (dragDropFinish)
  1340. {
  1341. bool accept = element->OnDragDropFinish(dragElement);
  1342. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  1343. if (accept && dragElement && element)
  1344. {
  1345. using namespace DragDropFinish;
  1346. VariantMap& eventData = GetEventDataMap();
  1347. eventData[P_SOURCE] = dragElement.Get();
  1348. eventData[P_TARGET] = element.Get();
  1349. eventData[P_ACCEPT] = accept;
  1350. SendEvent(E_DRAGDROPFINISH, eventData);
  1351. }
  1352. }
  1353. }
  1354. }
  1355. i = DragElementErase(i);
  1356. }
  1357. else
  1358. ++i;
  1359. }
  1360. }
  1361. void UI::ProcessMove(const IntVector2& windowCursorPos, const IntVector2& cursorDeltaPos, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor,
  1362. bool cursorVisible)
  1363. {
  1364. if (cursorVisible && dragElementsCount_ > 0 && buttons)
  1365. {
  1366. IntVector2 cursorPos;
  1367. GetElementAt(windowCursorPos, true, &cursorPos);
  1368. auto* input = GetSubsystem<Input>();
  1369. bool mouseGrabbed = input->IsMouseGrabbed();
  1370. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1371. {
  1372. WeakPtr<UIElement> dragElement = i->first_;
  1373. UI::DragData* dragData = i->second_;
  1374. if (!dragElement)
  1375. {
  1376. i = DragElementErase(i);
  1377. continue;
  1378. }
  1379. if (!(dragData->dragButtons & buttons))
  1380. {
  1381. ++i;
  1382. continue;
  1383. }
  1384. // Calculate the position that we should send for this drag event.
  1385. IntVector2 sendPos;
  1386. if (usingTouchInput_)
  1387. {
  1388. dragData->sumPos += cursorDeltaPos;
  1389. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1390. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1391. }
  1392. else
  1393. {
  1394. dragData->sumPos = cursorPos;
  1395. sendPos = cursorPos;
  1396. }
  1397. if (dragElement->IsEnabled() && dragElement->IsVisible())
  1398. {
  1399. // Signal drag begin if distance threshold was exceeded
  1400. if (dragData->dragBeginPending && !mouseGrabbed)
  1401. {
  1402. IntVector2 beginSendPos;
  1403. beginSendPos.x_ = dragData->dragBeginSumPos.x_ / dragData->numDragButtons;
  1404. beginSendPos.y_ = dragData->dragBeginSumPos.y_ / dragData->numDragButtons;
  1405. IntVector2 offset = cursorPos - beginSendPos;
  1406. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  1407. {
  1408. dragData->dragBeginPending = false;
  1409. dragConfirmedCount_++;
  1410. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, buttons, qualifiers,
  1411. cursor);
  1412. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  1413. }
  1414. }
  1415. if (!dragData->dragBeginPending)
  1416. {
  1417. dragElement->OnDragMove(dragElement->ScreenToElement(sendPos), sendPos, cursorDeltaPos, buttons, qualifiers,
  1418. cursor);
  1419. SendDragOrHoverEvent(E_DRAGMOVE, dragElement, sendPos, cursorDeltaPos, dragData);
  1420. }
  1421. }
  1422. else
  1423. {
  1424. dragElement->OnDragEnd(dragElement->ScreenToElement(sendPos), sendPos, dragData->dragButtons, buttons, cursor);
  1425. SendDragOrHoverEvent(E_DRAGEND, dragElement, sendPos, IntVector2::ZERO, dragData);
  1426. dragElement.Reset();
  1427. }
  1428. ++i;
  1429. }
  1430. }
  1431. }
  1432. void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos, const IntVector2& deltaPos,
  1433. UI::DragData* dragData)
  1434. {
  1435. if (!element)
  1436. return;
  1437. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1438. using namespace DragMove;
  1439. VariantMap& eventData = GetEventDataMap();
  1440. eventData[P_ELEMENT] = element;
  1441. eventData[P_X] = screenPos.x_;
  1442. eventData[P_Y] = screenPos.y_;
  1443. eventData[P_ELEMENTX] = relativePos.x_;
  1444. eventData[P_ELEMENTY] = relativePos.y_;
  1445. if (eventType == E_DRAGMOVE)
  1446. {
  1447. eventData[P_DX] = deltaPos.x_;
  1448. eventData[P_DY] = deltaPos.y_;
  1449. }
  1450. if (dragData)
  1451. {
  1452. eventData[P_BUTTONS] = (unsigned)dragData->dragButtons;
  1453. eventData[P_NUMBUTTONS] = dragData->numDragButtons;
  1454. }
  1455. element->SendEvent(eventType, eventData);
  1456. }
  1457. void UI::SendClickEvent(StringHash eventType, UIElement* beginElement, UIElement* endElement, const IntVector2& pos, MouseButton button,
  1458. MouseButtonFlags buttons, QualifierFlags qualifiers)
  1459. {
  1460. VariantMap& eventData = GetEventDataMap();
  1461. eventData[UIMouseClick::P_ELEMENT] = endElement;
  1462. eventData[UIMouseClick::P_X] = pos.x_;
  1463. eventData[UIMouseClick::P_Y] = pos.y_;
  1464. eventData[UIMouseClick::P_BUTTON] = button;
  1465. eventData[UIMouseClick::P_BUTTONS] = (unsigned)buttons;
  1466. eventData[UIMouseClick::P_QUALIFIERS] = (unsigned)qualifiers;
  1467. // For click end events, send also the element the click began on
  1468. if (eventType == E_UIMOUSECLICKEND)
  1469. eventData[UIMouseClickEnd::P_BEGINELEMENT] = beginElement;
  1470. if (endElement)
  1471. {
  1472. // Send also element version of the event
  1473. if (eventType == E_UIMOUSECLICK)
  1474. endElement->SendEvent(E_CLICK, eventData);
  1475. else if (eventType == E_UIMOUSECLICKEND)
  1476. endElement->SendEvent(E_CLICKEND, eventData);
  1477. }
  1478. // Send the global event from the UI subsystem last
  1479. SendEvent(eventType, eventData);
  1480. }
  1481. void UI::SendDoubleClickEvent(UIElement* beginElement, UIElement* endElement, const IntVector2& firstPos, const IntVector2& secondPos, MouseButton button,
  1482. MouseButtonFlags buttons, QualifierFlags qualifiers)
  1483. {
  1484. VariantMap& eventData = GetEventDataMap();
  1485. eventData[UIMouseDoubleClick::P_ELEMENT] = endElement;
  1486. eventData[UIMouseDoubleClick::P_X] = secondPos.x_;
  1487. eventData[UIMouseDoubleClick::P_Y] = secondPos.y_;
  1488. eventData[UIMouseDoubleClick::P_XBEGIN] = firstPos.x_;
  1489. eventData[UIMouseDoubleClick::P_YBEGIN] = firstPos.y_;
  1490. eventData[UIMouseDoubleClick::P_BUTTON] = button;
  1491. eventData[UIMouseDoubleClick::P_BUTTONS] = (unsigned)buttons;
  1492. eventData[UIMouseDoubleClick::P_QUALIFIERS] = (unsigned)qualifiers;
  1493. if (endElement)
  1494. {
  1495. // Send also element version of the event
  1496. endElement->SendEvent(E_DOUBLECLICK, eventData);
  1497. }
  1498. // Send the global event from the UI subsystem last
  1499. SendEvent(E_UIMOUSEDOUBLECLICK, eventData);
  1500. }
  1501. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1502. {
  1503. using namespace ScreenMode;
  1504. if (!initialized_)
  1505. Initialize();
  1506. else
  1507. ResizeRootElement();
  1508. }
  1509. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  1510. {
  1511. using namespace MouseButtonDown;
  1512. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1513. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1514. usingTouchInput_ = false;
  1515. IntVector2 cursorPos;
  1516. bool cursorVisible;
  1517. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1518. // Handle drag cancelling
  1519. ProcessDragCancel();
  1520. auto* input = GetSubsystem<Input>();
  1521. if (!input->IsMouseGrabbed())
  1522. ProcessClickBegin(cursorPos, MouseButton(eventData[P_BUTTON].GetUInt()), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1523. }
  1524. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  1525. {
  1526. using namespace MouseButtonUp;
  1527. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1528. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1529. IntVector2 cursorPos;
  1530. bool cursorVisible;
  1531. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1532. ProcessClickEnd(cursorPos, (MouseButton)eventData[P_BUTTON].GetUInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1533. }
  1534. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  1535. {
  1536. using namespace MouseMove;
  1537. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1538. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1539. usingTouchInput_ = false;
  1540. auto* input = GetSubsystem<Input>();
  1541. const IntVector2& rootSize = rootElement_->GetSize();
  1542. const IntVector2& rootPos = rootElement_->GetPosition();
  1543. const IntVector2 mouseDeltaPos{ eventData[P_DX].GetInt(), eventData[P_DY].GetInt() };
  1544. const IntVector2 mousePos{ eventData[P_X].GetInt(), eventData[P_Y].GetInt() };
  1545. if (cursor_)
  1546. {
  1547. if (!input->IsMouseVisible())
  1548. {
  1549. if (!input->IsMouseLocked())
  1550. cursor_->SetPosition(ConvertSystemToUI(mousePos));
  1551. else if (cursor_->IsVisible())
  1552. {
  1553. // Relative mouse motion: move cursor only when visible
  1554. IntVector2 pos = cursor_->GetPosition();
  1555. pos += ConvertSystemToUI(mouseDeltaPos);
  1556. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  1557. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  1558. cursor_->SetPosition(pos);
  1559. }
  1560. }
  1561. else
  1562. {
  1563. // Absolute mouse motion: move always
  1564. cursor_->SetPosition(ConvertSystemToUI(mousePos));
  1565. }
  1566. }
  1567. IntVector2 cursorPos;
  1568. bool cursorVisible;
  1569. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1570. ProcessMove(cursorPos, mouseDeltaPos, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1571. }
  1572. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1573. {
  1574. auto* input = GetSubsystem<Input>();
  1575. if (input->IsMouseGrabbed())
  1576. return;
  1577. using namespace MouseWheel;
  1578. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetInt());
  1579. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetInt());
  1580. int delta = eventData[P_WHEEL].GetInt();
  1581. usingTouchInput_ = false;
  1582. IntVector2 cursorPos;
  1583. bool cursorVisible;
  1584. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1585. if (!nonFocusedMouseWheel_ && focusElement_)
  1586. focusElement_->OnWheel(delta, mouseButtons_, qualifiers_);
  1587. else
  1588. {
  1589. // If no element has actual focus or in non-focused mode, get the element at cursor
  1590. if (cursorVisible)
  1591. {
  1592. UIElement* element = GetElementAt(cursorPos);
  1593. if (nonFocusedMouseWheel_)
  1594. {
  1595. // Going up the hierarchy chain to find element that could handle mouse wheel
  1596. while (element && !element->IsWheelHandler())
  1597. {
  1598. element = element->GetParent();
  1599. }
  1600. }
  1601. else
  1602. // If the element itself is not focusable, search for a focusable parent,
  1603. // although the focusable element may not actually handle mouse wheel
  1604. element = GetFocusableElement(element);
  1605. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1606. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1607. }
  1608. }
  1609. }
  1610. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1611. {
  1612. auto* input = GetSubsystem<Input>();
  1613. if (input->IsMouseGrabbed())
  1614. return;
  1615. using namespace TouchBegin;
  1616. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1617. pos = ConvertSystemToUI(pos);
  1618. usingTouchInput_ = true;
  1619. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetInt());
  1620. WeakPtr<UIElement> element(GetElementAt(pos));
  1621. if (element)
  1622. {
  1623. ProcessClickBegin(pos, touchId, touchDragElements_[element], QUAL_NONE, nullptr, true);
  1624. touchDragElements_[element] |= touchId;
  1625. }
  1626. else
  1627. ProcessClickBegin(pos, touchId, touchId, QUAL_NONE, nullptr, true);
  1628. }
  1629. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1630. {
  1631. using namespace TouchEnd;
  1632. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1633. pos = ConvertSystemToUI(pos);
  1634. // Get the touch index
  1635. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetInt());
  1636. // Transmit hover end to the position where the finger was lifted
  1637. WeakPtr<UIElement> element(GetElementAt(pos));
  1638. // Clear any drag events that were using the touch id
  1639. for (auto i = touchDragElements_.Begin(); i != touchDragElements_.End();)
  1640. {
  1641. const MouseButtonFlags touches = i->second_;
  1642. if (touches & touchId)
  1643. i = touchDragElements_.Erase(i);
  1644. else
  1645. ++i;
  1646. }
  1647. if (element && element->IsEnabled())
  1648. element->OnHover(element->ScreenToElement(pos), pos, MOUSEB_NONE, QUAL_NONE, nullptr);
  1649. ProcessClickEnd(pos, touchId, MOUSEB_NONE, QUAL_NONE, nullptr, true);
  1650. }
  1651. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1652. {
  1653. using namespace TouchMove;
  1654. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1655. IntVector2 deltaPos(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
  1656. pos = ConvertSystemToUI(pos);
  1657. deltaPos = ConvertSystemToUI(deltaPos);
  1658. usingTouchInput_ = true;
  1659. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetInt());
  1660. ProcessMove(pos, deltaPos, touchId, QUAL_NONE, nullptr, true);
  1661. }
  1662. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1663. {
  1664. using namespace KeyDown;
  1665. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1666. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1667. auto key = (Key)eventData[P_KEY].GetUInt();
  1668. // Cancel UI dragging
  1669. if (key == KEY_ESCAPE && dragElementsCount_ > 0)
  1670. {
  1671. ProcessDragCancel();
  1672. return;
  1673. }
  1674. // Dismiss modal element if any when ESC key is pressed
  1675. if (key == KEY_ESCAPE && HasModalElement())
  1676. {
  1677. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1678. if (element->GetVars().Contains(VAR_ORIGIN))
  1679. // If it is a popup, dismiss by defocusing it
  1680. SetFocusElement(nullptr);
  1681. else
  1682. {
  1683. // If it is a modal window, by resetting its modal flag
  1684. auto* window = dynamic_cast<Window*>(element);
  1685. if (window && window->GetModalAutoDismiss())
  1686. window->SetModal(false);
  1687. }
  1688. return;
  1689. }
  1690. UIElement* element = focusElement_;
  1691. if (element)
  1692. {
  1693. // Switch focus between focusable elements in the same top level window
  1694. if (key == KEY_TAB)
  1695. {
  1696. UIElement* topLevel = element->GetParent();
  1697. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1698. topLevel = topLevel->GetParent();
  1699. if (topLevel)
  1700. {
  1701. topLevel->GetChildren(tempElements_, true);
  1702. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1703. {
  1704. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1705. i = tempElements_.Erase(i);
  1706. else
  1707. ++i;
  1708. }
  1709. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1710. {
  1711. if (tempElements_[i] == element)
  1712. {
  1713. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1714. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1715. UIElement* next = tempElements_[nextIndex];
  1716. SetFocusElement(next, true);
  1717. return;
  1718. }
  1719. }
  1720. }
  1721. }
  1722. // Defocus the element
  1723. else if (key == KEY_ESCAPE && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1724. element->SetFocus(false);
  1725. // If none of the special keys, pass the key to the focused element
  1726. else
  1727. element->OnKey(key, mouseButtons_, qualifiers_);
  1728. }
  1729. }
  1730. void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
  1731. {
  1732. using namespace TextInput;
  1733. UIElement* element = focusElement_;
  1734. if (element)
  1735. element->OnTextInput(eventData[P_TEXT].GetString());
  1736. }
  1737. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1738. {
  1739. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1740. // custom shapes can do it after this, but needs to do it each frame
  1741. if (cursor_ && dragElementsCount_ == 0)
  1742. cursor_->SetShape(CS_NORMAL);
  1743. }
  1744. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1745. {
  1746. using namespace PostUpdate;
  1747. Update(eventData[P_TIMESTEP].GetFloat());
  1748. }
  1749. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1750. {
  1751. RenderUpdate();
  1752. }
  1753. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1754. {
  1755. auto* input = GetSubsystem<Input>();
  1756. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1757. if (input->IsMouseVisible())
  1758. {
  1759. IntVector2 screenPos = input->GetMousePosition();
  1760. screenPos = ConvertSystemToUI(screenPos);
  1761. UIElement* element = GetElementAt(screenPos);
  1762. using namespace UIDropFile;
  1763. VariantMap uiEventData;
  1764. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1765. uiEventData[P_X] = screenPos.x_;
  1766. uiEventData[P_Y] = screenPos.y_;
  1767. uiEventData[P_ELEMENT] = element;
  1768. if (element)
  1769. {
  1770. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1771. uiEventData[P_ELEMENTX] = relativePos.x_;
  1772. uiEventData[P_ELEMENTY] = relativePos.y_;
  1773. }
  1774. SendEvent(E_UIDROPFILE, uiEventData);
  1775. }
  1776. }
  1777. HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator UI::DragElementErase(HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i)
  1778. {
  1779. // If running the engine frame in response to an event (re-entering UI frame logic) the dragElements_ may already be empty
  1780. if (dragElements_.Empty())
  1781. return dragElements_.End();
  1782. dragElementsConfirmed_.Clear();
  1783. DragData* dragData = i->second_;
  1784. if (!dragData->dragBeginPending)
  1785. --dragConfirmedCount_;
  1786. i = dragElements_.Erase(i);
  1787. --dragElementsCount_;
  1788. delete dragData;
  1789. return i;
  1790. }
  1791. void UI::ProcessDragCancel()
  1792. {
  1793. // How to tell difference between drag cancel and new selection on multi-touch?
  1794. if (usingTouchInput_)
  1795. return;
  1796. IntVector2 cursorPos;
  1797. bool cursorVisible;
  1798. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1799. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1800. {
  1801. WeakPtr<UIElement> dragElement = i->first_;
  1802. UI::DragData* dragData = i->second_;
  1803. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1804. {
  1805. dragElement->OnDragCancel(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, mouseButtons_,
  1806. cursor_);
  1807. SendDragOrHoverEvent(E_DRAGCANCEL, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1808. i = DragElementErase(i);
  1809. }
  1810. else
  1811. ++i;
  1812. }
  1813. }
  1814. IntVector2 UI::SumTouchPositions(UI::DragData* dragData, const IntVector2& oldSendPos)
  1815. {
  1816. IntVector2 sendPos = oldSendPos;
  1817. if (usingTouchInput_)
  1818. {
  1819. MouseButtonFlags buttons = dragData->dragButtons;
  1820. dragData->sumPos = IntVector2::ZERO;
  1821. auto* input = GetSubsystem<Input>();
  1822. for (unsigned i = 0; (1u << i) <= (unsigned)buttons; i++)
  1823. {
  1824. auto mouseButton = static_cast<MouseButton>(1u << i); // NOLINT(misc-misplaced-widening-cast)
  1825. if (buttons & mouseButton)
  1826. {
  1827. TouchState* ts = input->GetTouch((unsigned)i);
  1828. if (!ts)
  1829. break;
  1830. IntVector2 pos = ts->position_;
  1831. pos = ConvertSystemToUI(pos);
  1832. dragData->sumPos += pos;
  1833. }
  1834. }
  1835. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1836. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1837. }
  1838. return sendPos;
  1839. }
  1840. void UI::ResizeRootElement()
  1841. {
  1842. IntVector2 effectiveSize = GetEffectiveRootElementSize();
  1843. rootElement_->SetSize(effectiveSize);
  1844. rootModalElement_->SetSize(effectiveSize);
  1845. }
  1846. IntVector2 UI::GetEffectiveRootElementSize(bool applyScale) const
  1847. {
  1848. // Use a fake size in headless mode
  1849. IntVector2 size = graphics_ ? IntVector2(graphics_->GetWidth(), graphics_->GetHeight()) : IntVector2(1024, 768);
  1850. if (customSize_.x_ > 0 && customSize_.y_ > 0)
  1851. size = customSize_;
  1852. if (applyScale)
  1853. {
  1854. size.x_ = RoundToInt((float)size.x_ / uiScale_);
  1855. size.y_ = RoundToInt((float)size.y_ / uiScale_);
  1856. }
  1857. return size;
  1858. }
  1859. void UI::SetElementRenderTexture(UIElement* element, Texture2D* texture)
  1860. {
  1861. if (element == nullptr)
  1862. {
  1863. URHO3D_LOGERROR("UI::SetElementRenderTexture called with null element.");
  1864. return;
  1865. }
  1866. auto it = renderToTexture_.Find(element);
  1867. if (texture && it == renderToTexture_.End())
  1868. {
  1869. RenderToTextureData data;
  1870. data.texture_ = texture;
  1871. data.rootElement_ = element;
  1872. data.vertexBuffer_ = new VertexBuffer(context_);
  1873. data.debugVertexBuffer_ = new VertexBuffer(context_);
  1874. renderToTexture_[element] = data;
  1875. }
  1876. else if (it != renderToTexture_.End())
  1877. {
  1878. if (texture == nullptr)
  1879. renderToTexture_.Erase(it);
  1880. else
  1881. it->second_.texture_ = texture;
  1882. }
  1883. }
  1884. void RegisterUILibrary(Context* context)
  1885. {
  1886. Font::RegisterObject(context);
  1887. UIElement::RegisterObject(context);
  1888. UISelectable::RegisterObject(context);
  1889. BorderImage::RegisterObject(context);
  1890. Sprite::RegisterObject(context);
  1891. Button::RegisterObject(context);
  1892. CheckBox::RegisterObject(context);
  1893. Cursor::RegisterObject(context);
  1894. Text::RegisterObject(context);
  1895. Text3D::RegisterObject(context);
  1896. Window::RegisterObject(context);
  1897. View3D::RegisterObject(context);
  1898. LineEdit::RegisterObject(context);
  1899. Slider::RegisterObject(context);
  1900. ScrollBar::RegisterObject(context);
  1901. ScrollView::RegisterObject(context);
  1902. ListView::RegisterObject(context);
  1903. Menu::RegisterObject(context);
  1904. DropDownList::RegisterObject(context);
  1905. FileSelector::RegisterObject(context);
  1906. MessageBox::RegisterObject(context);
  1907. ProgressBar::RegisterObject(context);
  1908. ToolTip::RegisterObject(context);
  1909. UIComponent::RegisterObject(context);
  1910. }
  1911. }