deferred.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. /*
  2. * Copyright 2011-2025 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include <bx/bounds.h>
  6. #include "common.h"
  7. #include "bgfx_utils.h"
  8. #include "imgui/imgui.h"
  9. #include "camera.h"
  10. namespace
  11. {
  12. constexpr bgfx::ViewId kRenderPassGeometry = 0;
  13. constexpr bgfx::ViewId kRenderPassClearUav = 1;
  14. constexpr bgfx::ViewId kRenderPassLight = 2;
  15. constexpr bgfx::ViewId kRenderPassCombine = 3;
  16. constexpr bgfx::ViewId kRenderPassDebugLights = 4;
  17. constexpr bgfx::ViewId kRenderPassDebugGBuffer = 5;
  18. struct PosNormalTangentTexcoordVertex
  19. {
  20. float m_x;
  21. float m_y;
  22. float m_z;
  23. uint32_t m_normal;
  24. uint32_t m_tangent;
  25. int16_t m_u;
  26. int16_t m_v;
  27. static void init()
  28. {
  29. ms_layout
  30. .begin()
  31. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  32. .add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true)
  33. .add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true)
  34. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Int16, true, true)
  35. .end();
  36. }
  37. static bgfx::VertexLayout ms_layout;
  38. };
  39. bgfx::VertexLayout PosNormalTangentTexcoordVertex::ms_layout;
  40. struct PosTexCoord0Vertex
  41. {
  42. float m_x;
  43. float m_y;
  44. float m_z;
  45. float m_u;
  46. float m_v;
  47. static void init()
  48. {
  49. ms_layout
  50. .begin()
  51. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  52. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  53. .end();
  54. }
  55. static bgfx::VertexLayout ms_layout;
  56. };
  57. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  58. struct DebugVertex
  59. {
  60. float m_x;
  61. float m_y;
  62. float m_z;
  63. uint32_t m_abgr;
  64. static void init()
  65. {
  66. ms_layout
  67. .begin()
  68. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  69. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  70. .end();
  71. }
  72. static bgfx::VertexLayout ms_layout;
  73. };
  74. bgfx::VertexLayout DebugVertex::ms_layout;
  75. static PosNormalTangentTexcoordVertex s_cubeVertices[24] =
  76. {
  77. {-1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0, 0 },
  78. { 1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0x7fff, 0 },
  79. {-1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0, 0x7fff },
  80. { 1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0x7fff, 0x7fff },
  81. {-1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0, 0 },
  82. { 1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0x7fff, 0 },
  83. {-1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0, 0x7fff },
  84. { 1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0x7fff, 0x7fff },
  85. {-1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0, 0 },
  86. { 1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0x7fff, 0 },
  87. {-1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0, 0x7fff },
  88. { 1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0x7fff, 0x7fff },
  89. {-1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0, 0 },
  90. { 1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0x7fff, 0 },
  91. {-1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0, 0x7fff },
  92. { 1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0x7fff, 0x7fff },
  93. { 1.0f, -1.0f, 1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0, 0 },
  94. { 1.0f, 1.0f, 1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0x7fff, 0 },
  95. { 1.0f, -1.0f, -1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0, 0x7fff },
  96. { 1.0f, 1.0f, -1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0x7fff, 0x7fff },
  97. {-1.0f, -1.0f, 1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0, 0 },
  98. {-1.0f, 1.0f, 1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0x7fff, 0 },
  99. {-1.0f, -1.0f, -1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0, 0x7fff },
  100. {-1.0f, 1.0f, -1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0x7fff, 0x7fff },
  101. };
  102. static const uint16_t s_cubeIndices[36] =
  103. {
  104. 0, 2, 1,
  105. 1, 2, 3,
  106. 4, 5, 6,
  107. 5, 7, 6,
  108. 8, 10, 9,
  109. 9, 10, 11,
  110. 12, 13, 14,
  111. 13, 15, 14,
  112. 16, 18, 17,
  113. 17, 18, 19,
  114. 20, 21, 22,
  115. 21, 23, 22,
  116. };
  117. void screenSpaceQuad(bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  118. {
  119. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout) )
  120. {
  121. bgfx::TransientVertexBuffer vb;
  122. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  123. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  124. const float minx = -_width;
  125. const float maxx = _width;
  126. const float miny = 0.0f;
  127. const float maxy = _height*2.0f;
  128. const float minu = -1.0f;
  129. const float maxu = 1.0f;
  130. const float zz = 0.0f;
  131. float minv = 0.0f;
  132. float maxv = 2.0f;
  133. if (_originBottomLeft)
  134. {
  135. float temp = minv;
  136. minv = maxv;
  137. maxv = temp;
  138. minv -= 1.0f;
  139. maxv -= 1.0f;
  140. }
  141. vertex[0].m_x = minx;
  142. vertex[0].m_y = miny;
  143. vertex[0].m_z = zz;
  144. vertex[0].m_u = minu;
  145. vertex[0].m_v = minv;
  146. vertex[1].m_x = maxx;
  147. vertex[1].m_y = miny;
  148. vertex[1].m_z = zz;
  149. vertex[1].m_u = maxu;
  150. vertex[1].m_v = minv;
  151. vertex[2].m_x = maxx;
  152. vertex[2].m_y = maxy;
  153. vertex[2].m_z = zz;
  154. vertex[2].m_u = maxu;
  155. vertex[2].m_v = maxv;
  156. bgfx::setVertexBuffer(0, &vb);
  157. }
  158. }
  159. class ExampleDeferred : public entry::AppI
  160. {
  161. public:
  162. ExampleDeferred(const char* _name, const char* _description, const char* _url)
  163. : entry::AppI(_name, _description, _url)
  164. {
  165. }
  166. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  167. {
  168. Args args(_argc, _argv);
  169. m_width = _width;
  170. m_height = _height;
  171. m_debug = BGFX_DEBUG_TEXT;
  172. m_reset = BGFX_RESET_VSYNC;
  173. bgfx::Init init;
  174. init.type = args.m_type;
  175. init.vendorId = args.m_pciId;
  176. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  177. init.platformData.ndt = entry::getNativeDisplayHandle();
  178. init.platformData.type = entry::getNativeWindowHandleType();
  179. init.resolution.width = m_width;
  180. init.resolution.height = m_height;
  181. init.resolution.reset = m_reset;
  182. bgfx::init(init);
  183. // Enable m_debug text.
  184. bgfx::setDebug(m_debug);
  185. // Set palette color for index 0
  186. bgfx::setPaletteColor(0, UINT32_C(0x00000000) );
  187. // Set palette color for index 1
  188. bgfx::setPaletteColor(1, UINT32_C(0x303030ff) );
  189. // Set geometry pass view clear state.
  190. bgfx::setViewClear(kRenderPassGeometry
  191. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  192. , 1.0f
  193. , 0
  194. , 1
  195. , 0
  196. );
  197. // Set light pass view clear state.
  198. bgfx::setViewClear(kRenderPassLight
  199. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  200. , 1.0f
  201. , 0
  202. , 0
  203. );
  204. // Create vertex stream declaration.
  205. PosNormalTangentTexcoordVertex::init();
  206. PosTexCoord0Vertex::init();
  207. DebugVertex::init();
  208. calcTangents(s_cubeVertices
  209. , BX_COUNTOF(s_cubeVertices)
  210. , PosNormalTangentTexcoordVertex::ms_layout
  211. , s_cubeIndices
  212. , BX_COUNTOF(s_cubeIndices)
  213. );
  214. // Create static vertex buffer.
  215. m_vbh = bgfx::createVertexBuffer(
  216. bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
  217. , PosNormalTangentTexcoordVertex::ms_layout
  218. );
  219. // Create static index buffer.
  220. m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
  221. // Create texture sampler uniforms.
  222. s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Sampler);
  223. s_texNormal = bgfx::createUniform("s_texNormal", bgfx::UniformType::Sampler);
  224. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  225. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler);
  226. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
  227. s_light = bgfx::createUniform("s_light", bgfx::UniformType::Sampler);
  228. u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Mat4);
  229. u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Vec4);
  230. u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Vec4);
  231. u_layer = bgfx::createUniform("u_layer", bgfx::UniformType::Vec4);
  232. // Create program from shaders.
  233. m_geomProgram = loadProgram("vs_deferred_geom", "fs_deferred_geom");
  234. m_lightProgram = loadProgram("vs_deferred_light", "fs_deferred_light");
  235. m_combineProgram = loadProgram("vs_deferred_combine", "fs_deferred_combine");
  236. m_debugProgram = loadProgram("vs_deferred_debug", "fs_deferred_debug");
  237. m_lineProgram = loadProgram("vs_deferred_debug_line", "fs_deferred_debug_line");
  238. m_useTArray = false;
  239. m_useUav = false;
  240. if (0 != (BGFX_CAPS_TEXTURE_2D_ARRAY & bgfx::getCaps()->supported) )
  241. {
  242. m_lightTaProgram = loadProgram("vs_deferred_light", "fs_deferred_light_ta");
  243. m_combineTaProgram = loadProgram("vs_deferred_combine", "fs_deferred_combine_ta");
  244. m_debugTaProgram = loadProgram("vs_deferred_debug", "fs_deferred_debug_ta");
  245. }
  246. else
  247. {
  248. m_lightTaProgram = BGFX_INVALID_HANDLE;
  249. m_combineTaProgram = BGFX_INVALID_HANDLE;
  250. m_debugTaProgram = BGFX_INVALID_HANDLE;
  251. }
  252. if (0 != (BGFX_CAPS_IMAGE_RW & bgfx::getCaps()->supported)
  253. && 0 != (BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ & bgfx::getCaps()->formats[bgfx::TextureFormat::RGBA8])
  254. && 0 != (BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE & bgfx::getCaps()->formats[bgfx::TextureFormat::RGBA8]) )
  255. {
  256. m_clearUavProgram = loadProgram("vs_deferred_light", "fs_deferred_clear_uav");
  257. m_lightUavProgram = loadProgram("vs_deferred_light", "fs_deferred_light_uav");
  258. }
  259. else
  260. {
  261. m_lightUavProgram = BGFX_INVALID_HANDLE;
  262. m_clearUavProgram = BGFX_INVALID_HANDLE;
  263. }
  264. // Load diffuse texture.
  265. m_textureColor = loadTexture("textures/fieldstone-rgba.dds");
  266. // Load normal texture.
  267. m_textureNormal = loadTexture("textures/fieldstone-n.dds");
  268. m_lightBufferTex.idx = bgfx::kInvalidHandle;
  269. m_gbufferTex[0].idx = bgfx::kInvalidHandle;
  270. m_gbufferTex[1].idx = bgfx::kInvalidHandle;
  271. m_gbufferTex[2].idx = bgfx::kInvalidHandle;
  272. m_gbuffer.idx = bgfx::kInvalidHandle;
  273. m_lightBuffer.idx = bgfx::kInvalidHandle;
  274. // Imgui.
  275. imguiCreate();
  276. m_timeOffset = bx::getHPCounter();
  277. // Get renderer capabilities info.
  278. m_caps = bgfx::getCaps();
  279. m_oldWidth = 0;
  280. m_oldHeight = 0;
  281. m_oldReset = m_reset;
  282. m_scrollArea = 0;
  283. m_numLights = 512;
  284. m_lightAnimationSpeed = 0.3f;
  285. m_animateMesh = true;
  286. m_showScissorRects = false;
  287. m_showGBuffer = true;
  288. cameraCreate();
  289. cameraSetPosition({ 0.0f, 0.0f, -15.0f });
  290. cameraSetVerticalAngle(0.0f);
  291. }
  292. virtual int shutdown() override
  293. {
  294. // Cleanup.
  295. cameraDestroy();
  296. imguiDestroy();
  297. if (bgfx::isValid(m_gbuffer) )
  298. {
  299. bgfx::destroy(m_gbuffer);
  300. }
  301. if (bgfx::isValid(m_lightBuffer) )
  302. {
  303. bgfx::destroy(m_lightBuffer);
  304. }
  305. if (bgfx::isValid(m_lightBufferTex) )
  306. {
  307. bgfx::destroy(m_lightBufferTex);
  308. }
  309. bgfx::destroy(m_ibh);
  310. bgfx::destroy(m_vbh);
  311. bgfx::destroy(m_geomProgram);
  312. bgfx::destroy(m_lightProgram);
  313. if (bgfx::isValid(m_lightTaProgram) )
  314. {
  315. bgfx::destroy(m_lightTaProgram);
  316. }
  317. if (bgfx::isValid(m_lightUavProgram) )
  318. {
  319. bgfx::destroy(m_lightUavProgram);
  320. bgfx::destroy(m_clearUavProgram);
  321. }
  322. bgfx::destroy(m_combineProgram);
  323. if (bgfx::isValid(m_combineTaProgram) )
  324. {
  325. bgfx::destroy(m_combineTaProgram);
  326. }
  327. bgfx::destroy(m_debugProgram);
  328. if (bgfx::isValid(m_debugTaProgram) )
  329. {
  330. bgfx::destroy(m_debugTaProgram);
  331. }
  332. bgfx::destroy(m_lineProgram);
  333. bgfx::destroy(m_textureColor);
  334. bgfx::destroy(m_textureNormal);
  335. bgfx::destroy(s_texColor);
  336. bgfx::destroy(s_texNormal);
  337. bgfx::destroy(s_albedo);
  338. bgfx::destroy(s_normal);
  339. bgfx::destroy(s_depth);
  340. bgfx::destroy(s_light);
  341. bgfx::destroy(u_layer);
  342. bgfx::destroy(u_lightPosRadius);
  343. bgfx::destroy(u_lightRgbInnerR);
  344. bgfx::destroy(u_mtx);
  345. // Shutdown bgfx.
  346. bgfx::shutdown();
  347. return 0;
  348. }
  349. bool update() override
  350. {
  351. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  352. {
  353. imguiBeginFrame(m_mouseState.m_mx
  354. , m_mouseState.m_my
  355. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  356. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  357. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  358. , m_mouseState.m_mz
  359. , uint16_t(m_width)
  360. , uint16_t(m_height)
  361. );
  362. showExampleDialog(this);
  363. int64_t now = bx::getHPCounter();
  364. static int64_t last = now;
  365. const int64_t frameTime = now - last;
  366. last = now;
  367. const double freq = double(bx::getHPFrequency() );
  368. const float deltaTime = float(frameTime/freq);
  369. float time = (float)( (now-m_timeOffset)/freq);
  370. ImGui::SetNextWindowPos(
  371. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  372. , ImGuiCond_FirstUseEver
  373. );
  374. ImGui::SetNextWindowSize(
  375. ImVec2(m_width / 5.0f, m_height / 3.0f)
  376. , ImGuiCond_FirstUseEver
  377. );
  378. ImGui::Begin("Settings", NULL, 0);
  379. ImGui::SliderInt("Num lights", &m_numLights, 1, 2048);
  380. ImGui::Checkbox("Show G-Buffer.", &m_showGBuffer);
  381. ImGui::Checkbox("Show light scissor.", &m_showScissorRects);
  382. if (bgfx::isValid(m_lightTaProgram))
  383. {
  384. ImGui::Checkbox("Use texture array frame buffer.", &m_useTArray);
  385. }
  386. else
  387. {
  388. ImGui::Text("Texture array frame buffer is not supported.");
  389. }
  390. if (bgfx::isValid(m_lightUavProgram))
  391. {
  392. ImGui::Checkbox("Use UAV.", &m_useUav);
  393. }
  394. else
  395. {
  396. ImGui::Text("UAV is not supported.");
  397. }
  398. ImGui::Checkbox("Animate mesh.", &m_animateMesh);
  399. ImGui::SliderFloat("Anim.speed", &m_lightAnimationSpeed, 0.0f, 0.4f);
  400. ImGui::End();
  401. if (2 > m_caps->limits.maxFBAttachments)
  402. {
  403. // When multiple render targets (MRT) is not supported by GPU,
  404. // implement alternative code path that doesn't use MRT.
  405. bool blink = uint32_t(time*3.0f)&1;
  406. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " MRT not supported by GPU. ");
  407. // Set view 0 default viewport.
  408. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  409. // This dummy draw call is here to make sure that view 0 is cleared
  410. // if no other draw calls are submitted to view 0.
  411. bgfx::touch(0);
  412. }
  413. else
  414. {
  415. if (m_oldWidth != m_width
  416. || m_oldHeight != m_height
  417. || m_oldReset != m_reset
  418. || m_oldUseTArray != m_useTArray
  419. || m_oldUseUav != m_useUav
  420. || !bgfx::isValid(m_gbuffer) )
  421. {
  422. // Recreate variable size render targets when resolution changes.
  423. m_oldWidth = m_width;
  424. m_oldHeight = m_height;
  425. m_oldReset = m_reset;
  426. m_oldUseTArray = m_useTArray;
  427. m_oldUseUav = m_useUav;
  428. if (bgfx::isValid(m_gbuffer) )
  429. {
  430. bgfx::destroy(m_gbuffer);
  431. m_gbufferTex[0].idx = bgfx::kInvalidHandle;
  432. m_gbufferTex[1].idx = bgfx::kInvalidHandle;
  433. m_gbufferTex[2].idx = bgfx::kInvalidHandle;
  434. }
  435. const uint64_t tsFlags = 0
  436. | BGFX_SAMPLER_MIN_POINT
  437. | BGFX_SAMPLER_MAG_POINT
  438. | BGFX_SAMPLER_MIP_POINT
  439. | BGFX_SAMPLER_U_CLAMP
  440. | BGFX_SAMPLER_V_CLAMP
  441. ;
  442. bgfx::Attachment gbufferAt[3];
  443. if (m_useTArray)
  444. {
  445. m_gbufferTex[0] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 2, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  446. gbufferAt[0].init(m_gbufferTex[0], bgfx::Access::Write, 0);
  447. gbufferAt[1].init(m_gbufferTex[0], bgfx::Access::Write, 1);
  448. }
  449. else
  450. {
  451. m_gbufferTex[0] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  452. m_gbufferTex[1] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  453. gbufferAt[0].init(m_gbufferTex[0]);
  454. gbufferAt[1].init(m_gbufferTex[1]);
  455. }
  456. bgfx::TextureFormat::Enum depthFormat =
  457. bgfx::isTextureValid(0, false, 1, bgfx::TextureFormat::D32F, BGFX_TEXTURE_RT | tsFlags)
  458. ? bgfx::TextureFormat::D32F
  459. : bgfx::TextureFormat::D24
  460. ;
  461. m_gbufferTex[2] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, depthFormat, BGFX_TEXTURE_RT | tsFlags);
  462. gbufferAt[2].init(m_gbufferTex[2]);
  463. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(gbufferAt), gbufferAt, true);
  464. if (bgfx::isValid(m_lightBuffer) )
  465. {
  466. bgfx::destroy(m_lightBuffer);
  467. m_lightBuffer.idx = bgfx::kInvalidHandle;
  468. }
  469. if (bgfx::isValid(m_lightBufferTex))
  470. {
  471. bgfx::destroy(m_lightBufferTex);
  472. m_lightBufferTex.idx = bgfx::kInvalidHandle;
  473. }
  474. if (m_useUav)
  475. {
  476. m_lightBufferTex = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::RGBA8, BGFX_TEXTURE_COMPUTE_WRITE | tsFlags);
  477. }
  478. else
  479. {
  480. m_lightBufferTex = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  481. m_lightBuffer = bgfx::createFrameBuffer(1, &m_lightBufferTex, true);
  482. }
  483. }
  484. // Update camera.
  485. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  486. float view[16];
  487. cameraGetViewMtx(view);
  488. // Setup views
  489. float vp[16];
  490. float invMvp[16];
  491. {
  492. bgfx::setViewRect(kRenderPassGeometry, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  493. bgfx::setViewRect(kRenderPassClearUav, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  494. bgfx::setViewRect(kRenderPassLight, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  495. bgfx::setViewRect(kRenderPassCombine, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  496. bgfx::setViewRect(kRenderPassDebugLights, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  497. bgfx::setViewRect(kRenderPassDebugGBuffer, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  498. if (!m_useUav)
  499. {
  500. bgfx::setViewFrameBuffer(kRenderPassLight, m_lightBuffer);
  501. }
  502. else
  503. {
  504. bgfx::setViewFrameBuffer(kRenderPassLight, BGFX_INVALID_HANDLE);
  505. }
  506. float proj[16];
  507. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, m_caps->homogeneousDepth);
  508. bgfx::setViewFrameBuffer(kRenderPassGeometry, m_gbuffer);
  509. bgfx::setViewTransform(kRenderPassGeometry, view, proj);
  510. bx::mtxMul(vp, view, proj);
  511. bx::mtxInverse(invMvp, vp);
  512. const bgfx::Caps* caps = bgfx::getCaps();
  513. bx::mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f, 0.0f, caps->homogeneousDepth);
  514. bgfx::setViewTransform(kRenderPassClearUav, NULL, proj);
  515. bgfx::setViewTransform(kRenderPassLight, NULL, proj);
  516. bgfx::setViewTransform(kRenderPassCombine, NULL, proj);
  517. const float aspectRatio = float(m_height)/float(m_width);
  518. const float size = 10.0f;
  519. bx::mtxOrtho(proj, -size, size, size*aspectRatio, -size*aspectRatio, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  520. bgfx::setViewTransform(kRenderPassDebugGBuffer, NULL, proj);
  521. bx::mtxOrtho(proj, 0.0f, (float)m_width, 0.0f, (float)m_height, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  522. bgfx::setViewTransform(kRenderPassDebugLights, NULL, proj);
  523. }
  524. const uint32_t dim = 11;
  525. const float offset = (float(dim-1) * 3.0f) * 0.5f;
  526. // Draw into geometry pass.
  527. for (uint32_t yy = 0; yy < dim; ++yy)
  528. {
  529. for (uint32_t xx = 0; xx < dim; ++xx)
  530. {
  531. float mtx[16];
  532. if (m_animateMesh)
  533. {
  534. bx::mtxRotateXY(mtx, time*1.023f + xx*0.21f, time*0.03f + yy*0.37f);
  535. }
  536. else
  537. {
  538. bx::mtxIdentity(mtx);
  539. }
  540. mtx[12] = -offset + float(xx)*3.0f;
  541. mtx[13] = -offset + float(yy)*3.0f;
  542. mtx[14] = 0.0f;
  543. // Set transform for draw call.
  544. bgfx::setTransform(mtx);
  545. // Set vertex and index buffer.
  546. bgfx::setVertexBuffer(0, m_vbh);
  547. bgfx::setIndexBuffer(m_ibh);
  548. // Bind textures.
  549. bgfx::setTexture(0, s_texColor, m_textureColor);
  550. bgfx::setTexture(1, s_texNormal, m_textureNormal);
  551. // Set render states.
  552. bgfx::setState(0
  553. | BGFX_STATE_WRITE_RGB
  554. | BGFX_STATE_WRITE_A
  555. | BGFX_STATE_WRITE_Z
  556. | BGFX_STATE_DEPTH_TEST_LESS
  557. | BGFX_STATE_MSAA
  558. );
  559. // Submit primitive for rendering to view 0.
  560. bgfx::submit(kRenderPassGeometry, m_geomProgram);
  561. }
  562. }
  563. // Clear UAV texture
  564. if (m_useUav)
  565. {
  566. screenSpaceQuad(m_caps->originBottomLeft);
  567. bgfx::setViewFrameBuffer(kRenderPassClearUav, BGFX_INVALID_HANDLE);
  568. bgfx::setState(0);
  569. bgfx::setImage(2, m_lightBufferTex, 0, bgfx::Access::ReadWrite, bgfx::TextureFormat::RGBA8);
  570. bgfx::submit(kRenderPassClearUav, m_clearUavProgram);
  571. }
  572. // Draw lights into light buffer.
  573. for (int32_t light = 0; light < m_numLights; ++light)
  574. {
  575. bx::Sphere lightPosRadius;
  576. float lightTime = time * m_lightAnimationSpeed * (bx::sin(light/float(m_numLights) * bx::kPiHalf ) * 0.5f + 0.5f);
  577. lightPosRadius.center.x = bx::sin( ( (lightTime + light*0.47f) + bx::kPiHalf*1.37f ) )*offset;
  578. lightPosRadius.center.y = bx::cos( ( (lightTime + light*0.69f) + bx::kPiHalf*1.49f ) )*offset;
  579. lightPosRadius.center.z = bx::sin( ( (lightTime + light*0.37f) + bx::kPiHalf*1.57f ) )*2.0f;
  580. lightPosRadius.radius = 2.0f;
  581. bx::Aabb aabb;
  582. toAabb(aabb, lightPosRadius);
  583. const bx::Vec3 box[8] =
  584. {
  585. { aabb.min.x, aabb.min.y, aabb.min.z },
  586. { aabb.min.x, aabb.min.y, aabb.max.z },
  587. { aabb.min.x, aabb.max.y, aabb.min.z },
  588. { aabb.min.x, aabb.max.y, aabb.max.z },
  589. { aabb.max.x, aabb.min.y, aabb.min.z },
  590. { aabb.max.x, aabb.min.y, aabb.max.z },
  591. { aabb.max.x, aabb.max.y, aabb.min.z },
  592. { aabb.max.x, aabb.max.y, aabb.max.z },
  593. };
  594. bx::Vec3 xyz = bx::mulH(box[0], vp);
  595. bx::Vec3 min = xyz;
  596. bx::Vec3 max = xyz;
  597. for (uint32_t ii = 1; ii < 8; ++ii)
  598. {
  599. xyz = bx::mulH(box[ii], vp);
  600. min = bx::min(min, xyz);
  601. max = bx::max(max, xyz);
  602. }
  603. // Cull light if it's fully behind camera.
  604. if (max.z >= 0.0f)
  605. {
  606. const float x0 = bx::clamp( (min.x * 0.5f + 0.5f) * m_width, 0.0f, (float)m_width);
  607. const float y0 = bx::clamp( (min.y * 0.5f + 0.5f) * m_height, 0.0f, (float)m_height);
  608. const float x1 = bx::clamp( (max.x * 0.5f + 0.5f) * m_width, 0.0f, (float)m_width);
  609. const float y1 = bx::clamp( (max.y * 0.5f + 0.5f) * m_height, 0.0f, (float)m_height);
  610. if (m_showScissorRects)
  611. {
  612. bgfx::TransientVertexBuffer tvb;
  613. bgfx::TransientIndexBuffer tib;
  614. if (bgfx::allocTransientBuffers(&tvb, DebugVertex::ms_layout, 4, &tib, 8) )
  615. {
  616. uint32_t abgr = 0x8000ff00;
  617. DebugVertex* vertex = (DebugVertex*)tvb.data;
  618. vertex->m_x = x0;
  619. vertex->m_y = y0;
  620. vertex->m_z = 0.0f;
  621. vertex->m_abgr = abgr;
  622. ++vertex;
  623. vertex->m_x = x1;
  624. vertex->m_y = y0;
  625. vertex->m_z = 0.0f;
  626. vertex->m_abgr = abgr;
  627. ++vertex;
  628. vertex->m_x = x1;
  629. vertex->m_y = y1;
  630. vertex->m_z = 0.0f;
  631. vertex->m_abgr = abgr;
  632. ++vertex;
  633. vertex->m_x = x0;
  634. vertex->m_y = y1;
  635. vertex->m_z = 0.0f;
  636. vertex->m_abgr = abgr;
  637. uint16_t* indices = (uint16_t*)tib.data;
  638. *indices++ = 0;
  639. *indices++ = 1;
  640. *indices++ = 1;
  641. *indices++ = 2;
  642. *indices++ = 2;
  643. *indices++ = 3;
  644. *indices++ = 3;
  645. *indices++ = 0;
  646. bgfx::setVertexBuffer(0, &tvb);
  647. bgfx::setIndexBuffer(&tib);
  648. bgfx::setState(0
  649. | BGFX_STATE_WRITE_RGB
  650. | BGFX_STATE_PT_LINES
  651. | BGFX_STATE_BLEND_ALPHA
  652. );
  653. bgfx::submit(kRenderPassDebugLights, m_lineProgram);
  654. }
  655. }
  656. uint8_t val = light&7;
  657. float lightRgbInnerR[4] =
  658. {
  659. val & 0x1 ? 1.0f : 0.25f,
  660. val & 0x2 ? 1.0f : 0.25f,
  661. val & 0x4 ? 1.0f : 0.25f,
  662. 0.8f,
  663. };
  664. // Draw light.
  665. bgfx::setUniform(u_lightPosRadius, &lightPosRadius);
  666. bgfx::setUniform(u_lightRgbInnerR, lightRgbInnerR);
  667. bgfx::setUniform(u_mtx, invMvp);
  668. const uint16_t scissorHeight = uint16_t(y1-y0);
  669. bgfx::setScissor(uint16_t(x0), uint16_t(m_height-scissorHeight-y0), uint16_t(x1-x0), uint16_t(scissorHeight) );
  670. bgfx::setTexture(0, s_normal, bgfx::getTexture(m_gbuffer, 1) );
  671. bgfx::setTexture(1, s_depth, bgfx::getTexture(m_gbuffer, 2) );
  672. bgfx::setState(0
  673. | BGFX_STATE_WRITE_RGB
  674. | BGFX_STATE_WRITE_A
  675. | BGFX_STATE_BLEND_ADD
  676. );
  677. screenSpaceQuad(m_caps->originBottomLeft);
  678. if (bgfx::isValid(m_lightTaProgram)
  679. && m_useTArray)
  680. {
  681. bgfx::submit(kRenderPassLight, m_lightTaProgram);
  682. }
  683. else if (bgfx::isValid(m_lightUavProgram)
  684. && m_useUav)
  685. {
  686. bgfx::setViewFrameBuffer(kRenderPassLight, BGFX_INVALID_HANDLE);
  687. bgfx::setState(0);
  688. bgfx::setImage(3, m_lightBufferTex, 0, bgfx::Access::ReadWrite, bgfx::TextureFormat::RGBA8);
  689. bgfx::submit(kRenderPassLight, m_lightUavProgram);
  690. }
  691. else
  692. {
  693. bgfx::submit(kRenderPassLight, m_lightProgram);
  694. }
  695. }
  696. }
  697. // Combine color and light buffers.
  698. bgfx::setTexture(0, s_albedo, bgfx::getTexture(m_gbuffer, 0) );
  699. bgfx::setTexture(1, s_light, m_lightBufferTex);
  700. bgfx::setState(0
  701. | BGFX_STATE_WRITE_RGB
  702. | BGFX_STATE_WRITE_A
  703. );
  704. screenSpaceQuad(m_caps->originBottomLeft);
  705. if (bgfx::isValid(m_lightTaProgram)
  706. && m_useTArray)
  707. {
  708. bgfx::submit(kRenderPassCombine, m_combineTaProgram);
  709. }
  710. else
  711. {
  712. bgfx::submit(kRenderPassCombine, m_combineProgram);
  713. }
  714. if (m_showGBuffer)
  715. {
  716. const float aspectRatio = float(m_width)/float(m_height);
  717. // Draw m_debug m_gbuffer.
  718. for (uint8_t ii = 0; ii < BX_COUNTOF(m_gbufferTex); ++ii)
  719. {
  720. float mtx[16];
  721. bx::mtxSRT(mtx
  722. , aspectRatio, 1.0f, 1.0f
  723. , 0.0f, 0.0f, 0.0f
  724. , -7.9f - BX_COUNTOF(m_gbufferTex)*0.1f*0.5f + ii*2.1f*aspectRatio, 4.0f, 0.0f
  725. );
  726. bgfx::setTransform(mtx);
  727. bgfx::setVertexBuffer(0, m_vbh);
  728. bgfx::setIndexBuffer(m_ibh, 0, 6);
  729. bgfx::setTexture(0, s_texColor, bgfx::getTexture(m_gbuffer, ii) );
  730. bgfx::setState(BGFX_STATE_WRITE_RGB);
  731. if (ii != BX_COUNTOF(m_gbufferTex) - 1
  732. && bgfx::isValid(m_lightTaProgram)
  733. && m_useTArray)
  734. {
  735. const float layer[4] = { float(ii) };
  736. bgfx::setUniform(u_layer, layer);
  737. bgfx::submit(kRenderPassDebugGBuffer, m_debugTaProgram);
  738. }
  739. else
  740. {
  741. bgfx::submit(kRenderPassDebugGBuffer, m_debugProgram);
  742. }
  743. }
  744. }
  745. }
  746. imguiEndFrame();
  747. // Advance to next frame. Rendering thread will be kicked to
  748. // process submitted rendering primitives.
  749. bgfx::frame();
  750. return true;
  751. }
  752. return false;
  753. }
  754. bgfx::VertexBufferHandle m_vbh;
  755. bgfx::IndexBufferHandle m_ibh;
  756. bgfx::UniformHandle s_texColor;
  757. bgfx::UniformHandle s_texNormal;
  758. bgfx::UniformHandle s_albedo;
  759. bgfx::UniformHandle s_normal;
  760. bgfx::UniformHandle s_depth;
  761. bgfx::UniformHandle s_light;
  762. bgfx::UniformHandle u_mtx;
  763. bgfx::UniformHandle u_lightPosRadius;
  764. bgfx::UniformHandle u_lightRgbInnerR;
  765. bgfx::UniformHandle u_layer;
  766. bgfx::ProgramHandle m_geomProgram;
  767. bgfx::ProgramHandle m_lightProgram;
  768. bgfx::ProgramHandle m_lightTaProgram;
  769. bgfx::ProgramHandle m_lightUavProgram;
  770. bgfx::ProgramHandle m_clearUavProgram;
  771. bgfx::ProgramHandle m_combineProgram;
  772. bgfx::ProgramHandle m_combineTaProgram;
  773. bgfx::ProgramHandle m_debugProgram;
  774. bgfx::ProgramHandle m_debugTaProgram;
  775. bgfx::ProgramHandle m_lineProgram;
  776. bgfx::TextureHandle m_textureColor;
  777. bgfx::TextureHandle m_textureNormal;
  778. bgfx::TextureHandle m_gbufferTex[3];
  779. bgfx::TextureHandle m_lightBufferTex;
  780. bgfx::FrameBufferHandle m_gbuffer;
  781. bgfx::FrameBufferHandle m_lightBuffer;
  782. uint32_t m_width;
  783. uint32_t m_height;
  784. uint32_t m_debug;
  785. uint32_t m_reset;
  786. uint32_t m_oldWidth;
  787. uint32_t m_oldHeight;
  788. uint32_t m_oldReset;
  789. bool m_useTArray;
  790. bool m_oldUseTArray;
  791. bool m_useUav;
  792. bool m_oldUseUav;
  793. int32_t m_scrollArea;
  794. int32_t m_numLights;
  795. float m_lightAnimationSpeed;
  796. bool m_animateMesh;
  797. bool m_showScissorRects;
  798. bool m_showGBuffer;
  799. entry::MouseState m_mouseState;
  800. const bgfx::Caps* m_caps;
  801. int64_t m_timeOffset;
  802. };
  803. } // namespace
  804. ENTRY_IMPLEMENT_MAIN(
  805. ExampleDeferred
  806. , "21-deferred"
  807. , "MRT rendering and deferred shading."
  808. , "https://bkaradzic.github.io/bgfx/examples.html#deferred"
  809. );