UI.cpp 14 KB

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