instancing.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*
  2. * Copyright 2011-2023 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "common.h"
  6. #include "bgfx_utils.h"
  7. #include "imgui/imgui.h"
  8. namespace
  9. {
  10. struct PosColorVertex
  11. {
  12. float m_x;
  13. float m_y;
  14. float m_z;
  15. uint32_t m_abgr;
  16. static void init()
  17. {
  18. ms_layout
  19. .begin()
  20. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  21. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  22. .end();
  23. };
  24. static bgfx::VertexLayout ms_layout;
  25. };
  26. bgfx::VertexLayout PosColorVertex::ms_layout;
  27. static PosColorVertex s_cubeVertices[8] =
  28. {
  29. {-1.0f, 1.0f, 1.0f, 0xff000000 },
  30. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  31. {-1.0f, -1.0f, 1.0f, 0xff00ff00 },
  32. { 1.0f, -1.0f, 1.0f, 0xff00ffff },
  33. {-1.0f, 1.0f, -1.0f, 0xffff0000 },
  34. { 1.0f, 1.0f, -1.0f, 0xffff00ff },
  35. {-1.0f, -1.0f, -1.0f, 0xffffff00 },
  36. { 1.0f, -1.0f, -1.0f, 0xffffffff },
  37. };
  38. static const uint16_t s_cubeIndices[36] =
  39. {
  40. 0, 1, 2, // 0
  41. 1, 3, 2,
  42. 4, 6, 5, // 2
  43. 5, 6, 7,
  44. 0, 2, 4, // 4
  45. 4, 2, 6,
  46. 1, 5, 3, // 6
  47. 5, 7, 3,
  48. 0, 4, 1, // 8
  49. 4, 5, 1,
  50. 2, 3, 6, // 10
  51. 6, 3, 7,
  52. };
  53. class ExampleInstancing : public entry::AppI
  54. {
  55. public:
  56. ExampleInstancing(const char* _name, const char* _description, const char* _url)
  57. : entry::AppI(_name, _description, _url)
  58. {
  59. }
  60. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  61. {
  62. Args args(_argc, _argv);
  63. m_width = _width;
  64. m_height = _height;
  65. m_debug = BGFX_DEBUG_TEXT;
  66. m_reset = BGFX_RESET_VSYNC;
  67. m_useInstancing = true;
  68. m_lastFrameMissing = 0;
  69. m_sideSize = 11;
  70. bgfx::Init init;
  71. init.type = args.m_type;
  72. init.vendorId = args.m_pciId;
  73. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  74. init.platformData.ndt = entry::getNativeDisplayHandle();
  75. init.resolution.width = m_width;
  76. init.resolution.height = m_height;
  77. init.resolution.reset = m_reset;
  78. bgfx::init(init);
  79. // Enable debug text.
  80. bgfx::setDebug(m_debug);
  81. // Set view 0 clear state.
  82. bgfx::setViewClear(0
  83. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  84. , 0x303030ff
  85. , 1.0f
  86. , 0
  87. );
  88. // Create vertex stream declaration.
  89. PosColorVertex::init();
  90. // Create static vertex buffer.
  91. m_vbh = bgfx::createVertexBuffer(
  92. bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
  93. , PosColorVertex::ms_layout
  94. );
  95. // Create static index buffer.
  96. m_ibh = bgfx::createIndexBuffer(
  97. bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) )
  98. );
  99. // Create program from shaders.
  100. m_program = loadProgram("vs_instancing", "fs_instancing");
  101. m_program_non_instanced = loadProgram("vs_cubes", "fs_cubes");
  102. m_timeOffset = bx::getHPCounter();
  103. imguiCreate();
  104. }
  105. int shutdown() override
  106. {
  107. imguiDestroy();
  108. // Cleanup.
  109. bgfx::destroy(m_ibh);
  110. bgfx::destroy(m_vbh);
  111. bgfx::destroy(m_program);
  112. bgfx::destroy(m_program_non_instanced);
  113. // Shutdown bgfx.
  114. bgfx::shutdown();
  115. return 0;
  116. }
  117. bool update() override
  118. {
  119. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  120. {
  121. imguiBeginFrame(m_mouseState.m_mx
  122. , m_mouseState.m_my
  123. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  124. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  125. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  126. , m_mouseState.m_mz
  127. , uint16_t(m_width)
  128. , uint16_t(m_height)
  129. );
  130. showExampleDialog(this);
  131. ImGui::SetNextWindowPos(
  132. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  133. , ImGuiCond_FirstUseEver
  134. );
  135. ImGui::SetNextWindowSize(
  136. ImVec2(m_width / 5.0f, m_height / 2.0f)
  137. , ImGuiCond_FirstUseEver
  138. );
  139. ImGui::Begin("Settings"
  140. , NULL
  141. , 0
  142. );
  143. // Get renderer capabilities info.
  144. const bgfx::Caps* caps = bgfx::getCaps();
  145. // Check if instancing is supported.
  146. const bool instancingSupported = 0 != (BGFX_CAPS_INSTANCING & caps->supported);
  147. m_useInstancing &= instancingSupported;
  148. ImGui::Text("%d draw calls", bgfx::getStats()->numDraw);
  149. ImGui::PushEnabled(instancingSupported);
  150. ImGui::Checkbox("Use Instancing", &m_useInstancing);
  151. ImGui::PopEnabled();
  152. ImGui::Text("Grid Side Size:");
  153. ImGui::SliderInt("##size", (int*)&m_sideSize, 1, 512);
  154. if (m_lastFrameMissing > 0)
  155. {
  156. ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Couldn't draw %d cubes last frame", m_lastFrameMissing);
  157. }
  158. if (bgfx::getStats()->numDraw >= bgfx::getCaps()->limits.maxDrawCalls)
  159. {
  160. ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Draw call limit reached!");
  161. }
  162. ImGui::End();
  163. imguiEndFrame();
  164. // Set view 0 default viewport.
  165. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  166. // This dummy draw call is here to make sure that view 0 is cleared
  167. // if no other draw calls are submitted to view 0.
  168. bgfx::touch(0);
  169. float time = (float)( (bx::getHPCounter() - m_timeOffset)/double(bx::getHPFrequency() ) );
  170. if (!instancingSupported)
  171. {
  172. // When instancing is not supported by GPU, implement alternative
  173. // code path that doesn't use instancing.
  174. bool blink = uint32_t(time*3.0f)&1;
  175. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Instancing is not supported by GPU. ");
  176. m_useInstancing = false;
  177. }
  178. const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };
  179. const bx::Vec3 eye = { 0.0f, 0.0f, -35.0f };
  180. // Set view and projection matrix for view 0.
  181. {
  182. float view[16];
  183. bx::mtxLookAt(view, eye, at);
  184. float proj[16];
  185. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  186. bgfx::setViewTransform(0, view, proj);
  187. // Set view 0 default viewport.
  188. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  189. }
  190. m_lastFrameMissing = 0;
  191. if (m_useInstancing)
  192. {
  193. // 80 bytes stride = 64 bytes for 4x4 matrix + 16 bytes for RGBA color.
  194. const uint16_t instanceStride = 80;
  195. // to total number of instances to draw
  196. uint32_t totalCubes = m_sideSize * m_sideSize;
  197. // figure out how big of a buffer is available
  198. uint32_t drawnCubes = bgfx::getAvailInstanceDataBuffer(totalCubes, instanceStride);
  199. // save how many we couldn't draw due to buffer room so we can display it
  200. m_lastFrameMissing = totalCubes - drawnCubes;
  201. bgfx::InstanceDataBuffer idb;
  202. bgfx::allocInstanceDataBuffer(&idb, drawnCubes, instanceStride);
  203. uint8_t* data = idb.data;
  204. for (uint32_t ii = 0; ii < drawnCubes; ++ii)
  205. {
  206. uint32_t yy = ii / m_sideSize;
  207. uint32_t xx = ii % m_sideSize;
  208. float* mtx = (float*)data;
  209. bx::mtxRotateXY(mtx, time + xx * 0.21f, time + yy * 0.37f);
  210. mtx[12] = -15.0f + float(xx) * 3.0f;
  211. mtx[13] = -15.0f + float(yy) * 3.0f;
  212. mtx[14] = 0.0f;
  213. float* color = (float*)&data[64];
  214. color[0] = bx::sin(time + float(xx) / 11.0f) * 0.5f + 0.5f;
  215. color[1] = bx::cos(time + float(yy) / 11.0f) * 0.5f + 0.5f;
  216. color[2] = bx::sin(time * 3.0f) * 0.5f + 0.5f;
  217. color[3] = 1.0f;
  218. data += instanceStride;
  219. }
  220. // Set vertex and index buffer.
  221. bgfx::setVertexBuffer(0, m_vbh);
  222. bgfx::setIndexBuffer(m_ibh);
  223. // Set instance data buffer.
  224. bgfx::setInstanceDataBuffer(&idb);
  225. // Set render states.
  226. bgfx::setState(BGFX_STATE_DEFAULT);
  227. // Submit primitive for rendering to view 0.
  228. bgfx::submit(0, m_program);
  229. }
  230. else
  231. {
  232. // non-instanced path
  233. for (uint32_t yy = 0; yy < m_sideSize; ++yy)
  234. {
  235. for (uint32_t xx = 0; xx < m_sideSize; ++xx)
  236. {
  237. float mtx[16];
  238. bx::mtxRotateXY(mtx, time + xx * 0.21f, time + yy * 0.37f);
  239. mtx[12] = -15.0f + float(xx) * 3.0f;
  240. mtx[13] = -15.0f + float(yy) * 3.0f;
  241. mtx[14] = 0.0f;
  242. // Set model matrix for rendering.
  243. bgfx::setTransform(mtx);
  244. // Set vertex and index buffer.
  245. bgfx::setVertexBuffer(0, m_vbh);
  246. bgfx::setIndexBuffer(m_ibh);
  247. // Set render states.
  248. bgfx::setState(BGFX_STATE_DEFAULT);
  249. // Submit primitive for rendering to view 0.
  250. bgfx::submit(0, m_program_non_instanced);
  251. }
  252. }
  253. }
  254. // Advance to next frame. Rendering thread will be kicked to
  255. // process submitted rendering primitives.
  256. bgfx::frame();
  257. return true;
  258. }
  259. return false;
  260. }
  261. entry::MouseState m_mouseState;
  262. uint32_t m_width;
  263. uint32_t m_height;
  264. uint32_t m_debug;
  265. uint32_t m_reset;
  266. bool m_useInstancing;
  267. uint32_t m_lastFrameMissing;
  268. uint32_t m_sideSize;
  269. bgfx::VertexBufferHandle m_vbh;
  270. bgfx::IndexBufferHandle m_ibh;
  271. bgfx::ProgramHandle m_program;
  272. bgfx::ProgramHandle m_program_non_instanced;
  273. int64_t m_timeOffset;
  274. };
  275. } // namespace
  276. ENTRY_IMPLEMENT_MAIN(
  277. ExampleInstancing
  278. , "05-instancing"
  279. , "Geometry instancing."
  280. , "https://bkaradzic.github.io/bgfx/examples.html#instancing"
  281. );