UI.cpp 16 KB

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