UI.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "BaseUIElementFactory.h"
  25. #include "Cursor.h"
  26. #include "Font.h"
  27. #include "InputEvents.h"
  28. #include "Log.h"
  29. #include "Matrix4.h"
  30. #include "PixelShader.h"
  31. #include "Profiler.h"
  32. #include "Renderer.h"
  33. #include "RendererEvents.h"
  34. #include "RendererImpl.h"
  35. #include "ResourceCache.h"
  36. #include "StringUtils.h"
  37. #include "Texture2D.h"
  38. #include "UI.h"
  39. #include "VertexShader.h"
  40. #include <algorithm>
  41. #include "DebugNew.h"
  42. static bool compareUIElements(const UIElement* lhs, const UIElement* rhs)
  43. {
  44. return lhs->getPriority() < rhs->getPriority();
  45. }
  46. UI::UI(Renderer* renderer, ResourceCache* cache) :
  47. mRenderer(renderer),
  48. mCache(cache),
  49. mMouseDrag(false),
  50. mMouseDragElement(0),
  51. mMouseButtons(0)
  52. {
  53. if (!mRenderer)
  54. EXCEPTION("Null renderer for UI");
  55. if (!mCache)
  56. EXCEPTION("Null resource cache for UI");
  57. LOGINFO("UI created");
  58. mRootElement = new UIElement();
  59. mRootElement->setSize(mRenderer->getWidth(), mRenderer->getHeight());
  60. subscribeToEvent(EVENT_WINDOWRESIZED, EVENT_HANDLER(UI, handleWindowResized));
  61. subscribeToEvent(EVENT_MOUSEMOVE, EVENT_HANDLER(UI, handleMouseMove));
  62. subscribeToEvent(EVENT_MOUSEBUTTONDOWN, EVENT_HANDLER(UI, handleMouseButtonDown));
  63. subscribeToEvent(EVENT_MOUSEBUTTONUP, EVENT_HANDLER(UI, handleMouseButtonUp));
  64. subscribeToEvent(EVENT_CHAR, EVENT_HANDLER(UI, handleChar));
  65. mNoTextureVS = mCache->getResource<VertexShader>("Shaders/SM2/Basic_VCol.vs2");
  66. mDiffTextureVS = mCache->getResource<VertexShader>("Shaders/SM2/Basic_DiffVCol.vs2");
  67. mNoTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_VCol.ps2");
  68. mDiffTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_DiffVCol.ps2");
  69. mAlphaTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_AlphaVCol.ps2");
  70. // Add the base element factory
  71. addElementFactory(new BaseUIElementFactory());
  72. }
  73. UI::~UI()
  74. {
  75. LOGINFO("UI shut down");
  76. }
  77. void UI::setCursor(Cursor* cursor)
  78. {
  79. // Remove old cursor (if any) and set new
  80. if (mCursor)
  81. {
  82. mRootElement->removeChild(mCursor);
  83. mCursor.reset();
  84. }
  85. if (cursor)
  86. {
  87. mRootElement->addChild(cursor);
  88. mCursor = cursor;
  89. IntVector2 pos = mCursor->getPosition();
  90. IntVector2 rootSize = mRootElement->getSize();
  91. pos.mX = clamp(pos.mX, 0, rootSize.mX - 1);
  92. pos.mY = clamp(pos.mY, 0, rootSize.mY - 1);
  93. mCursor->setPosition(pos);
  94. }
  95. }
  96. void UI::setFocusElement(UIElement* element)
  97. {
  98. if (element)
  99. {
  100. if ((element->hasFocus()) || (!element->isFocusable()))
  101. return;
  102. }
  103. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  104. // Go through all elements to clear the old focus
  105. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  106. {
  107. UIElement* other = *i;
  108. if ((other != element) && (other->hasFocus()))
  109. other->setFocus(false);
  110. }
  111. if (element)
  112. element->setFocus(true);
  113. }
  114. void UI::bringToFront(UIElement* element)
  115. {
  116. if (!element)
  117. return;
  118. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  119. UIElement* ptr = element;
  120. while ((ptr) && (ptr->getParent() != mRootElement))
  121. ptr = ptr->getParent();
  122. if ((!ptr) || (!ptr->getBringToFront()))
  123. return;
  124. // Get the highest priority used by all other top level elements, decrease their priority by one,
  125. // and assign that to new front element. However, take into account only active (enabled) elements
  126. // so that any noninteractive overlays are left alone
  127. int maxPriority = M_MIN_INT;
  128. std::vector<UIElement*> topLevelElements = mRootElement->getChildren();
  129. for (std::vector<UIElement*>::iterator i = topLevelElements.begin(); i != topLevelElements.end(); ++i)
  130. {
  131. UIElement* other = *i;
  132. if ((other->isEnabled()) && (other != ptr))
  133. {
  134. int priority = other->getPriority();
  135. maxPriority = max(priority, maxPriority);
  136. other->setPriority(priority - 1);
  137. }
  138. }
  139. ptr->setPriority(maxPriority);
  140. }
  141. void UI::update(float timeStep)
  142. {
  143. PROFILE(UI_Update);
  144. // If device lost, do not perform update
  145. if (mRenderer->isDeviceLost())
  146. return;
  147. if ((mCursor) && (mCursor->isVisible()))
  148. {
  149. IntVector2 pos = mCursor->getPosition();
  150. UIElement* element = getElementAt(pos);
  151. if (element)
  152. element->onHover(element->screenToElement(pos), pos, mMouseButtons);
  153. }
  154. {
  155. PROFILE(UI_UpdateElements);
  156. update(timeStep, mRootElement);
  157. }
  158. {
  159. PROFILE(UI_GetBatches);
  160. mBatches.clear();
  161. mQuads.clear();
  162. IntVector2 rootSize = mRootElement->getSize();
  163. getBatches(mRootElement, IntRect(0, 0, rootSize.mX, rootSize.mY));
  164. }
  165. }
  166. void UI::render()
  167. {
  168. PROFILE(UI_Render);
  169. static const Vector2 scale(2.0f, -2.0f);
  170. static const Vector2 offset(-1.0f, 1.0f);
  171. Matrix4 projection;
  172. memset(&projection, 0, sizeof(projection));
  173. projection.m00 = scale.mX;
  174. projection.m03 = offset.mX;
  175. projection.m11 = scale.mY;
  176. projection.m13 = offset.mY;
  177. projection.m22 = 1.0f;
  178. projection.m23 = 0.0f;
  179. projection.m33 = 1.0f;
  180. mRenderer->resetRenderTargets();
  181. mRenderer->setCullMode(CULL_CCW);
  182. mRenderer->setDepthTest(CMP_ALWAYS);
  183. mRenderer->setDepthWrite(false);
  184. mRenderer->setFillMode(FILL_SOLID);
  185. mRenderer->setStencilTest(false);
  186. mRenderer->setVertexShaderConstant(getVSRegister(VSP_MODELVIEWPROJ), projection);
  187. mRenderer->setPixelShaderConstant(getPSRegister(PSP_MATDIFFCOLOR), Color(1.0f, 1.0f, 1.0f, 1.0f));
  188. PixelShader* ps = 0;
  189. VertexShader* vs = 0;
  190. for (unsigned i = 0; i < mBatches.size(); ++i)
  191. {
  192. // Choose shaders here so that UIBatch does not need to look up shaders each time
  193. if (!mBatches[i].mTexture)
  194. {
  195. ps = mNoTexturePS;
  196. vs = mNoTextureVS;
  197. }
  198. else
  199. {
  200. // If texture contains only an alpha channel, use the alpha pixel shader
  201. vs = mDiffTextureVS;
  202. if (mBatches[i].mTexture->getFormat() == D3DFMT_A8)
  203. ps = mAlphaTexturePS;
  204. else
  205. ps = mDiffTexturePS;
  206. }
  207. mBatches[i].draw(mRenderer, vs, ps);
  208. }
  209. }
  210. void UI::addElementFactory(UIElementFactory* factory)
  211. {
  212. if (!factory)
  213. return;
  214. mFactories.push_back(SharedPtr<UIElementFactory>(factory));
  215. }
  216. SharedPtr<UIElement> UI::createElement(ShortStringHash type, const std::string& name)
  217. {
  218. SharedPtr<UIElement> element;
  219. for (unsigned i = 0; i < mFactories.size(); ++i)
  220. {
  221. element = mFactories[i]->createElement(type, name);
  222. if (element)
  223. return element;
  224. }
  225. EXCEPTION("Could not create unknown UI element type " + toString(type));
  226. }
  227. SharedPtr<UIElement> UI::loadLayout(XMLFile* file, XMLFile* styleFile)
  228. {
  229. PROFILE(UI_LoadLayout);
  230. SharedPtr<UIElement> root;
  231. if (!file)
  232. {
  233. LOGERROR("Null UI layout XML file");
  234. return root;
  235. }
  236. LOGDEBUG("Loading UI layout " + file->getName());
  237. XMLElement rootElem = file->getRootElement();
  238. XMLElement childElem = rootElem.getChildElement("element");
  239. if (!childElem)
  240. {
  241. LOGERROR("No root UI element in " + file->getName());
  242. return root;
  243. }
  244. root = createElement(ShortStringHash(childElem.getString("type")), childElem.getString("name"));
  245. // First set the base style from the style file if exists, then apply UI layout overrides
  246. if (styleFile)
  247. root->setStyleAuto(styleFile, mCache);
  248. root->setStyle(childElem, mCache);
  249. // Load rest of the elements recursively
  250. loadLayout(root, childElem, styleFile);
  251. if (childElem.getNextElement("element"))
  252. LOGWARNING("Ignored additional root UI elements in " + file->getName());
  253. return root;
  254. }
  255. UIElement* UI::getElementAt(const IntVector2& position, bool enabledOnly)
  256. {
  257. UIElement* result = 0;
  258. getElementAt(result, mRootElement, position, enabledOnly);
  259. return result;
  260. }
  261. UIElement* UI::getElementAt(int x, int y, bool enabledOnly)
  262. {
  263. UIElement* result = 0;
  264. getElementAt(result, mRootElement, IntVector2(x, y), enabledOnly);
  265. return result;
  266. }
  267. UIElement* UI::getFocusElement()
  268. {
  269. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  270. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  271. {
  272. if ((*i)->hasFocus())
  273. return *i;
  274. }
  275. return 0;
  276. }
  277. IntVector2 UI::getCursorPosition()
  278. {
  279. if (!mCursor)
  280. return IntVector2::sZero;
  281. else
  282. return mCursor->getPosition();
  283. }
  284. void UI::update(float timeStep, UIElement* element)
  285. {
  286. element->update(timeStep);
  287. const std::vector<UIElement*> children = element->getChildren();
  288. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  289. update(timeStep, *i);
  290. }
  291. void UI::getBatches(UIElement* element, IntRect currentScissor)
  292. {
  293. // If hidden, do not draw this element or its children
  294. if (!element->isVisible())
  295. return;
  296. element->getBatches(mBatches, mQuads, currentScissor);
  297. // Set clipping scissor for child elements, then get child element batches in low-to-high priority order
  298. element->adjustScissor(currentScissor);
  299. std::vector<UIElement*> children = element->getChildren();
  300. std::sort(children.begin(), children.end(), compareUIElements);
  301. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  302. getBatches(*i, currentScissor);
  303. }
  304. void UI::getElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  305. {
  306. if (!current)
  307. return;
  308. // Get children from lowest priority to highest
  309. std::vector<UIElement*> children = current->getChildren(false);
  310. std::sort(children.begin(), children.end(), compareUIElements);
  311. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  312. {
  313. UIElement* element = *i;
  314. if ((element != mCursor.getPtr()) && (element->isVisible()))
  315. {
  316. const IntVector2& screenPosition = element->getScreenPosition();
  317. const IntVector2& size = element->getSize();
  318. if ((position.mX >= screenPosition.mX) && (position.mX < screenPosition.mX + size.mX) &&
  319. (position.mY >= screenPosition.mY) && (position.mY < screenPosition.mY + size.mY))
  320. {
  321. // Store the current result, then recurse into its children. Because children
  322. // are sorted from lowest to highest priority, we should be left with the topmost match
  323. if ((element->isEnabled()) || (!enabledOnly))
  324. result = element;
  325. getElementAt(result, element, position, enabledOnly);
  326. }
  327. }
  328. }
  329. }
  330. UIElement* UI::verifyElement(UIElement* element)
  331. {
  332. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  333. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  334. {
  335. if ((*i) == element)
  336. return *i;
  337. }
  338. return 0;
  339. }
  340. void UI::handleWindowResized(StringHash eventType, VariantMap& eventData)
  341. {
  342. using namespace WindowResized;
  343. mRootElement->setSize(eventData[P_WIDTH].getInt(), eventData[P_HEIGHT].getInt());
  344. }
  345. void UI::handleMouseMove(StringHash eventType, VariantMap& eventData)
  346. {
  347. using namespace MouseMove;
  348. mMouseButtons = eventData[P_BUTTONS].getInt();
  349. if ((mCursor) && (mCursor->isVisible()))
  350. {
  351. IntVector2 pos = mCursor->getPosition();
  352. pos.mX += eventData[P_X].getInt();
  353. pos.mY += eventData[P_Y].getInt();
  354. IntVector2 rootSize = mRootElement->getSize();
  355. pos.mX = clamp(pos.mX, 0, rootSize.mX - 1);
  356. pos.mY = clamp(pos.mY, 0, rootSize.mY - 1);
  357. mCursor->setPosition(pos);
  358. if ((mMouseDrag) && (mMouseButtons))
  359. {
  360. UIElement* element = verifyElement(mMouseDragElement);
  361. if ((element) && (element->isEnabled()) && (element->isVisible()))
  362. element->onDragMove(element->screenToElement(pos), pos, mMouseButtons);
  363. else
  364. {
  365. mMouseDrag = false;
  366. mMouseDragElement = 0;
  367. }
  368. }
  369. }
  370. }
  371. void UI::handleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  372. {
  373. using namespace MouseButtonDown;
  374. mMouseButtons = eventData[P_BUTTONS].getInt();
  375. int button = eventData[P_BUTTON].getInt();
  376. if ((mCursor) && (mCursor->isVisible()))
  377. {
  378. IntVector2 pos = mCursor->getPosition();
  379. UIElement* element = getElementAt(pos);
  380. if (element)
  381. {
  382. // Handle focusing & bringing to front
  383. if (button == MOUSEB_LEFT)
  384. {
  385. setFocusElement(element);
  386. bringToFront(element);
  387. }
  388. // Handle click
  389. element->onClick(element->screenToElement(pos), pos, mMouseButtons);
  390. // Handle start of drag
  391. if (!mMouseDrag)
  392. {
  393. mMouseDrag = true;
  394. mMouseDragElement = element;
  395. element->onDragStart(element->screenToElement(pos), pos, mMouseButtons);
  396. }
  397. }
  398. }
  399. }
  400. void UI::handleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  401. {
  402. using namespace MouseButtonUp;
  403. mMouseButtons = eventData[P_BUTTONS].getInt();
  404. if ((mCursor) && (mCursor->isVisible()))
  405. {
  406. IntVector2 pos = mCursor->getPosition();
  407. if ((mMouseDrag) && (!mMouseButtons))
  408. {
  409. UIElement* element = verifyElement(mMouseDragElement);
  410. if ((element) && (element->isEnabled()) && (element->isVisible()))
  411. element->onDragEnd(element->screenToElement(pos), pos);
  412. mMouseDrag = false;
  413. mMouseDragElement = 0;
  414. }
  415. }
  416. }
  417. void UI::handleChar(StringHash eventType, VariantMap& eventData)
  418. {
  419. using namespace Char;
  420. UIElement* element = getFocusElement();
  421. if (element)
  422. element->onChar(eventData[P_CHAR].getInt());
  423. }
  424. void UI::loadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  425. {
  426. XMLElement childElem = elem.getChildElement("element");
  427. while (childElem)
  428. {
  429. SharedPtr<UIElement> child = createElement(ShortStringHash(childElem.getString("type")), childElem.getString("name"));
  430. // First set the base style from the style file if exists, then apply UI layout overrides
  431. if (styleFile)
  432. child->setStyleAuto(styleFile, mCache);
  433. child->setStyle(childElem, mCache);
  434. // Add to the hierarchy and recurse
  435. current->addChild(child);
  436. loadLayout(child, childElem, styleFile);
  437. childElem = childElem.getNextElement("element");
  438. }
  439. }