UI.cpp 15 KB

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