UI.cpp 11 KB

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