UI.cpp 78 KB

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