2
0

UI.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. //
  2. // Copyright (c) 2008-2013 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 "CheckBox.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "Cursor.h"
  27. #include "DropDownList.h"
  28. #include "FileSelector.h"
  29. #include "Font.h"
  30. #include "Graphics.h"
  31. #include "GraphicsEvents.h"
  32. #include "Input.h"
  33. #include "InputEvents.h"
  34. #include "LineEdit.h"
  35. #include "ListView.h"
  36. #include "Log.h"
  37. #include "Matrix3x4.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ScrollBar.h"
  41. #include "Shader.h"
  42. #include "ShaderVariation.h"
  43. #include "Slider.h"
  44. #include "Sort.h"
  45. #include "Sprite.h"
  46. #include "Text.h"
  47. #include "Texture2D.h"
  48. #include "UI.h"
  49. #include "UIEvents.h"
  50. #include "VertexBuffer.h"
  51. #include "Window.h"
  52. #include "DebugNew.h"
  53. namespace Urho3D
  54. {
  55. ShortStringHash VAR_ORIGIN("Origin");
  56. OBJECTTYPESTATIC(UI);
  57. UI::UI(Context* context) :
  58. Object(context),
  59. rootElement_(new UIElement(context)),
  60. mouseButtons_(0),
  61. qualifiers_(0),
  62. initialized_(false),
  63. #ifdef WIN32
  64. nonFocusedMouseWheel_(false) // Default MS Windows behaviour
  65. #else
  66. nonFocusedMouseWheel_(true) // Default Mac OS X and Linux behaviour
  67. #endif
  68. {
  69. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  70. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  71. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  72. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  73. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  74. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  75. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  76. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  77. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  78. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  79. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  80. // Delay SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate)) and
  81. // SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate)) until UI is initialized
  82. // Try to initialize right now, but skip if screen mode is not yet set
  83. Initialize();
  84. }
  85. UI::~UI()
  86. {
  87. }
  88. void UI::SetCursor(Cursor* cursor)
  89. {
  90. // Remove old cursor (if any) and set new
  91. if (cursor_)
  92. {
  93. rootElement_->RemoveChild(cursor_);
  94. cursor_.Reset();
  95. }
  96. if (cursor)
  97. {
  98. rootElement_->AddChild(cursor);
  99. cursor_ = cursor;
  100. IntVector2 pos = cursor_->GetPosition();
  101. const IntVector2& rootSize = rootElement_->GetSize();
  102. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  103. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  104. cursor_->SetPosition(pos);
  105. }
  106. }
  107. void UI::SetFocusElement(UIElement* element)
  108. {
  109. using namespace FocusChanged;
  110. VariantMap eventData;
  111. eventData[P_CLICKEDELEMENT] = (void*)element;
  112. if (element)
  113. {
  114. // Return if already has focus
  115. if (focusElement_ == element)
  116. return;
  117. // Only allow child elements of the modal element to receive focus
  118. if (modalElement_)
  119. {
  120. UIElement* topLevel = element->GetParent();
  121. while (topLevel && topLevel->GetParent() != rootElement_)
  122. topLevel = topLevel->GetParent();
  123. if (topLevel != modalElement_)
  124. return;
  125. }
  126. // Search for an element in the hierarchy that can alter focus. If none found, exit
  127. element = GetFocusableElement(element);
  128. if (!element)
  129. return;
  130. }
  131. // Remove focus from the old element
  132. if (focusElement_)
  133. {
  134. UIElement* oldFocusElement = focusElement_;
  135. focusElement_.Reset();
  136. VariantMap focusEventData;
  137. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  138. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  139. }
  140. // Then set focus to the new
  141. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  142. {
  143. focusElement_ = element;
  144. VariantMap focusEventData;
  145. focusEventData[Focused::P_ELEMENT] = element;
  146. element->SendEvent(E_FOCUSED, focusEventData);
  147. }
  148. eventData[P_ELEMENT] = (void*)element;
  149. SendEvent(E_FOCUSCHANGED, eventData);
  150. }
  151. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  152. {
  153. // Only allow one modal element at a time, only the currently active modal element can disable itself
  154. if (modalElement_ && modalElement != modalElement_)
  155. return false;
  156. // The modal element must be parented to root
  157. if (modalElement->GetParent() != rootElement_)
  158. return false;
  159. // Currently only allow modal window
  160. if (modalElement && modalElement->GetType() != Window::GetTypeStatic())
  161. return false;
  162. modalElement_ = enable ? modalElement : 0;
  163. return true;
  164. }
  165. void UI::Clear()
  166. {
  167. rootElement_->RemoveAllChildren();
  168. if (cursor_)
  169. rootElement_->AddChild(cursor_);
  170. }
  171. void UI::Update(float timeStep)
  172. {
  173. assert(rootElement_);
  174. PROFILE(UpdateUI);
  175. if (cursor_ && cursor_->IsVisible())
  176. {
  177. IntVector2 pos = cursor_->GetPosition();
  178. WeakPtr<UIElement> element(GetElementAt(pos));
  179. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  180. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  181. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  182. // Hover effect
  183. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  184. if (element && element->IsEnabled())
  185. {
  186. if (!dragElement_ || dragElement_ == element || dragDropTest)
  187. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  188. }
  189. else
  190. cursor_->SetShape(CS_NORMAL);
  191. // Drag and drop test
  192. if (dragDropTest)
  193. {
  194. bool accept = element->OnDragDropTest(dragElement_);
  195. if (accept)
  196. {
  197. using namespace DragDropTest;
  198. VariantMap eventData;
  199. eventData[P_SOURCE] = (void*)dragElement_.Get();
  200. eventData[P_TARGET] = (void*)element.Get();
  201. eventData[P_ACCEPT] = accept;
  202. SendEvent(E_DRAGDROPTEST, eventData);
  203. accept = eventData[P_ACCEPT].GetBool();
  204. }
  205. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  206. }
  207. else if (dragSource)
  208. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  209. }
  210. // Touch hover
  211. Input* input = GetSubsystem<Input>();
  212. if (input)
  213. {
  214. unsigned numTouches = input->GetNumTouches();
  215. for (unsigned i = 0; i < numTouches; ++i)
  216. {
  217. TouchState* touch = input->GetTouch(i);
  218. UIElement* element = GetElementAt(touch->position_);
  219. if (element && element->IsEnabled())
  220. element->OnHover(element->ScreenToElement(touch->position_), touch->position_, MOUSEB_LEFT, 0, 0);
  221. }
  222. }
  223. Update(timeStep, rootElement_);
  224. }
  225. void UI::RenderUpdate()
  226. {
  227. assert(rootElement_ && graphics_);
  228. PROFILE(GetUIBatches);
  229. // If the OS cursor is visible, do not render the UI's own cursor
  230. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  231. bool uiCursorVisible = false;
  232. if (osCursorVisible && cursor_)
  233. {
  234. uiCursorVisible = cursor_->IsVisible();
  235. cursor_->SetTempVisible(false);
  236. }
  237. // Get rendering batches from the UI elements
  238. batches_.Clear();
  239. vertexData_.Clear();
  240. const IntVector2& rootSize = rootElement_->GetSize();
  241. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  242. // Restore UI cursor visibility state
  243. if (osCursorVisible && cursor_)
  244. cursor_->SetTempVisible(uiCursorVisible);
  245. }
  246. void UI::Render()
  247. {
  248. PROFILE(RenderUI);
  249. Render(batches_, vertexData_);
  250. Render(debugDrawBatches_, debugDrawVertexData_);
  251. // Clear the debug draw batches and data
  252. debugDrawBatches_.Clear();
  253. debugDrawVertexData_.Clear();
  254. }
  255. void UI::DebugDraw(UIElement* element)
  256. {
  257. if (element)
  258. {
  259. const IntVector2& rootSize = rootElement_->GetSize();
  260. IntRect currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  261. // Set clipping scissor for child elements. No need to draw if zero size
  262. element->AdjustScissor(currentScissor);
  263. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  264. return;
  265. element->GetDebugDrawBatches(debugDrawBatches_, debugDrawVertexData_, currentScissor);
  266. }
  267. }
  268. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  269. {
  270. SharedPtr<XMLFile> xml(new XMLFile(context_));
  271. if (!xml->Load(source))
  272. return SharedPtr<UIElement>();
  273. else
  274. return LoadLayout(xml, styleFile);
  275. }
  276. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  277. {
  278. PROFILE(LoadUILayout);
  279. SharedPtr<UIElement> root;
  280. if (!file)
  281. {
  282. LOGERROR("Null UI layout XML file");
  283. return root;
  284. }
  285. LOGDEBUG("Loading UI layout " + file->GetName());
  286. XMLElement rootElem = file->GetRoot("element");
  287. if (!rootElem)
  288. {
  289. LOGERROR("No root UI element in " + file->GetName());
  290. return root;
  291. }
  292. String typeName = rootElem.GetAttribute("type");
  293. if (typeName.Empty())
  294. typeName = "UIElement";
  295. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  296. if (!root)
  297. {
  298. LOGERROR("Could not create unknown UI element " + typeName);
  299. return root;
  300. }
  301. if (styleFile)
  302. // Set it as default for later use by children elements
  303. root->SetDefaultStyle(styleFile);
  304. else
  305. // Use default style file of the root element if it has one
  306. styleFile = rootElement_->GetDefaultStyle(false);
  307. root->LoadXML(rootElem, styleFile);
  308. return root;
  309. }
  310. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  311. {
  312. PROFILE(SaveUILayout);
  313. if (element)
  314. return element->SaveXML(dest);
  315. else
  316. return false;
  317. }
  318. void UI::SetClipBoardText(const String& text)
  319. {
  320. clipBoard_ = text;
  321. }
  322. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  323. {
  324. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  325. }
  326. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  327. {
  328. UIElement* result = 0;
  329. GetElementAt(result, rootElement_, position, enabledOnly);
  330. return result;
  331. }
  332. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  333. {
  334. return GetElementAt(IntVector2(x, y), enabledOnly);
  335. }
  336. UIElement* UI::GetFrontElement() const
  337. {
  338. // If modal element is set then return it
  339. if (modalElement_)
  340. return modalElement_;
  341. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  342. int maxPriority = M_MIN_INT;
  343. UIElement* front = 0;
  344. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  345. {
  346. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  347. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  348. continue;
  349. int priority = rootChildren[i]->GetPriority();
  350. if (priority > maxPriority)
  351. {
  352. maxPriority = priority;
  353. front = rootChildren[i];
  354. }
  355. }
  356. return front;
  357. }
  358. IntVector2 UI::GetCursorPosition()
  359. {
  360. if (!cursor_)
  361. return IntVector2::ZERO;
  362. else
  363. return cursor_->GetPosition();
  364. }
  365. void UI::Initialize()
  366. {
  367. Graphics* graphics = GetSubsystem<Graphics>();
  368. Renderer* renderer = GetSubsystem<Renderer>();
  369. if (!graphics || !graphics->IsInitialized() || !renderer)
  370. return;
  371. PROFILE(InitUI);
  372. graphics_ = graphics;
  373. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  374. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  375. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  376. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  377. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  378. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  379. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  380. vertexBuffer_ = new VertexBuffer(context_);
  381. initialized_ = true;
  382. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  383. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  384. LOGINFO("Initialized user interface");
  385. }
  386. void UI::Update(float timeStep, UIElement* element)
  387. {
  388. element->Update(timeStep);
  389. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  390. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  391. Update(timeStep, *i);
  392. }
  393. void UI::Render(const PODVector<UIBatch>& batches, const PODVector<float>& vertexData)
  394. {
  395. // Engine does not render when window is closed or device is lost
  396. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  397. if (vertexData.Empty())
  398. return;
  399. // Update quad geometry into the vertex buffer
  400. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  401. // Resize the vertex buffer if too small or much too large
  402. if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
  403. vertexBuffer_->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  404. vertexBuffer_->SetData(&vertexData[0]);
  405. Vector2 invScreenSize(1.0f / (float)graphics_->GetWidth(), 1.0f / (float)graphics_->GetHeight());
  406. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  407. Vector2 offset(-1.0f, 1.0f);
  408. Matrix4 projection(Matrix4::IDENTITY);
  409. projection.m00_ = scale.x_;
  410. projection.m03_ = offset.x_;
  411. projection.m11_ = scale.y_;
  412. projection.m13_ = offset.y_;
  413. projection.m22_ = 1.0f;
  414. projection.m23_ = 0.0f;
  415. projection.m33_ = 1.0f;
  416. graphics_->ClearParameterSources();
  417. graphics_->SetCullMode(CULL_CCW);
  418. graphics_->SetDepthTest(CMP_ALWAYS);
  419. graphics_->SetDepthWrite(false);
  420. graphics_->SetStencilTest(false);
  421. graphics_->ResetRenderTargets();
  422. ShaderVariation* ps = 0;
  423. ShaderVariation* vs = 0;
  424. unsigned alphaFormat = Graphics::GetAlphaFormat();
  425. for (unsigned i = 0; i < batches.Size(); ++i)
  426. {
  427. const UIBatch& batch = batches[i];
  428. if (batch.vertexStart_ == batch.vertexEnd_)
  429. continue;
  430. if (!batch.texture_)
  431. {
  432. ps = noTexturePS_;
  433. vs = noTextureVS_;
  434. }
  435. else
  436. {
  437. // If texture contains only an alpha channel, use alpha shader (for fonts)
  438. vs = diffTextureVS_;
  439. if (batch.texture_->GetFormat() == alphaFormat)
  440. ps = alphaTexturePS_;
  441. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  442. ps = diffMaskTexturePS_;
  443. else
  444. ps = diffTexturePS_;
  445. }
  446. graphics_->SetShaders(vs, ps);
  447. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  448. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  449. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  450. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  451. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  452. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  453. graphics_->SetBlendMode(batch.blendMode_);
  454. graphics_->SetScissorTest(true, batch.scissor_);
  455. graphics_->SetTexture(0, batch.texture_);
  456. graphics_->SetVertexBuffer(vertexBuffer_);
  457. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  458. UI_VERTEX_SIZE);
  459. }
  460. }
  461. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  462. {
  463. // Set clipping scissor for child elements. No need to draw if zero size
  464. element->AdjustScissor(currentScissor);
  465. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  466. return;
  467. element->SortChildren();
  468. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  469. if (children.Empty())
  470. return;
  471. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  472. // same renderstate
  473. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  474. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  475. {
  476. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  477. while (i != children.End())
  478. {
  479. int currentPriority = (*i)->GetPriority();
  480. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  481. {
  482. if ((*j)->IsWithinScissor(currentScissor))
  483. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  484. ++j;
  485. }
  486. // Now recurse into the children
  487. while (i != j)
  488. {
  489. if ((*i)->IsVisible())
  490. GetBatches(*i, currentScissor);
  491. ++i;
  492. }
  493. }
  494. }
  495. // On the root level draw each element and its children immediately after to avoid artifacts
  496. else
  497. {
  498. while (i != children.End())
  499. {
  500. if ((*i)->IsWithinScissor(currentScissor))
  501. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  502. if ((*i)->IsVisible())
  503. GetBatches(*i, currentScissor);
  504. ++i;
  505. }
  506. }
  507. }
  508. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  509. {
  510. if (!current)
  511. return;
  512. current->SortChildren();
  513. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  514. LayoutMode parentLayoutMode = current->GetLayoutMode();
  515. for (unsigned i = 0; i < children.Size(); ++i)
  516. {
  517. UIElement* element = children[i];
  518. // If has a modal element, skip other elements from the root level
  519. // Exception: if the element has the "origin" element in its variables it is a popup and should not be skipped
  520. // if the origin element belongs to the modal element's hierarchy
  521. if (current == rootElement_ && modalElement_ && element != modalElement_)
  522. {
  523. bool shouldSkip = true;
  524. UIElement* originElement = static_cast<UIElement*>(element->GetVar(VAR_ORIGIN).GetPtr());
  525. while (originElement)
  526. {
  527. if (originElement == modalElement_)
  528. {
  529. shouldSkip = false;
  530. break;
  531. }
  532. originElement = originElement->GetParent();
  533. }
  534. if (shouldSkip)
  535. continue;
  536. }
  537. bool hasChildren = element->GetNumChildren() > 0;
  538. if (element != cursor_.Get() && element->IsVisible())
  539. {
  540. if (element->IsInside(position, true))
  541. {
  542. // Store the current result, then recurse into its children. Because children
  543. // are sorted from lowest to highest priority, the topmost match should remain
  544. if (element->IsEnabled() || !enabledOnly)
  545. result = element;
  546. if (hasChildren)
  547. GetElementAt(result, element, position, enabledOnly);
  548. // Layout optimization: if the element has no children, can break out after the first match
  549. else if (parentLayoutMode != LM_FREE)
  550. break;
  551. }
  552. else
  553. {
  554. if (hasChildren)
  555. {
  556. if (element->IsInsideCombined(position, true))
  557. GetElementAt(result, element, position, enabledOnly);
  558. }
  559. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  560. // or if we already passed all visible elements
  561. else if (parentLayoutMode != LM_FREE)
  562. {
  563. if (!i)
  564. {
  565. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  566. element->GetScreenPosition().y_;
  567. int layoutMinSize = current->GetLayoutMinSize();
  568. if (screenPos < 0 && layoutMinSize > 0)
  569. {
  570. unsigned toSkip = -screenPos / layoutMinSize;
  571. if (toSkip > 0)
  572. i += (toSkip - 1);
  573. }
  574. }
  575. else if (parentLayoutMode == LM_HORIZONTAL)
  576. {
  577. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  578. break;
  579. }
  580. else if (parentLayoutMode == LM_VERTICAL)
  581. {
  582. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  583. break;
  584. }
  585. }
  586. }
  587. }
  588. }
  589. }
  590. UIElement* UI::GetFocusableElement(UIElement* element)
  591. {
  592. while (element)
  593. {
  594. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  595. break;
  596. element = element->GetParent();
  597. }
  598. return element;
  599. }
  600. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  601. {
  602. using namespace ScreenMode;
  603. if (!initialized_)
  604. Initialize();
  605. else
  606. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  607. }
  608. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  609. {
  610. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  611. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  612. if (cursor_ && cursor_->IsVisible())
  613. {
  614. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  615. IntVector2 pos = cursor_->GetPosition();
  616. WeakPtr<UIElement> element(GetElementAt(pos));
  617. if (element)
  618. {
  619. // Handle focusing & bringing to front
  620. if (button == MOUSEB_LEFT)
  621. {
  622. SetFocusElement(element);
  623. element->BringToFront();
  624. }
  625. // Handle click
  626. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  627. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  628. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  629. {
  630. dragElement_ = element;
  631. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  632. }
  633. }
  634. else
  635. {
  636. // If clicked over no element, or a disabled element, lose focus
  637. SetFocusElement(0);
  638. }
  639. using namespace UIMouseClick;
  640. VariantMap eventData;
  641. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  642. eventData[UIMouseClick::P_X] = pos.x_;
  643. eventData[UIMouseClick::P_Y] = pos.y_;
  644. eventData[UIMouseClick::P_BUTTON] = button;
  645. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  646. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  647. SendEvent(E_UIMOUSECLICK, eventData);
  648. }
  649. }
  650. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  651. {
  652. using namespace MouseButtonUp;
  653. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  654. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  655. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  656. {
  657. IntVector2 pos = cursor_->GetPosition();
  658. if (dragElement_ && !mouseButtons_)
  659. {
  660. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  661. {
  662. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  663. // Drag and drop finish
  664. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  665. if (dragSource)
  666. {
  667. WeakPtr<UIElement> target(GetElementAt(pos));
  668. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  669. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  670. if (dragDropFinish)
  671. {
  672. bool accept = target->OnDragDropFinish(dragElement_);
  673. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  674. if (accept && dragElement_ && target)
  675. {
  676. using namespace DragDropFinish;
  677. VariantMap eventData;
  678. eventData[P_SOURCE] = (void*)dragElement_.Get();
  679. eventData[P_TARGET] = (void*)target.Get();
  680. eventData[P_ACCEPT] = accept;
  681. SendEvent(E_DRAGDROPFINISH, eventData);
  682. }
  683. }
  684. }
  685. }
  686. dragElement_.Reset();
  687. }
  688. }
  689. }
  690. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  691. {
  692. using namespace MouseMove;
  693. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  694. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  695. if (cursor_)
  696. {
  697. Input* input = GetSubsystem<Input>();
  698. const IntVector2& rootSize = rootElement_->GetSize();
  699. if (!input->IsMouseVisible())
  700. {
  701. // Relative mouse motion: move cursor only when visible
  702. if (cursor_->IsVisible())
  703. {
  704. IntVector2 pos = cursor_->GetPosition();
  705. pos.x_ += eventData[P_DX].GetInt();
  706. pos.y_ += eventData[P_DY].GetInt();
  707. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  708. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  709. cursor_->SetPosition(pos);
  710. }
  711. }
  712. else
  713. {
  714. // Absolute mouse motion: move always
  715. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  716. }
  717. if (dragElement_ && mouseButtons_)
  718. {
  719. IntVector2 pos = cursor_->GetPosition();
  720. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  721. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  722. else
  723. {
  724. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  725. dragElement_.Reset();
  726. }
  727. }
  728. }
  729. }
  730. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  731. {
  732. using namespace MouseWheel;
  733. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  734. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  735. int delta = eventData[P_WHEEL].GetInt();
  736. UIElement* element;
  737. if (!nonFocusedMouseWheel_&& (element = focusElement_))
  738. element->OnWheel(delta, mouseButtons_, qualifiers_);
  739. else
  740. {
  741. // If no element has actual focus or in non-focused mode, get the element at cursor
  742. if (cursor_)
  743. {
  744. IntVector2 pos = cursor_->GetPosition();
  745. element = GetElementAt(pos);
  746. if (nonFocusedMouseWheel_)
  747. {
  748. // Going up the hierarchy chain to find element that could handle mouse wheel
  749. while (element)
  750. {
  751. if (element->GetType() == ListView::GetTypeStatic() ||
  752. element->GetType() == ScrollView::GetTypeStatic())
  753. break;
  754. element = element->GetParent();
  755. }
  756. }
  757. else
  758. // If the element itself is not focusable, search for a focusable parent,
  759. // although the focusable element may not actually handle mouse wheel
  760. element = GetFocusableElement(element);
  761. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  762. element->OnWheel(delta, mouseButtons_, qualifiers_);
  763. }
  764. }
  765. }
  766. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  767. {
  768. using namespace TouchBegin;
  769. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  770. WeakPtr<UIElement> element(GetElementAt(pos));
  771. if (element)
  772. {
  773. // Handle focusing & bringing to front
  774. SetFocusElement(element);
  775. element->BringToFront();
  776. // Handle click
  777. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  778. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  779. if (element && !dragElement_ )
  780. {
  781. dragElement_ = element;
  782. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  783. }
  784. }
  785. else
  786. {
  787. // If clicked over no element, or a disabled element, lose focus
  788. SetFocusElement(0);
  789. }
  790. using namespace UIMouseClick;
  791. VariantMap clickEventData;
  792. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  793. clickEventData[UIMouseClick::P_X] = pos.x_;
  794. clickEventData[UIMouseClick::P_Y] = pos.y_;
  795. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  796. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  797. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  798. SendEvent(E_UIMOUSECLICK, clickEventData);
  799. }
  800. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  801. {
  802. using namespace TouchEnd;
  803. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  804. // Transmit hover end to the position where the finger was lifted
  805. UIElement* element = GetElementAt(pos);
  806. if (element && element->IsEnabled())
  807. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  808. if (dragElement_)
  809. {
  810. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  811. {
  812. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  813. // Drag and drop finish
  814. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  815. if (dragSource)
  816. {
  817. WeakPtr<UIElement> target(GetElementAt(pos));
  818. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  819. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  820. if (dragDropFinish)
  821. {
  822. bool accept = target->OnDragDropFinish(dragElement_);
  823. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  824. if (accept && dragElement_ && target)
  825. {
  826. using namespace DragDropFinish;
  827. VariantMap eventData;
  828. eventData[P_SOURCE] = (void*)dragElement_.Get();
  829. eventData[P_TARGET] = (void*)target.Get();
  830. eventData[P_ACCEPT] = accept;
  831. SendEvent(E_DRAGDROPFINISH, eventData);
  832. }
  833. }
  834. }
  835. }
  836. dragElement_.Reset();
  837. }
  838. }
  839. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  840. {
  841. using namespace TouchMove;
  842. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  843. if (dragElement_)
  844. {
  845. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  846. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  847. else
  848. {
  849. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  850. dragElement_.Reset();
  851. }
  852. }
  853. }
  854. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  855. {
  856. using namespace KeyDown;
  857. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  858. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  859. int key = eventData[P_KEY].GetInt();
  860. UIElement* element = focusElement_;
  861. if (element)
  862. {
  863. // Switch focus between focusable elements in the same top level window
  864. if (key == KEY_TAB)
  865. {
  866. UIElement* topLevel = element->GetParent();
  867. while (topLevel && topLevel->GetParent() != rootElement_)
  868. topLevel = topLevel->GetParent();
  869. if (topLevel)
  870. {
  871. topLevel->GetChildren(tempElements_, true);
  872. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  873. {
  874. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  875. i = tempElements_.Erase(i);
  876. else
  877. ++i;
  878. }
  879. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  880. {
  881. if (tempElements_[i] == element)
  882. {
  883. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  884. SetFocusElement(next);
  885. return;
  886. }
  887. }
  888. }
  889. }
  890. // Defocus the element
  891. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  892. element->SetFocus(false);
  893. // If none of the special keys, pass the key to the focused element
  894. else
  895. element->OnKey(key, mouseButtons_, qualifiers_);
  896. }
  897. }
  898. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  899. {
  900. using namespace Char;
  901. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  902. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  903. UIElement* element = focusElement_;
  904. if (element)
  905. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  906. }
  907. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  908. {
  909. using namespace PostUpdate;
  910. Update(eventData[P_TIMESTEP].GetFloat());
  911. }
  912. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  913. {
  914. RenderUpdate();
  915. }
  916. void RegisterUILibrary(Context* context)
  917. {
  918. Font::RegisterObject(context);
  919. UIElement::RegisterObject(context);
  920. BorderImage::RegisterObject(context);
  921. Sprite::RegisterObject(context);
  922. Button::RegisterObject(context);
  923. CheckBox::RegisterObject(context);
  924. Cursor::RegisterObject(context);
  925. Text::RegisterObject(context);
  926. Window::RegisterObject(context);
  927. LineEdit::RegisterObject(context);
  928. Slider::RegisterObject(context);
  929. ScrollBar::RegisterObject(context);
  930. ScrollView::RegisterObject(context);
  931. ListView::RegisterObject(context);
  932. Menu::RegisterObject(context);
  933. DropDownList::RegisterObject(context);
  934. FileSelector::RegisterObject(context);
  935. }
  936. }