UI.cpp 12 KB

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