UI.cpp 15 KB

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