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. TBFile::SetReaderFunction(0);
  56. TBID::tbidRegisterCallback = 0;
  57. tb::TBWidgetsAnimationManager::Shutdown();
  58. widgetWrap_.Clear();
  59. delete rootWidget_;
  60. // leak
  61. //delete TBUIRenderer::renderer_;
  62. tb_core_shutdown();
  63. }
  64. uiContext_ = 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_->SetFillMode(FILL_SOLID);
  146. graphics_->SetStencilTest(false);
  147. graphics_->ResetRenderTargets();
  148. graphics_->SetVertexBuffer(buffer);
  149. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  150. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  151. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  152. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  153. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  154. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  155. unsigned alphaFormat = Graphics::GetAlphaFormat();
  156. for (unsigned i = batchStart; i < batchEnd; ++i)
  157. {
  158. const UIBatch& batch = batches[i];
  159. if (batch.vertexStart_ == batch.vertexEnd_)
  160. continue;
  161. ShaderVariation* ps;
  162. ShaderVariation* vs;
  163. if (!batch.texture_)
  164. {
  165. ps = noTexturePS;
  166. vs = noTextureVS;
  167. }
  168. else
  169. {
  170. // If texture contains only an alpha channel, use alpha shader (for fonts)
  171. vs = diffTextureVS;
  172. if (batch.texture_->GetFormat() == alphaFormat)
  173. ps = alphaTexturePS;
  174. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  175. ps = diffMaskTexturePS;
  176. else
  177. ps = diffTexturePS;
  178. }
  179. graphics_->SetShaders(vs, ps);
  180. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  181. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  182. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  183. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  184. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  185. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  186. graphics_->SetBlendMode(batch.blendMode_);
  187. graphics_->SetScissorTest(true, batch.scissor_);
  188. graphics_->SetTexture(0, batch.texture_);
  189. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  190. UI_VERTEX_SIZE);
  191. }
  192. }
  193. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  194. {
  195. if (vertexData.Empty())
  196. return;
  197. // Update quad geometry into the vertex buffer
  198. // Resize the vertex buffer first if too small or much too large
  199. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  200. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  201. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  202. dest->SetData(&vertexData[0]);
  203. }
  204. void UI::Render(bool resetRenderTargets)
  205. {
  206. SetVertexData(vertexBuffer_, vertexData_);
  207. Render(vertexBuffer_, batches_, 0, batches_.Size());
  208. }
  209. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  210. {
  211. // Get rendering batches from the non-modal UI elements
  212. batches_.Clear();
  213. vertexData_.Clear();
  214. tb::TBRect rect = rootWidget_->GetRect();
  215. IntRect currentScissor = IntRect(0, 0, rect.w, rect.h);
  216. GetBatches(batches_, vertexData_, currentScissor);
  217. }
  218. void UI::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  219. {
  220. //if (!initialized_)
  221. // return;
  222. TBAnimationManager::Update();
  223. rootWidget_->InvokeProcessStates();
  224. rootWidget_->InvokeProcess();
  225. tb::g_renderer->BeginPaint(rootWidget_->GetRect().w, rootWidget_->GetRect().h);
  226. renderer_->currentScissor_ = currentScissor;
  227. renderer_->batches_ = &batches;
  228. renderer_->vertexData_ = &vertexData;
  229. rootWidget_->InvokePaint(tb::TBWidget::PaintProps());
  230. tb::g_renderer->EndPaint();
  231. }
  232. void UI::SubmitBatchVertexData(Texture* texture, const PODVector<float>& vertexData)
  233. {
  234. UIBatch b(BLEND_ALPHA , renderer_->currentScissor_, texture, &vertexData_);
  235. unsigned begin = b.vertexData_->Size();
  236. b.vertexData_->Resize(begin + vertexData.Size());
  237. float* dest = &(b.vertexData_->At(begin));
  238. b.vertexEnd_ = b.vertexData_->Size();
  239. for (unsigned i = 0; i < vertexData.Size(); i++, dest++)
  240. {
  241. *dest = vertexData[i];
  242. }
  243. UIBatch::AddOrMerge(b, batches_);
  244. }
  245. void UI::TBFileReader(const char* filename, void** data, unsigned* length)
  246. {
  247. *data = 0;
  248. *length = 0;
  249. ResourceCache* cache = uiContext_->GetSubsystem<ResourceCache>();
  250. SharedPtr<File> file = cache->GetFile(filename);
  251. if (!file || !file->IsOpen())
  252. {
  253. LOGERRORF("UI::TBFileReader: Unable to load file: %s", filename);
  254. return;
  255. }
  256. unsigned size = file->GetSize();
  257. if (!size)
  258. return;
  259. void* _data = malloc(size);
  260. if (!_data)
  261. return;
  262. if (file->Read(_data, size) != size)
  263. {
  264. free(_data);
  265. return;
  266. }
  267. *length = size;
  268. *data = _data;
  269. }
  270. void UI::GetTBIDString(unsigned id, String& value)
  271. {
  272. if (!id)
  273. {
  274. value = "";
  275. }
  276. else
  277. {
  278. value = tbidToString_[id];
  279. }
  280. }
  281. void UI::TBIDRegisterStringCallback(unsigned id, const char* value)
  282. {
  283. uiContext_->GetSubsystem<UI>()->tbidToString_[id] = String(value);
  284. }
  285. bool UI::LoadResourceFile(TBWidget* widget, const String& filename)
  286. {
  287. tb::TBNode node;
  288. if (!node.ReadFile(filename.CString()))
  289. return false;
  290. tb::g_widgets_reader->LoadNodeTree(widget, &node);
  291. return true;
  292. }
  293. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  294. {
  295. using namespace ScreenMode;
  296. rootWidget_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  297. //SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  298. }
  299. void UI::HandleUpdate(StringHash eventType, VariantMap& eventData)
  300. {
  301. TBMessageHandler::ProcessMessages();
  302. }
  303. bool UI::IsWidgetWrapped(tb::TBWidget* widget)
  304. {
  305. return widgetWrap_.Contains(widget);
  306. }
  307. bool UI::UnwrapWidget(tb::TBWidget* widget)
  308. {
  309. if (widgetWrap_.Contains(widget))
  310. {
  311. widgetWrap_.Erase(widget);
  312. return true;
  313. }
  314. return false;
  315. }
  316. void UI::PruneUnreachableWidgets()
  317. {
  318. HashMap<tb::TBWidget*, SharedPtr<UIWidget>>::Iterator itr;
  319. for (itr = widgetWrap_.Begin(); itr != widgetWrap_.End(); )
  320. {
  321. if ((*itr).first_->GetParent() || (*itr).second_->JSGetHeapPtr())
  322. {
  323. itr++;
  324. continue;
  325. }
  326. tb::TBWidget* toDelete = (*itr).first_;
  327. itr.GotoNext();
  328. delete toDelete;
  329. // this will likely be flagged by valgrind as accessing invalid memory
  330. assert(!widgetWrap_.Contains(toDelete));
  331. }
  332. }
  333. void UI::WrapWidget(UIWidget* widget, tb::TBWidget* tbwidget)
  334. {
  335. assert (!widgetWrap_.Contains(tbwidget));
  336. widgetWrap_[tbwidget] = widget;
  337. }
  338. UIWidget* UI::WrapWidget(tb::TBWidget* widget)
  339. {
  340. if (widgetWrap_.Contains(widget))
  341. return widgetWrap_[widget];
  342. // switch this to use a factory?
  343. // this is order dependent as we're using IsOfType which also works if a base class
  344. if (widget->IsOfType<TBLayout>())
  345. {
  346. UILayout* layout = new UILayout(context_, false);
  347. layout->SetWidget(widget);
  348. widgetWrap_[widget] = layout;
  349. return layout;
  350. }
  351. if (widget->IsOfType<TBButton>())
  352. {
  353. // don't wrap the close button of a TBWindow.close
  354. if (widget->GetID() == TBIDC("TBWindow.close"))
  355. return 0;
  356. UIButton* button = new UIButton(context_, false);
  357. button->SetWidget(widget);
  358. widgetWrap_[widget] = button;
  359. return button;
  360. }
  361. if (widget->IsOfType<TBTextField>())
  362. {
  363. UITextField* textfield = new UITextField(context_, false);
  364. textfield->SetWidget(widget);
  365. widgetWrap_[widget] = textfield;
  366. return textfield;
  367. }
  368. if (widget->IsOfType<TBEditField>())
  369. {
  370. UIEditField* editfield = new UIEditField(context_, false);
  371. editfield->SetWidget(widget);
  372. widgetWrap_[widget] = editfield;
  373. return editfield;
  374. }
  375. if (widget->IsOfType<TBImageWidget>())
  376. {
  377. UIImageWidget* imagewidget = new UIImageWidget(context_, false);
  378. imagewidget->SetWidget(widget);
  379. widgetWrap_[widget] = imagewidget;
  380. return imagewidget;
  381. }
  382. if (widget->IsOfType<TBClickLabel>())
  383. {
  384. UIClickLabel* nwidget = new UIClickLabel(context_, false);
  385. nwidget->SetWidget(widget);
  386. widgetWrap_[widget] = nwidget;
  387. return nwidget;
  388. }
  389. if (widget->IsOfType<TBCheckBox>())
  390. {
  391. UICheckBox* nwidget = new UICheckBox(context_, false);
  392. nwidget->SetWidget(widget);
  393. widgetWrap_[widget] = nwidget;
  394. return nwidget;
  395. }
  396. if (widget->IsOfType<TBWidget>())
  397. {
  398. UIWidget* nwidget = new UIWidget(context_, false);
  399. nwidget->SetWidget(widget);
  400. widgetWrap_[widget] = nwidget;
  401. return nwidget;
  402. }
  403. return 0;
  404. }
  405. }