UI.cpp 17 KB

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