UI.cpp 74 KB

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