UI.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. #include <TurboBadger/tb_core.h>
  2. #include <TurboBadger/tb_system.h>
  3. #include <TurboBadger/tb_debug.h>
  4. #include <TurboBadger/animation/tb_widget_animation.h>
  5. #include <TurboBadger/renderers/tb_renderer_batcher.h>
  6. #include <TurboBadger/tb_font_renderer.h>
  7. #include <TurboBadger/tb_node_tree.h>
  8. #include <TurboBadger/tb_widgets_reader.h>
  9. #include <TurboBadger/tb_window.h>
  10. #include <TurboBadger/tb_message_window.h>
  11. #include <TurboBadger/tb_editfield.h>
  12. #include <TurboBadger/tb_select.h>
  13. #include <TurboBadger/tb_inline_select.h>
  14. #include <TurboBadger/tb_tab_container.h>
  15. #include <TurboBadger/tb_toggle_container.h>
  16. #include <TurboBadger/tb_scroll_container.h>
  17. #include <TurboBadger/image/tb_image_widget.h>
  18. void register_tbbf_font_renderer();
  19. void register_stb_font_renderer();
  20. void register_freetype_font_renderer();
  21. using namespace tb;
  22. #include "../Core/CoreEvents.h"
  23. #include "../IO/Log.h"
  24. #include "../Input/Input.h"
  25. #include "../Input/InputEvents.h"
  26. #include "../Resource/ResourceCache.h"
  27. #include "../Graphics/Graphics.h"
  28. #include "../Graphics/GraphicsEvents.h"
  29. #include "../Graphics/Texture2D.h"
  30. #include "../Graphics/VertexBuffer.h"
  31. #include "UIRenderer.h"
  32. #include "UI.h"
  33. #include "UIButton.h"
  34. #include "UITextField.h"
  35. #include "UIEditField.h"
  36. #include "UILayout.h"
  37. #include "UIImageWidget.h"
  38. #include "UIClickLabel.h"
  39. #include "UICheckBox.h"
  40. #include "UISelectList.h"
  41. #include "UIMessageWindow.h"
  42. #include "UISkinImage.h"
  43. #include "UITabContainer.h"
  44. #include "UISceneView.h"
  45. #include "UIDragDrop.h"
  46. #include "UIContainer.h"
  47. #include "UISection.h"
  48. #include "UIInlineSelect.h"
  49. #include "UIScrollContainer.h"
  50. namespace tb
  51. {
  52. void TBSystem::RescheduleTimer(double fire_time)
  53. {
  54. }
  55. }
  56. namespace Atomic
  57. {
  58. WeakPtr<Context> UI::uiContext_;
  59. UI::UI(Context* context) :
  60. Object(context),
  61. rootWidget_(0),
  62. inputDisabled_(false),
  63. keyboardDisabled_(false),
  64. initialized_(false)
  65. {
  66. }
  67. UI::~UI()
  68. {
  69. if (initialized_)
  70. {
  71. TBFile::SetReaderFunction(0);
  72. TBID::tbidRegisterCallback = 0;
  73. tb::TBWidgetsAnimationManager::Shutdown();
  74. widgetWrap_.Clear();
  75. delete rootWidget_;
  76. // leak
  77. //delete TBUIRenderer::renderer_;
  78. tb_core_shutdown();
  79. }
  80. uiContext_ = 0;
  81. }
  82. void UI::Shutdown()
  83. {
  84. SetInputDisabled(true);
  85. }
  86. void UI::Initialize(const String& languageFile)
  87. {
  88. Graphics* graphics = GetSubsystem<Graphics>();
  89. assert(graphics);
  90. assert(graphics->IsInitialized());
  91. graphics_ = graphics;
  92. vertexBuffer_ = new VertexBuffer(context_);
  93. uiContext_ = context_;
  94. TBFile::SetReaderFunction(TBFileReader);
  95. TBID::tbidRegisterCallback = UI::TBIDRegisterStringCallback;
  96. TBWidgetsAnimationManager::Init();
  97. renderer_ = new UIRenderer(graphics_->GetContext());
  98. tb_core_init(renderer_, languageFile.CString());
  99. //register_tbbf_font_renderer();
  100. //register_stb_font_renderer();
  101. register_freetype_font_renderer();
  102. rootWidget_ = new TBWidget();
  103. int width = graphics_->GetWidth();
  104. int height = graphics_->GetHeight();
  105. rootWidget_->SetSize(width, height);
  106. rootWidget_->SetVisibilility(tb::WIDGET_VISIBILITY_VISIBLE);
  107. // register the UIDragDrop subsystem
  108. context_->RegisterSubsystem(new UIDragDrop(context_));
  109. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  110. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  111. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  112. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  113. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  114. SubscribeToEvent(E_KEYUP, HANDLER(UI, HandleKeyUp));
  115. SubscribeToEvent(E_TEXTINPUT, HANDLER(UI, HandleTextInput));
  116. SubscribeToEvent(E_UPDATE, HANDLER(UI, HandleUpdate));
  117. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  118. initialized_ = true;
  119. //TB_DEBUG_SETTING(LAYOUT_BOUNDS) = 1;
  120. }
  121. void UI::LoadSkin(const String& skin, const String& overrideSkin)
  122. {
  123. // Load the default skin, and override skin
  124. tb::g_tb_skin->Load(skin.CString(), overrideSkin.CString());
  125. }
  126. void UI::SetDefaultFont(const String& name, int size)
  127. {
  128. tb::TBFontDescription fd;
  129. fd.SetID(tb::TBIDC(name.CString()));
  130. fd.SetSize(tb::g_tb_skin->GetDimensionConverter()->DpToPx(12));
  131. tb::g_font_manager->SetDefaultFontDescription(fd);
  132. // Create the font now.
  133. tb::TBFontFace *font = tb::g_font_manager->CreateFontFace(tb::g_font_manager->GetDefaultFontDescription());
  134. // Render some glyphs in one go now since we know we are going to use them. It would work fine
  135. // without this since glyphs are rendered when needed, but with some extra updating of the glyph bitmap.
  136. if (font)
  137. font->RenderGlyphs(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~•·åäöÅÄÖ");
  138. }
  139. void UI::AddFont(const String& fontFile, const String& name)
  140. {
  141. tb::g_font_manager->AddFontInfo(fontFile.CString(), name.CString());
  142. }
  143. void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  144. {
  145. if (batches.Empty())
  146. return;
  147. Vector2 invScreenSize(1.0f / (float)graphics_->GetWidth(), 1.0f / (float)graphics_->GetHeight());
  148. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  149. Vector2 offset(-1.0f, 1.0f);
  150. Matrix4 projection(Matrix4::IDENTITY);
  151. projection.m00_ = scale.x_;
  152. projection.m03_ = offset.x_;
  153. projection.m11_ = scale.y_;
  154. projection.m13_ = offset.y_;
  155. projection.m22_ = 1.0f;
  156. projection.m23_ = 0.0f;
  157. projection.m33_ = 1.0f;
  158. graphics_->ClearParameterSources();
  159. graphics_->SetColorWrite(true);
  160. graphics_->SetCullMode(CULL_NONE);
  161. graphics_->SetDepthTest(CMP_ALWAYS);
  162. graphics_->SetDepthWrite(false);
  163. graphics_->SetFillMode(FILL_SOLID);
  164. graphics_->SetStencilTest(false);
  165. graphics_->ResetRenderTargets();
  166. graphics_->SetVertexBuffer(buffer);
  167. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  168. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  169. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  170. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  171. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  172. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  173. unsigned alphaFormat = Graphics::GetAlphaFormat();
  174. for (unsigned i = batchStart; i < batchEnd; ++i)
  175. {
  176. const UIBatch& batch = batches[i];
  177. if (batch.vertexStart_ == batch.vertexEnd_)
  178. continue;
  179. ShaderVariation* ps;
  180. ShaderVariation* vs;
  181. if (!batch.texture_)
  182. {
  183. ps = noTexturePS;
  184. vs = noTextureVS;
  185. }
  186. else
  187. {
  188. // If texture contains only an alpha channel, use alpha shader (for fonts)
  189. vs = diffTextureVS;
  190. if (batch.texture_->GetFormat() == alphaFormat)
  191. ps = alphaTexturePS;
  192. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  193. ps = diffMaskTexturePS;
  194. else
  195. ps = diffTexturePS;
  196. }
  197. graphics_->SetShaders(vs, ps);
  198. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  199. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  200. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  201. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  202. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  203. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  204. graphics_->SetBlendMode(batch.blendMode_);
  205. graphics_->SetScissorTest(true, batch.scissor_);
  206. graphics_->SetTexture(0, batch.texture_);
  207. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  208. UI_VERTEX_SIZE);
  209. }
  210. }
  211. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  212. {
  213. if (vertexData.Empty())
  214. return;
  215. // Update quad geometry into the vertex buffer
  216. // Resize the vertex buffer first if too small or much too large
  217. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  218. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  219. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  220. dest->SetData(&vertexData[0]);
  221. }
  222. void UI::Render(bool resetRenderTargets)
  223. {
  224. SetVertexData(vertexBuffer_, vertexData_);
  225. Render(vertexBuffer_, batches_, 0, batches_.Size());
  226. }
  227. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  228. {
  229. // Get rendering batches from the non-modal UI elements
  230. batches_.Clear();
  231. vertexData_.Clear();
  232. tb::TBRect rect = rootWidget_->GetRect();
  233. IntRect currentScissor = IntRect(0, 0, rect.w, rect.h);
  234. GetBatches(batches_, vertexData_, currentScissor);
  235. }
  236. void UI::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  237. {
  238. //if (!initialized_)
  239. // return;
  240. TBAnimationManager::Update();
  241. rootWidget_->InvokeProcessStates();
  242. rootWidget_->InvokeProcess();
  243. tb::g_renderer->BeginPaint(rootWidget_->GetRect().w, rootWidget_->GetRect().h);
  244. renderer_->currentScissor_ = currentScissor;
  245. renderer_->batches_ = &batches;
  246. renderer_->vertexData_ = &vertexData;
  247. rootWidget_->InvokePaint(tb::TBWidget::PaintProps());
  248. tb::g_renderer->EndPaint();
  249. }
  250. void UI::SubmitBatchVertexData(Texture* texture, const PODVector<float>& vertexData)
  251. {
  252. UIBatch b(BLEND_ALPHA , renderer_->currentScissor_, texture, &vertexData_);
  253. unsigned begin = b.vertexData_->Size();
  254. b.vertexData_->Resize(begin + vertexData.Size());
  255. float* dest = &(b.vertexData_->At(begin));
  256. b.vertexEnd_ = b.vertexData_->Size();
  257. for (unsigned i = 0; i < vertexData.Size(); i++, dest++)
  258. {
  259. *dest = vertexData[i];
  260. }
  261. UIBatch::AddOrMerge(b, batches_);
  262. }
  263. void UI::TBFileReader(const char* filename, void** data, unsigned* length)
  264. {
  265. *data = 0;
  266. *length = 0;
  267. ResourceCache* cache = uiContext_->GetSubsystem<ResourceCache>();
  268. SharedPtr<File> file = cache->GetFile(filename);
  269. if (!file || !file->IsOpen())
  270. {
  271. LOGERRORF("UI::TBFileReader: Unable to load file: %s", filename);
  272. return;
  273. }
  274. unsigned size = file->GetSize();
  275. if (!size)
  276. return;
  277. void* _data = malloc(size);
  278. if (!_data)
  279. return;
  280. if (file->Read(_data, size) != size)
  281. {
  282. free(_data);
  283. return;
  284. }
  285. *length = size;
  286. *data = _data;
  287. }
  288. void UI::GetTBIDString(unsigned id, String& value)
  289. {
  290. if (!id)
  291. {
  292. value = "";
  293. }
  294. else
  295. {
  296. value = tbidToString_[id];
  297. }
  298. }
  299. void UI::TBIDRegisterStringCallback(unsigned id, const char* value)
  300. {
  301. uiContext_->GetSubsystem<UI>()->tbidToString_[id] = String(value);
  302. }
  303. bool UI::LoadResourceFile(TBWidget* widget, const String& filename)
  304. {
  305. tb::TBNode node;
  306. if (!node.ReadFile(filename.CString()))
  307. return false;
  308. tb::g_widgets_reader->LoadNodeTree(widget, &node);
  309. return true;
  310. }
  311. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  312. {
  313. using namespace ScreenMode;
  314. rootWidget_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  315. //SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  316. }
  317. void UI::HandleUpdate(StringHash eventType, VariantMap& eventData)
  318. {
  319. TBMessageHandler::ProcessMessages();
  320. }
  321. bool UI::IsWidgetWrapped(tb::TBWidget* widget)
  322. {
  323. return widgetWrap_.Contains(widget);
  324. }
  325. bool UI::UnwrapWidget(tb::TBWidget* widget)
  326. {
  327. if (widgetWrap_.Contains(widget))
  328. {
  329. widgetWrap_.Erase(widget);
  330. return true;
  331. }
  332. return false;
  333. }
  334. void UI::PruneUnreachableWidgets()
  335. {
  336. HashMap<tb::TBWidget*, SharedPtr<UIWidget>>::Iterator itr;
  337. for (itr = widgetWrap_.Begin(); itr != widgetWrap_.End(); )
  338. {
  339. if ((*itr).first_->GetParent() || (*itr).second_->JSGetHeapPtr())
  340. {
  341. itr++;
  342. continue;
  343. }
  344. tb::TBWidget* toDelete = (*itr).first_;
  345. itr.GotoNext();
  346. delete toDelete;
  347. // this will likely be flagged by valgrind as accessing invalid memory
  348. assert(!widgetWrap_.Contains(toDelete));
  349. }
  350. }
  351. void UI::WrapWidget(UIWidget* widget, tb::TBWidget* tbwidget)
  352. {
  353. assert (!widgetWrap_.Contains(tbwidget));
  354. widgetWrap_[tbwidget] = widget;
  355. }
  356. UIWidget* UI::WrapWidget(tb::TBWidget* widget)
  357. {
  358. if (!widget)
  359. return NULL;
  360. if (widgetWrap_.Contains(widget))
  361. return widgetWrap_[widget];
  362. // switch this to use a factory?
  363. // this is order dependent as we're using IsOfType which also works if a base class
  364. if (widget->IsOfType<TBScrollContainer>())
  365. {
  366. UIScrollContainer* container = new UIScrollContainer(context_, false);
  367. container->SetWidget(widget);
  368. widgetWrap_[widget] = container;
  369. return container;
  370. }
  371. if (widget->IsOfType<TBInlineSelect>())
  372. {
  373. UIInlineSelect* select = new UIInlineSelect(context_, false);
  374. select->SetWidget(widget);
  375. widgetWrap_[widget] = select;
  376. return select;
  377. }
  378. if (widget->IsOfType<TBSection>())
  379. {
  380. UISection* section = new UISection(context_, false);
  381. section->SetWidget(widget);
  382. widgetWrap_[widget] = section;
  383. return section;
  384. }
  385. if (widget->IsOfType<TBContainer>())
  386. {
  387. UIContainer* container = new UIContainer(context_, false);
  388. container->SetWidget(widget);
  389. widgetWrap_[widget] = container;
  390. return container;
  391. }
  392. if (widget->IsOfType<TBButton>())
  393. {
  394. // don't wrap the close button of a TBWindow.close
  395. if (widget->GetID() == TBIDC("TBWindow.close"))
  396. return 0;
  397. UIButton* button = new UIButton(context_, false);
  398. button->SetWidget(widget);
  399. widgetWrap_[widget] = button;
  400. return button;
  401. }
  402. if (widget->IsOfType<TBTextField>())
  403. {
  404. UITextField* textfield = new UITextField(context_, false);
  405. textfield->SetWidget(widget);
  406. widgetWrap_[widget] = textfield;
  407. return textfield;
  408. }
  409. if (widget->IsOfType<TBEditField>())
  410. {
  411. UIEditField* editfield = new UIEditField(context_, false);
  412. editfield->SetWidget(widget);
  413. widgetWrap_[widget] = editfield;
  414. return editfield;
  415. }
  416. if (widget->IsOfType<TBSkinImage>())
  417. {
  418. UISkinImage* skinimage = new UISkinImage(context_, "", false);
  419. skinimage->SetWidget(widget);
  420. widgetWrap_[widget] = skinimage;
  421. return skinimage;
  422. }
  423. if (widget->IsOfType<TBImageWidget>())
  424. {
  425. UIImageWidget* imagewidget = new UIImageWidget(context_, false);
  426. imagewidget->SetWidget(widget);
  427. widgetWrap_[widget] = imagewidget;
  428. return imagewidget;
  429. }
  430. if (widget->IsOfType<TBClickLabel>())
  431. {
  432. UIClickLabel* nwidget = new UIClickLabel(context_, false);
  433. nwidget->SetWidget(widget);
  434. widgetWrap_[widget] = nwidget;
  435. return nwidget;
  436. }
  437. if (widget->IsOfType<TBCheckBox>())
  438. {
  439. UICheckBox* nwidget = new UICheckBox(context_, false);
  440. nwidget->SetWidget(widget);
  441. widgetWrap_[widget] = nwidget;
  442. return nwidget;
  443. }
  444. if (widget->IsOfType<TBSelectList>())
  445. {
  446. UISelectList* nwidget = new UISelectList(context_, false);
  447. nwidget->SetWidget(widget);
  448. widgetWrap_[widget] = nwidget;
  449. return nwidget;
  450. }
  451. if (widget->IsOfType<TBMessageWindow>())
  452. {
  453. UIMessageWindow* nwidget = new UIMessageWindow(context_, NULL, "", false);
  454. nwidget->SetWidget(widget);
  455. widgetWrap_[widget] = nwidget;
  456. return nwidget;
  457. }
  458. if (widget->IsOfType<TBTabContainer>())
  459. {
  460. UITabContainer* nwidget = new UITabContainer(context_, false);
  461. nwidget->SetWidget(widget);
  462. widgetWrap_[widget] = nwidget;
  463. return nwidget;
  464. }
  465. if (widget->IsOfType<SceneViewWidget>())
  466. {
  467. UISceneView* nwidget = new UISceneView(context_, false);
  468. nwidget->SetWidget(widget);
  469. widgetWrap_[widget] = nwidget;
  470. return nwidget;
  471. }
  472. if (widget->IsOfType<TBLayout>())
  473. {
  474. UILayout* layout = new UILayout(context_, (UI_AXIS) widget->GetAxis(), false);
  475. layout->SetWidget(widget);
  476. widgetWrap_[widget] = layout;
  477. return layout;
  478. }
  479. if (widget->IsOfType<TBWidget>())
  480. {
  481. UIWidget* nwidget = new UIWidget(context_, false);
  482. nwidget->SetWidget(widget);
  483. widgetWrap_[widget] = nwidget;
  484. return nwidget;
  485. }
  486. return 0;
  487. }
  488. }