UI.cpp 13 KB

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