UI.cpp 17 KB

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