UI.cpp 16 KB

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