1 /*
2  * Copyright 2014-2015 Daniel Collin. All rights reserved.
3  * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
4  */
5 
6 #include <bgfx/bgfx.h>
7 #include <bgfx/embedded_shader.h>
8 #include <bx/allocator.h>
9 #include <bx/math.h>
10 #include <bx/timer.h>
11 #include <dear-imgui/imgui.h>
12 
13 #include "imgui.h"
14 #include "../bgfx_utils.h"
15 
16 //#define USE_ENTRY 1
17 
18 #ifndef USE_ENTRY
19 #	define USE_ENTRY 0
20 #endif // USE_ENTRY
21 
22 #if USE_ENTRY
23 #	include "../entry/entry.h"
24 #	include "../entry/input.h"
25 #endif // USE_ENTRY
26 
27 #include "vs_ocornut_imgui.bin.h"
28 #include "fs_ocornut_imgui.bin.h"
29 #include "vs_imgui_image.bin.h"
30 #include "fs_imgui_image.bin.h"
31 
32 #include "roboto_regular.ttf.h"
33 #include "robotomono_regular.ttf.h"
34 #include "icons_kenney.ttf.h"
35 #include "icons_font_awesome.ttf.h"
36 
37 static const bgfx::EmbeddedShader s_embeddedShaders[] =
38 {
39 	BGFX_EMBEDDED_SHADER(vs_ocornut_imgui),
40 	BGFX_EMBEDDED_SHADER(fs_ocornut_imgui),
41 	BGFX_EMBEDDED_SHADER(vs_imgui_image),
42 	BGFX_EMBEDDED_SHADER(fs_imgui_image),
43 
44 	BGFX_EMBEDDED_SHADER_END()
45 };
46 
47 struct FontRangeMerge
48 {
49 	const void* data;
50 	size_t      size;
51 	ImWchar     ranges[3];
52 };
53 
54 static FontRangeMerge s_fontRangeMerge[] =
55 {
56 	{ s_iconsKenneyTtf,      sizeof(s_iconsKenneyTtf),      { ICON_MIN_KI, ICON_MAX_KI, 0 } },
57 	{ s_iconsFontAwesomeTtf, sizeof(s_iconsFontAwesomeTtf), { ICON_MIN_FA, ICON_MAX_FA, 0 } },
58 };
59 
60 static void* memAlloc(size_t _size, void* _userData);
61 static void memFree(void* _ptr, void* _userData);
62 
63 struct OcornutImguiContext
64 {
renderOcornutImguiContext65 	void render(ImDrawData* _drawData)
66 	{
67 		const ImGuiIO& io = ImGui::GetIO();
68 		const float width  = io.DisplaySize.x;
69 		const float height = io.DisplaySize.y;
70 
71 		bgfx::setViewName(m_viewId, "ImGui");
72 		bgfx::setViewMode(m_viewId, bgfx::ViewMode::Sequential);
73 
74 		const bgfx::Caps* caps = bgfx::getCaps();
75 		{
76 			float ortho[16];
77 			bx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
78 			bgfx::setViewTransform(m_viewId, NULL, ortho);
79 			bgfx::setViewRect(m_viewId, 0, 0, uint16_t(width), uint16_t(height) );
80 		}
81 
82 		// Render command lists
83 		for (int32_t ii = 0, num = _drawData->CmdListsCount; ii < num; ++ii)
84 		{
85 			bgfx::TransientVertexBuffer tvb;
86 			bgfx::TransientIndexBuffer tib;
87 
88 			const ImDrawList* drawList = _drawData->CmdLists[ii];
89 			uint32_t numVertices = (uint32_t)drawList->VtxBuffer.size();
90 			uint32_t numIndices  = (uint32_t)drawList->IdxBuffer.size();
91 
92 			if (!checkAvailTransientBuffers(numVertices, m_layout, numIndices) )
93 			{
94 				// not enough space in transient buffer just quit drawing the rest...
95 				break;
96 			}
97 
98 			bgfx::allocTransientVertexBuffer(&tvb, numVertices, m_layout);
99 			bgfx::allocTransientIndexBuffer(&tib, numIndices);
100 
101 			ImDrawVert* verts = (ImDrawVert*)tvb.data;
102 			bx::memCopy(verts, drawList->VtxBuffer.begin(), numVertices * sizeof(ImDrawVert) );
103 
104 			ImDrawIdx* indices = (ImDrawIdx*)tib.data;
105 			bx::memCopy(indices, drawList->IdxBuffer.begin(), numIndices * sizeof(ImDrawIdx) );
106 
107 			uint32_t offset = 0;
108 			for (const ImDrawCmd* cmd = drawList->CmdBuffer.begin(), *cmdEnd = drawList->CmdBuffer.end(); cmd != cmdEnd; ++cmd)
109 			{
110 				if (cmd->UserCallback)
111 				{
112 					cmd->UserCallback(drawList, cmd);
113 				}
114 				else if (0 != cmd->ElemCount)
115 				{
116 					uint64_t state = 0
117 						| BGFX_STATE_WRITE_RGB
118 						| BGFX_STATE_WRITE_A
119 						| BGFX_STATE_MSAA
120 						;
121 
122 					bgfx::TextureHandle th = m_texture;
123 					bgfx::ProgramHandle program = m_program;
124 
125 					if (NULL != cmd->TextureId)
126 					{
127 						union { ImTextureID ptr; struct { bgfx::TextureHandle handle; uint8_t flags; uint8_t mip; } s; } texture = { cmd->TextureId };
128 						state |= 0 != (IMGUI_FLAGS_ALPHA_BLEND & texture.s.flags)
129 							? BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
130 							: BGFX_STATE_NONE
131 							;
132 						th = texture.s.handle;
133 						if (0 != texture.s.mip)
134 						{
135 							const float lodEnabled[4] = { float(texture.s.mip), 1.0f, 0.0f, 0.0f };
136 							bgfx::setUniform(u_imageLodEnabled, lodEnabled);
137 							program = m_imageProgram;
138 						}
139 					}
140 					else
141 					{
142 						state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
143 					}
144 
145 					const uint16_t xx = uint16_t(bx::max(cmd->ClipRect.x, 0.0f) );
146 					const uint16_t yy = uint16_t(bx::max(cmd->ClipRect.y, 0.0f) );
147 					bgfx::setScissor(xx, yy
148 						, uint16_t(bx::min(cmd->ClipRect.z, 65535.0f)-xx)
149 						, uint16_t(bx::min(cmd->ClipRect.w, 65535.0f)-yy)
150 						);
151 
152 					bgfx::setState(state);
153 					bgfx::setTexture(0, s_tex, th);
154 					bgfx::setVertexBuffer(0, &tvb, 0, numVertices);
155 					bgfx::setIndexBuffer(&tib, offset, cmd->ElemCount);
156 					bgfx::submit(m_viewId, program);
157 				}
158 
159 				offset += cmd->ElemCount;
160 			}
161 		}
162 	}
163 
createOcornutImguiContext164 	void create(float _fontSize, bx::AllocatorI* _allocator)
165 	{
166 		m_allocator = _allocator;
167 
168 		if (NULL == _allocator)
169 		{
170 			static bx::DefaultAllocator allocator;
171 			m_allocator = &allocator;
172 		}
173 
174 		m_viewId = 255;
175 		m_lastScroll = 0;
176 		m_last = bx::getHPCounter();
177 
178 		ImGui::SetAllocatorFunctions(memAlloc, memFree, NULL);
179 
180 		m_imgui = ImGui::CreateContext();
181 
182 		ImGuiIO& io = ImGui::GetIO();
183 
184 		io.DisplaySize = ImVec2(1280.0f, 720.0f);
185 		io.DeltaTime   = 1.0f / 60.0f;
186 		io.IniFilename = NULL;
187 
188 		setupStyle(true);
189 
190 #if USE_ENTRY
191 		io.KeyMap[ImGuiKey_Tab]        = (int)entry::Key::Tab;
192 		io.KeyMap[ImGuiKey_LeftArrow]  = (int)entry::Key::Left;
193 		io.KeyMap[ImGuiKey_RightArrow] = (int)entry::Key::Right;
194 		io.KeyMap[ImGuiKey_UpArrow]    = (int)entry::Key::Up;
195 		io.KeyMap[ImGuiKey_DownArrow]  = (int)entry::Key::Down;
196 		io.KeyMap[ImGuiKey_PageUp]     = (int)entry::Key::PageUp;
197 		io.KeyMap[ImGuiKey_PageDown]   = (int)entry::Key::PageDown;
198 		io.KeyMap[ImGuiKey_Home]       = (int)entry::Key::Home;
199 		io.KeyMap[ImGuiKey_End]        = (int)entry::Key::End;
200 		io.KeyMap[ImGuiKey_Insert]     = (int)entry::Key::Insert;
201 		io.KeyMap[ImGuiKey_Delete]     = (int)entry::Key::Delete;
202 		io.KeyMap[ImGuiKey_Backspace]  = (int)entry::Key::Backspace;
203 		io.KeyMap[ImGuiKey_Space]      = (int)entry::Key::Space;
204 		io.KeyMap[ImGuiKey_Enter]      = (int)entry::Key::Return;
205 		io.KeyMap[ImGuiKey_Escape]     = (int)entry::Key::Esc;
206 		io.KeyMap[ImGuiKey_A]          = (int)entry::Key::KeyA;
207 		io.KeyMap[ImGuiKey_C]          = (int)entry::Key::KeyC;
208 		io.KeyMap[ImGuiKey_V]          = (int)entry::Key::KeyV;
209 		io.KeyMap[ImGuiKey_X]          = (int)entry::Key::KeyX;
210 		io.KeyMap[ImGuiKey_Y]          = (int)entry::Key::KeyY;
211 		io.KeyMap[ImGuiKey_Z]          = (int)entry::Key::KeyZ;
212 
213 		io.ConfigFlags |= 0
214 			| ImGuiConfigFlags_NavEnableGamepad
215 			| ImGuiConfigFlags_NavEnableKeyboard
216 			;
217 
218 		io.NavInputs[ImGuiNavInput_Activate]    = (int)entry::Key::GamepadA;
219 		io.NavInputs[ImGuiNavInput_Cancel]      = (int)entry::Key::GamepadB;
220 //		io.NavInputs[ImGuiNavInput_Input]       = (int)entry::Key::;
221 //		io.NavInputs[ImGuiNavInput_Menu]        = (int)entry::Key::;
222 		io.NavInputs[ImGuiNavInput_DpadLeft]    = (int)entry::Key::GamepadLeft;
223 		io.NavInputs[ImGuiNavInput_DpadRight]   = (int)entry::Key::GamepadRight;
224 		io.NavInputs[ImGuiNavInput_DpadUp]      = (int)entry::Key::GamepadUp;
225 		io.NavInputs[ImGuiNavInput_DpadDown]    = (int)entry::Key::GamepadDown;
226 //		io.NavInputs[ImGuiNavInput_LStickLeft]  = (int)entry::Key::;
227 //		io.NavInputs[ImGuiNavInput_LStickRight] = (int)entry::Key::;
228 //		io.NavInputs[ImGuiNavInput_LStickUp]    = (int)entry::Key::;
229 //		io.NavInputs[ImGuiNavInput_LStickDown]  = (int)entry::Key::;
230 //		io.NavInputs[ImGuiNavInput_FocusPrev]   = (int)entry::Key::;
231 //		io.NavInputs[ImGuiNavInput_FocusNext]   = (int)entry::Key::;
232 //		io.NavInputs[ImGuiNavInput_TweakSlow]   = (int)entry::Key::;
233 //		io.NavInputs[ImGuiNavInput_TweakFast]   = (int)entry::Key::;
234 #endif // USE_ENTRY
235 
236 		bgfx::RendererType::Enum type = bgfx::getRendererType();
237 		m_program = bgfx::createProgram(
238 			  bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_ocornut_imgui")
239 			, bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_ocornut_imgui")
240 			, true
241 			);
242 
243 		u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
244 		m_imageProgram = bgfx::createProgram(
245 			  bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_imgui_image")
246 			, bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_imgui_image")
247 			, true
248 			);
249 
250 		m_layout
251 			.begin()
252 			.add(bgfx::Attrib::Position,  2, bgfx::AttribType::Float)
253 			.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
254 			.add(bgfx::Attrib::Color0,    4, bgfx::AttribType::Uint8, true)
255 			.end();
256 
257 		s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Sampler);
258 
259 		uint8_t* data;
260 		int32_t width;
261 		int32_t height;
262 		{
263 			ImFontConfig config;
264 			config.FontDataOwnedByAtlas = false;
265 			config.MergeMode = false;
266 //			config.MergeGlyphCenterV = true;
267 
268 			const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
269 			m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf,     sizeof(s_robotoRegularTtf),     _fontSize,      &config, ranges);
270 			m_font[ImGui::Font::Mono   ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
271 
272 			config.MergeMode = true;
273 			config.DstFont   = m_font[ImGui::Font::Regular];
274 
275 			for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
276 			{
277 				const FontRangeMerge& frm = s_fontRangeMerge[ii];
278 
279 				io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
280 						, (int)frm.size
281 						, _fontSize-3.0f
282 						, &config
283 						, frm.ranges
284 						);
285 			}
286 		}
287 
288 		io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
289 
290 		m_texture = bgfx::createTexture2D(
291 			  (uint16_t)width
292 			, (uint16_t)height
293 			, false
294 			, 1
295 			, bgfx::TextureFormat::BGRA8
296 			, 0
297 			, bgfx::copy(data, width*height*4)
298 			);
299 
300 		ImGui::InitDockContext();
301 	}
302 
destroyOcornutImguiContext303 	void destroy()
304 	{
305 		ImGui::ShutdownDockContext();
306 		ImGui::DestroyContext(m_imgui);
307 
308 		bgfx::destroy(s_tex);
309 		bgfx::destroy(m_texture);
310 
311 		bgfx::destroy(u_imageLodEnabled);
312 		bgfx::destroy(m_imageProgram);
313 		bgfx::destroy(m_program);
314 
315 		m_allocator = NULL;
316 	}
317 
setupStyleOcornutImguiContext318 	void setupStyle(bool _dark)
319 	{
320 		// Doug Binks' darl color scheme
321 		// https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
322 		ImGuiStyle& style = ImGui::GetStyle();
323 		if (_dark)
324 		{
325 			ImGui::StyleColorsDark(&style);
326 		}
327 		else
328 		{
329 			ImGui::StyleColorsLight(&style);
330 		}
331 
332 		style.FrameRounding    = 4.0f;
333 		style.WindowBorderSize = 0.0f;
334 	}
335 
beginFrameOcornutImguiContext336 	void beginFrame(
337 		  int32_t _mx
338 		, int32_t _my
339 		, uint8_t _button
340 		, int32_t _scroll
341 		, int _width
342 		, int _height
343 		, int _inputChar
344 		, bgfx::ViewId _viewId
345 		)
346 	{
347 		m_viewId = _viewId;
348 
349 		ImGuiIO& io = ImGui::GetIO();
350 		if (_inputChar >= 0)
351 		{
352 			io.AddInputCharacter(_inputChar);
353 		}
354 
355 		io.DisplaySize = ImVec2( (float)_width, (float)_height);
356 
357 		const int64_t now = bx::getHPCounter();
358 		const int64_t frameTime = now - m_last;
359 		m_last = now;
360 		const double freq = double(bx::getHPFrequency() );
361 		io.DeltaTime = float(frameTime/freq);
362 
363 		io.MousePos = ImVec2( (float)_mx, (float)_my);
364 		io.MouseDown[0] = 0 != (_button & IMGUI_MBUT_LEFT);
365 		io.MouseDown[1] = 0 != (_button & IMGUI_MBUT_RIGHT);
366 		io.MouseDown[2] = 0 != (_button & IMGUI_MBUT_MIDDLE);
367 		io.MouseWheel = (float)(_scroll - m_lastScroll);
368 		m_lastScroll = _scroll;
369 
370 #if USE_ENTRY
371 		uint8_t modifiers = inputGetModifiersState();
372 		io.KeyShift = 0 != (modifiers & (entry::Modifier::LeftShift | entry::Modifier::RightShift) );
373 		io.KeyCtrl  = 0 != (modifiers & (entry::Modifier::LeftCtrl  | entry::Modifier::RightCtrl ) );
374 		io.KeyAlt   = 0 != (modifiers & (entry::Modifier::LeftAlt   | entry::Modifier::RightAlt  ) );
375 		for (int32_t ii = 0; ii < (int32_t)entry::Key::Count; ++ii)
376 		{
377 			io.KeysDown[ii] = inputGetKeyState(entry::Key::Enum(ii) );
378 		}
379 #endif // USE_ENTRY
380 
381 		ImGui::NewFrame();
382 
383 		ImGuizmo::BeginFrame();
384 	}
385 
endFrameOcornutImguiContext386 	void endFrame()
387 	{
388 		ImGui::Render();
389 		render(ImGui::GetDrawData() );
390 	}
391 
392 	ImGuiContext*       m_imgui;
393 	bx::AllocatorI*     m_allocator;
394 	bgfx::VertexLayout  m_layout;
395 	bgfx::ProgramHandle m_program;
396 	bgfx::ProgramHandle m_imageProgram;
397 	bgfx::TextureHandle m_texture;
398 	bgfx::UniformHandle s_tex;
399 	bgfx::UniformHandle u_imageLodEnabled;
400 	ImFont* m_font[ImGui::Font::Count];
401 	int64_t m_last;
402 	int32_t m_lastScroll;
403 	bgfx::ViewId m_viewId;
404 };
405 
406 static OcornutImguiContext s_ctx;
407 
memAlloc(size_t _size,void * _userData)408 static void* memAlloc(size_t _size, void* _userData)
409 {
410 	BX_UNUSED(_userData);
411 	return BX_ALLOC(s_ctx.m_allocator, _size);
412 }
413 
memFree(void * _ptr,void * _userData)414 static void memFree(void* _ptr, void* _userData)
415 {
416 	BX_UNUSED(_userData);
417 	BX_FREE(s_ctx.m_allocator, _ptr);
418 }
419 
imguiCreate(float _fontSize,bx::AllocatorI * _allocator)420 void imguiCreate(float _fontSize, bx::AllocatorI* _allocator)
421 {
422 	s_ctx.create(_fontSize, _allocator);
423 }
424 
imguiDestroy()425 void imguiDestroy()
426 {
427 	s_ctx.destroy();
428 }
429 
imguiBeginFrame(int32_t _mx,int32_t _my,uint8_t _button,int32_t _scroll,uint16_t _width,uint16_t _height,int _inputChar,bgfx::ViewId _viewId)430 void imguiBeginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, uint16_t _width, uint16_t _height, int _inputChar, bgfx::ViewId _viewId)
431 {
432 	s_ctx.beginFrame(_mx, _my, _button, _scroll, _width, _height, _inputChar, _viewId);
433 }
434 
imguiEndFrame()435 void imguiEndFrame()
436 {
437 	s_ctx.endFrame();
438 }
439 
440 namespace ImGui
441 {
PushFont(Font::Enum _font)442 	void PushFont(Font::Enum _font)
443 	{
444 		PushFont(s_ctx.m_font[_font]);
445 	}
446 } // namespace ImGui
447 
448 BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505); // error C4505: '' : unreferenced local function has been removed
449 BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function"); // warning: 'int rect_width_compare(const void*, const void*)' defined but not used
450 BX_PRAGMA_DIAGNOSTIC_PUSH();
451 BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG("-Wunknown-pragmas")
452 BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits"); // warning: comparison is always true due to limited range of data type
453 #define STBTT_malloc(_size, _userData) memAlloc(_size, _userData)
454 #define STBTT_free(_ptr, _userData) memFree(_ptr, _userData)
455 #define STB_RECT_PACK_IMPLEMENTATION
456 #include <stb/stb_rect_pack.h>
457 #define STB_TRUETYPE_IMPLEMENTATION
458 #include <stb/stb_truetype.h>
459 BX_PRAGMA_DIAGNOSTIC_POP();
460