reflectiveshadowmap.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. /*
  2. * Copyright 2016 Joseph Cherlin. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "common.h"
  6. #include "camera.h"
  7. #include "bgfx_utils.h"
  8. #include "imgui/imgui.h"
  9. #include <bx/rng.h>
  10. /*
  11. * Intro
  12. * =====
  13. *
  14. * RSM (reflective shadow map) is a technique for global illumination.
  15. * It is similar to shadow map. It piggybacks on the shadow map, in fact.
  16. *
  17. * RSM is compatible with any type of lighting which can handle handle
  18. * a lot of point lights. This sample happens to use a deferred renderer,
  19. * but other types would work.
  20. *
  21. * Overview:
  22. *
  23. * - Draw into G-Buffer
  24. * - Draw Shadow Map (with RSM piggybacked on)
  25. * - Populate light buffer
  26. * - Deferred "combine" pass.
  27. *
  28. * Details
  29. * =======
  30. *
  31. * ## G-Buffer
  32. *
  33. * Typical G-Buffer with normals, color, depth.
  34. *
  35. * ## RSM
  36. *
  37. * A typical shadow map, except it also outputs to a "RSM" buffer.
  38. * The RSM contains the color of the item drawn, as well as a scalar value which represents
  39. * how much light would bounce off of the surface if it were hit with light from the origin
  40. * of the shadow map.
  41. *
  42. * ## Light Buffer
  43. *
  44. * We draw a lot of spheres into the light buffer. These spheres are called VPL (virtual
  45. * point lights). VPLs represent bounced light, and let us eliminate the classic "ambient"
  46. * term. Instead of us supplying their world space position in a transform matrix,
  47. * VPLs gain their position from the shadow map from step 2, using an unprojection. They gain
  48. * their color from the RSM. You could also store their position in a buffer while drawing shadows,
  49. * I'm just using depth to keep the sample smaller.
  50. *
  51. * ## Deferred combine
  52. *
  53. * Typical combine used in almost any sort of deferred renderer.
  54. *
  55. * References
  56. * ==========
  57. *
  58. * http: *www.bpeers.com/blog/?itemid=517
  59. *
  60. */
  61. // Render passes
  62. #define RENDER_PASS_GBUFFER 0 // GBuffer for normals and albedo
  63. #define RENDER_PASS_SHADOW_MAP 1 // Draw into the shadow map (RSM and regular shadow map at same time)
  64. #define RENDER_PASS_LIGHT_BUFFER 2 // Light buffer for point lights
  65. #define RENDER_PASS_COMBINE 3 // Directional light and final result
  66. // Gbuffer has multiple render targets
  67. #define GBUFFER_RT_NORMAL 0
  68. #define GBUFFER_RT_COLOR 1
  69. #define GBUFFER_RT_DEPTH 2
  70. // Shadow map has multiple render targets
  71. #define SHADOW_RT_RSM 0 // In this algorithm, shadows write lighting info as well.
  72. #define SHADOW_RT_DEPTH 1 // Shadow maps always write a depth
  73. // Random meshes we draw
  74. #define MODEL_COUNT 222 // In this demo, a model is a mesh plus a transform and a color
  75. #define SHADOW_MAP_DIM 512
  76. #define LIGHT_DIST 10.0f
  77. static const char * s_meshPaths[] =
  78. {
  79. "meshes/cube.bin",
  80. "meshes/orb.bin",
  81. "meshes/column.bin",
  82. "meshes/bunny.bin",
  83. "meshes/tree.bin",
  84. "meshes/hollowcube.bin"
  85. };
  86. static const float s_meshScale[] =
  87. {
  88. 0.25f,
  89. 0.5f,
  90. 0.05f,
  91. 0.5f,
  92. 0.05f,
  93. 0.05f
  94. };
  95. // Vertex decl for our screen space quad (used in deferred rendering)
  96. struct PosTexCoord0Vertex
  97. {
  98. float m_x;
  99. float m_y;
  100. float m_z;
  101. float m_u;
  102. float m_v;
  103. static void init()
  104. {
  105. ms_decl
  106. .begin()
  107. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  108. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  109. .end();
  110. }
  111. static bgfx::VertexDecl ms_decl;
  112. };
  113. bgfx::VertexDecl PosTexCoord0Vertex::ms_decl;
  114. // Utility function to draw a screen space quad for deferred rendering
  115. void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  116. {
  117. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_decl) )
  118. {
  119. bgfx::TransientVertexBuffer vb;
  120. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_decl);
  121. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  122. const float minx = -_width;
  123. const float maxx = _width;
  124. const float miny = 0.0f;
  125. const float maxy = _height*2.0f;
  126. const float texelHalfW = _texelHalf/_textureWidth;
  127. const float texelHalfH = _texelHalf/_textureHeight;
  128. const float minu = -1.0f + texelHalfW;
  129. const float maxu = 1.0f + texelHalfH;
  130. const float zz = 0.0f;
  131. float minv = texelHalfH;
  132. float maxv = 2.0f + texelHalfH;
  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(&vb);
  157. }
  158. }
  159. class ExampleRSM : public entry::AppI
  160. {
  161. public:
  162. ExampleRSM()
  163. : m_reading(0)
  164. , m_currFrame(UINT32_MAX)
  165. , m_cameraSpin(false)
  166. , m_lightElevation(35.0f)
  167. , m_lightAzimuth(215.0f)
  168. , m_rsmAmount(0.25f)
  169. , m_vplRadius(3.0f)
  170. , m_texelHalf(0.0f)
  171. {
  172. }
  173. void init(int _argc, char** _argv) BX_OVERRIDE
  174. {
  175. Args args(_argc, _argv);
  176. m_width = 1280;
  177. m_height = 720;
  178. m_debug = BGFX_DEBUG_TEXT;
  179. m_reset = BGFX_RESET_VSYNC;
  180. bgfx::init(args.m_type, args.m_pciId);
  181. bgfx::reset(m_width, m_height, m_reset);
  182. // Enable debug text.
  183. bgfx::setDebug(m_debug);
  184. // Labeling for renderdoc captures, etc
  185. bgfx::setViewName(RENDER_PASS_GBUFFER, "gbuffer" );
  186. bgfx::setViewName(RENDER_PASS_SHADOW_MAP, "shadow map" );
  187. bgfx::setViewName(RENDER_PASS_LIGHT_BUFFER, "light buffer");
  188. bgfx::setViewName(RENDER_PASS_COMBINE, "post combine");
  189. // Set up screen clears
  190. bgfx::setViewClear(RENDER_PASS_GBUFFER
  191. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  192. , 0
  193. , 1.0f
  194. , 0
  195. );
  196. bgfx::setViewClear(RENDER_PASS_LIGHT_BUFFER
  197. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  198. , 0
  199. , 1.0f
  200. , 0
  201. );
  202. bgfx::setViewClear(RENDER_PASS_SHADOW_MAP
  203. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  204. , 0
  205. , 1.0f
  206. , 0
  207. );
  208. // Create uniforms
  209. u_tint = bgfx::createUniform("u_tint", bgfx::UniformType::Vec4); // Tint for when you click on items
  210. u_lightDir = bgfx::createUniform("u_lightDir", bgfx::UniformType::Vec4); // Single directional light for entire scene
  211. u_sphereInfo = bgfx::createUniform("u_sphereInfo", bgfx::UniformType::Vec4); // Info for RSM
  212. u_invMvp = bgfx::createUniform("u_invMvp", bgfx::UniformType::Mat4); // Matrix needed in light buffer
  213. u_invMvpShadow = bgfx::createUniform("u_invMvpShadow", bgfx::UniformType::Mat4); // Matrix needed in light buffer
  214. u_lightMtx = bgfx::createUniform("u_lightMtx", bgfx::UniformType::Mat4); // Matrix needed to use shadow map (world to shadow space)
  215. u_shadowDimsInv = bgfx::createUniform("u_shadowDimsInv", bgfx::UniformType::Vec4); // Used in PCF
  216. u_rsmAmount = bgfx::createUniform("u_rsmAmount", bgfx::UniformType::Vec4); // How much RSM to use vs directional light
  217. // Create texture sampler uniforms (used when we bind textures)
  218. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Int1); // Normal gbuffer
  219. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Int1); // Normal gbuffer
  220. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Int1); // Color (albedo) gbuffer
  221. s_light = bgfx::createUniform("s_light", bgfx::UniformType::Int1); // Light buffer
  222. s_shadowMap = bgfx::createUniform("s_shadowMap", bgfx::UniformType::Int1); // Shadow map
  223. s_rsm = bgfx::createUniform("s_rsm", bgfx::UniformType::Int1); // Reflective shadow map
  224. // Create program from shaders.
  225. m_gbufferProgram = loadProgram("vs_rsm_gbuffer", "fs_rsm_gbuffer"); // Gbuffer
  226. m_shadowProgram = loadProgram("vs_rsm_shadow", "fs_rsm_shadow" ); // Drawing shadow map
  227. m_lightProgram = loadProgram("vs_rsm_lbuffer", "fs_rsm_lbuffer"); // Light buffer
  228. m_combineProgram = loadProgram("vs_rsm_combine", "fs_rsm_combine"); // Combiner
  229. // Load some meshes
  230. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  231. {
  232. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  233. }
  234. // Randomly create some models
  235. bx::RngMwc mwc; // Random number generator
  236. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  237. {
  238. Model& model = m_models[ii];
  239. uint32_t rr = mwc.gen() % 256;
  240. uint32_t gg = mwc.gen() % 256;
  241. uint32_t bb = mwc.gen() % 256;
  242. model.mesh = 1+mwc.gen()%(BX_COUNTOF(s_meshPaths)-1);
  243. model.color[0] = rr/255.0f;
  244. model.color[1] = gg/255.0f;
  245. model.color[2] = bb/255.0f;
  246. model.color[3] = 1.0f;
  247. model.position[0] = (((mwc.gen() % 256)) - 128.0f)/20.0f;
  248. model.position[1] = 0;
  249. model.position[2] = (((mwc.gen() % 256)) - 128.0f)/20.0f;
  250. }
  251. // Load ground. We'll just use the cube since I don't have a ground model right now
  252. m_ground = meshLoad("meshes/cube.bin");
  253. // Light sphere
  254. m_lightSphere = meshLoad("meshes/unit_sphere.bin");
  255. const uint32_t samplerFlags = 0
  256. | BGFX_TEXTURE_RT
  257. | BGFX_TEXTURE_MIN_POINT
  258. | BGFX_TEXTURE_MAG_POINT
  259. | BGFX_TEXTURE_MIP_POINT
  260. | BGFX_TEXTURE_U_CLAMP
  261. | BGFX_TEXTURE_V_CLAMP
  262. ;
  263. // Make gbuffer and related textures
  264. m_gbufferTex[GBUFFER_RT_NORMAL] = bgfx::createTexture2D(bgfx::BackbufferRatio::Equal, false, 1, bgfx::TextureFormat::BGRA8, samplerFlags);
  265. m_gbufferTex[GBUFFER_RT_COLOR] = bgfx::createTexture2D(bgfx::BackbufferRatio::Equal, false, 1, bgfx::TextureFormat::BGRA8, samplerFlags);
  266. m_gbufferTex[GBUFFER_RT_DEPTH] = bgfx::createTexture2D(bgfx::BackbufferRatio::Equal, false, 1, bgfx::TextureFormat::D24, samplerFlags);
  267. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_gbufferTex), m_gbufferTex, true);
  268. // Make light buffer
  269. m_lightBufferTex = bgfx::createTexture2D(bgfx::BackbufferRatio::Equal, false, 1, bgfx::TextureFormat::BGRA8, samplerFlags);
  270. bgfx::TextureHandle lightBufferRTs[] = {
  271. m_lightBufferTex
  272. };
  273. m_lightBuffer = bgfx::createFrameBuffer(BX_COUNTOF(lightBufferRTs), lightBufferRTs, true);
  274. // Make shadow buffer
  275. const uint32_t rsmFlags = 0
  276. | BGFX_TEXTURE_RT
  277. | BGFX_TEXTURE_MIN_POINT
  278. | BGFX_TEXTURE_MAG_POINT
  279. | BGFX_TEXTURE_MIP_POINT
  280. | BGFX_TEXTURE_U_CLAMP
  281. | BGFX_TEXTURE_V_CLAMP
  282. ;
  283. // Reflective shadow map
  284. m_shadowBufferTex[SHADOW_RT_RSM] = bgfx::createTexture2D(
  285. SHADOW_MAP_DIM
  286. , SHADOW_MAP_DIM
  287. , false
  288. , 1
  289. , bgfx::TextureFormat::BGRA8,
  290. rsmFlags
  291. );
  292. // Typical shadow map
  293. m_shadowBufferTex[SHADOW_RT_DEPTH] = bgfx::createTexture2D(
  294. SHADOW_MAP_DIM
  295. , SHADOW_MAP_DIM
  296. , false
  297. , 1
  298. , bgfx::TextureFormat::D16,
  299. BGFX_TEXTURE_RT/* | BGFX_TEXTURE_COMPARE_LEQUAL*/
  300. ); // Note I'm not setting BGFX_TEXTURE_COMPARE_LEQUAL. Why?
  301. // Normally a PCF shadow map such as this requires a compare. However, this sample also
  302. // reads from this texture in the lighting pass, and only uses the PCF capabilites in the
  303. // combine pass, so the flag is disabled by default.
  304. m_shadowBuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_shadowBufferTex), m_shadowBufferTex, true);
  305. // Vertex decl
  306. PosTexCoord0Vertex::init();
  307. // Init camera
  308. cameraCreate();
  309. float camPos[] = {0.0f, 1.5f, 0.0f};
  310. cameraSetPosition(camPos);
  311. cameraSetVerticalAngle(-0.3f);
  312. // Init directional light
  313. updateLightDir();
  314. // Get renderer capabilities info.
  315. m_caps = bgfx::getCaps();
  316. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  317. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  318. imguiCreate();
  319. }
  320. int shutdown() BX_OVERRIDE
  321. {
  322. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  323. {
  324. meshUnload(m_meshes[ii]);
  325. }
  326. meshUnload(m_ground);
  327. meshUnload(m_lightSphere);
  328. // Cleanup.
  329. bgfx::destroyProgram(m_gbufferProgram);
  330. bgfx::destroyProgram(m_lightProgram);
  331. bgfx::destroyProgram(m_combineProgram);
  332. bgfx::destroyProgram(m_shadowProgram);
  333. bgfx::destroyUniform(u_tint);
  334. bgfx::destroyUniform(u_lightDir);
  335. bgfx::destroyUniform(u_sphereInfo);
  336. bgfx::destroyUniform(u_invMvp);
  337. bgfx::destroyUniform(u_invMvpShadow);
  338. bgfx::destroyUniform(u_lightMtx);
  339. bgfx::destroyUniform(u_shadowDimsInv);
  340. bgfx::destroyUniform(u_rsmAmount);
  341. bgfx::destroyUniform(s_normal);
  342. bgfx::destroyUniform(s_depth);
  343. bgfx::destroyUniform(s_light);
  344. bgfx::destroyUniform(s_color);
  345. bgfx::destroyUniform(s_shadowMap);
  346. bgfx::destroyUniform(s_rsm);
  347. bgfx::destroyFrameBuffer(m_gbuffer);
  348. bgfx::destroyFrameBuffer(m_lightBuffer);
  349. bgfx::destroyFrameBuffer(m_shadowBuffer);
  350. for (uint32_t ii = 0; ii < BX_COUNTOF(m_gbufferTex); ++ii)
  351. {
  352. bgfx::destroyTexture(m_gbufferTex[ii]);
  353. }
  354. bgfx::destroyTexture(m_lightBufferTex);
  355. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shadowBufferTex); ++ii)
  356. {
  357. bgfx::destroyTexture(m_shadowBufferTex[ii]);
  358. }
  359. cameraDestroy();
  360. imguiDestroy();
  361. // Shutdown bgfx.
  362. bgfx::shutdown();
  363. return 0;
  364. }
  365. bool update() BX_OVERRIDE
  366. {
  367. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  368. {
  369. // Update frame timer
  370. int64_t now = bx::getHPCounter();
  371. static int64_t last = now;
  372. const int64_t frameTime = now - last;
  373. last = now;
  374. const double freq = double(bx::getHPFrequency());
  375. const double toMs = 1000.0 / freq;
  376. const float deltaTime = float(frameTime/freq);
  377. // Use debug font to print information about this example.
  378. bgfx::dbgTextClear();
  379. bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/31-rsm");
  380. bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Global Illumination with Reflective Shadow Map.");
  381. bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
  382. // Update camera
  383. cameraUpdate(deltaTime*0.15f, m_mouseState);
  384. // Set up matrices for gbuffer
  385. float view[16];
  386. cameraGetViewMtx(view);
  387. float proj[16];
  388. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f);
  389. bgfx::setViewRect(RENDER_PASS_GBUFFER, 0, 0, uint16_t(m_width), uint16_t(m_height));
  390. bgfx::setViewTransform(RENDER_PASS_GBUFFER, view, proj);
  391. // Make sure when we draw it goes into gbuffer and not backbuffer
  392. bgfx::setViewFrameBuffer(RENDER_PASS_GBUFFER, m_gbuffer);
  393. // Draw everything into g-buffer
  394. drawAllModels(RENDER_PASS_GBUFFER, m_gbufferProgram);
  395. // Draw shadow map
  396. // Set up transforms for shadow map
  397. float smView[16], smProj[16], lightEye[3], lightAt[3];
  398. lightEye[0] = m_lightDir[0]*LIGHT_DIST;
  399. lightEye[1] = m_lightDir[1]*LIGHT_DIST;
  400. lightEye[2] = m_lightDir[2]*LIGHT_DIST;
  401. lightAt[0] = 0.0f;
  402. lightAt[1] = 0.0f;
  403. lightAt[2] = 0.0f;
  404. bx::mtxLookAt(smView, lightEye, lightAt);
  405. const float area = 10.0f;
  406. bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  407. bool flipV = false
  408. || renderer == bgfx::RendererType::OpenGL
  409. || renderer == bgfx::RendererType::OpenGLES
  410. ;
  411. bx::mtxOrtho(smProj, -area, area, -area, area, -100.0f, 100.0f, 0.0f, flipV);
  412. bgfx::setViewTransform(RENDER_PASS_SHADOW_MAP, smView, smProj);
  413. bgfx::setViewFrameBuffer(RENDER_PASS_SHADOW_MAP, m_shadowBuffer);
  414. bgfx::setViewRect(RENDER_PASS_SHADOW_MAP, 0, 0, SHADOW_MAP_DIM, SHADOW_MAP_DIM);
  415. drawAllModels(RENDER_PASS_SHADOW_MAP, m_shadowProgram);
  416. // Next draw light buffer
  417. // Set up matrices for light buffer
  418. bgfx::setViewRect(RENDER_PASS_LIGHT_BUFFER, 0, 0, uint16_t(m_width), uint16_t(m_height));
  419. bgfx::setViewTransform(RENDER_PASS_LIGHT_BUFFER, view, proj); // Notice, same view and proj as gbuffer
  420. // Set drawing into light buffer
  421. bgfx::setViewFrameBuffer(RENDER_PASS_LIGHT_BUFFER, m_lightBuffer);
  422. // Inverse view projection is needed in shader so set that up
  423. float vp[16], invMvp[16];
  424. bx::mtxMul(vp, view, proj);
  425. bx::mtxInverse(invMvp, vp);
  426. // Light matrix used in combine pass and inverse used in light pass
  427. float lightMtx[16]; // World space to light space (shadow map space)
  428. bx::mtxMul(lightMtx, smView, smProj);
  429. float invMvpShadow[16];
  430. bx::mtxInverse(invMvpShadow, lightMtx);
  431. // Draw some lights (these should really be instanced but for this example they aren't...)
  432. const unsigned MAX_SPHERE = 32;
  433. for (uint32_t i = 0; i < MAX_SPHERE; i++)
  434. {
  435. for (uint32_t j = 0; j < MAX_SPHERE; j++)
  436. {
  437. // These are used in the fragment shader
  438. bgfx::setTexture(0, s_normal, bgfx::getTexture(m_gbuffer, GBUFFER_RT_NORMAL) ); // Normal for lighting calculations
  439. bgfx::setTexture(1, s_depth, bgfx::getTexture(m_gbuffer, GBUFFER_RT_DEPTH) ); // Depth to reconstruct world position
  440. // Thse are used in the vert shader
  441. bgfx::setTexture(2, s_shadowMap, bgfx::getTexture(m_shadowBuffer, SHADOW_RT_DEPTH) ); // Used to place sphere
  442. bgfx::setTexture(3, s_rsm, bgfx::getTexture(m_shadowBuffer, SHADOW_RT_RSM) ); // Used to scale/color sphere
  443. bgfx::setUniform(u_invMvp, invMvp);
  444. bgfx::setUniform(u_invMvpShadow, invMvpShadow);
  445. float sphereInfo[4];
  446. sphereInfo[0] = ((float)i/(MAX_SPHERE-1));
  447. sphereInfo[1] = ((float)j/(MAX_SPHERE-1));
  448. sphereInfo[2] = m_vplRadius;
  449. sphereInfo[3] = 0.0; // Unused
  450. bgfx::setUniform(u_sphereInfo, sphereInfo);
  451. const uint64_t lightDrawState = 0
  452. | BGFX_STATE_RGB_WRITE
  453. | BGFX_STATE_BLEND_ADD // <=== Overlapping lights contribute more
  454. | BGFX_STATE_ALPHA_WRITE
  455. | BGFX_STATE_CULL_CW // <=== If we go into the lights, there will be problems, so we draw the far back face.
  456. ;
  457. meshSubmit(
  458. m_lightSphere,
  459. RENDER_PASS_LIGHT_BUFFER,
  460. m_lightProgram,
  461. NULL,
  462. lightDrawState
  463. );
  464. }
  465. }
  466. // Draw combine pass
  467. // Texture inputs for combine pass
  468. bgfx::setTexture(0, s_normal, bgfx::getTexture(m_gbuffer, GBUFFER_RT_NORMAL) );
  469. bgfx::setTexture(1, s_color, bgfx::getTexture(m_gbuffer, GBUFFER_RT_COLOR) );
  470. bgfx::setTexture(2, s_light, bgfx::getTexture(m_lightBuffer, 0) );
  471. bgfx::setTexture(3, s_depth, bgfx::getTexture(m_gbuffer, GBUFFER_RT_DEPTH) );
  472. bgfx::setTexture(4, s_shadowMap, bgfx::getTexture(m_shadowBuffer, SHADOW_RT_DEPTH)
  473. , BGFX_TEXTURE_COMPARE_LEQUAL
  474. );
  475. // Uniforms for combine pass
  476. bgfx::setUniform(u_lightDir, m_lightDir);
  477. bgfx::setUniform(u_invMvp, invMvp);
  478. bgfx::setUniform(u_lightMtx, lightMtx);
  479. const float invDim[4] = {1.0f/SHADOW_MAP_DIM, 0.0f, 0.0f, 0.0f};
  480. bgfx::setUniform(u_shadowDimsInv, invDim);
  481. float rsmAmount[4] = {m_rsmAmount,m_rsmAmount,m_rsmAmount,m_rsmAmount};
  482. bgfx::setUniform(u_rsmAmount, rsmAmount);
  483. // Set up state for combine pass
  484. // point of this is to avoid doing depth test, which is in the default state
  485. bgfx::setState(0
  486. | BGFX_STATE_RGB_WRITE
  487. | BGFX_STATE_ALPHA_WRITE
  488. );
  489. // Set up transform matrix for fullscreen quad
  490. float orthoProj[16];
  491. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f);
  492. bgfx::setViewTransform(RENDER_PASS_COMBINE, NULL, orthoProj);
  493. bgfx::setViewRect(RENDER_PASS_COMBINE, 0, 0, m_width, m_height);
  494. // Bind vertex buffer and draw quad
  495. screenSpaceQuad( (float)m_width, (float)m_height, m_texelHalf, m_caps->originBottomLeft);
  496. bgfx::submit(RENDER_PASS_COMBINE, m_combineProgram);
  497. // Draw UI
  498. imguiBeginFrame(m_mouseState.m_mx
  499. , m_mouseState.m_my
  500. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  501. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  502. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  503. , m_mouseState.m_mz
  504. , m_width
  505. , m_height
  506. );
  507. imguiBeginArea("RSM:", 10, 100, 300, 400);
  508. imguiSlider("rsm amount", m_rsmAmount, 0.0f, 0.7f, 0.01f);
  509. imguiSlider("vpl radius", m_vplRadius, 0.25f, 20.0f, 0.1f);
  510. imguiSlider("light azimuth", m_lightAzimuth, 0.0f, 360.0f, 0.01f);
  511. imguiSlider("light elevation", m_lightElevation, 35.0f, 90.0f, 0.01f);
  512. imguiEndArea();
  513. imguiEndFrame();
  514. updateLightDir();
  515. // Advance to next frame. Rendering thread will be kicked to
  516. // process submitted rendering primitives.
  517. m_currFrame = bgfx::frame();
  518. return true;
  519. }
  520. return false;
  521. }
  522. void drawAllModels(uint8_t _pass, bgfx::ProgramHandle _program)
  523. {
  524. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  525. {
  526. const Model& model = m_models[ii];
  527. // Set up transform matrix for each model
  528. float scale = s_meshScale[model.mesh];
  529. float mtx[16];
  530. bx::mtxSRT(mtx
  531. , scale
  532. , scale
  533. , scale
  534. , 0.0f
  535. , 0.0f
  536. , 0.0f
  537. , model.position[0]
  538. , model.position[1]
  539. , model.position[2]
  540. );
  541. // Submit mesh to gbuffer
  542. bgfx::setUniform(u_tint, model.color);
  543. meshSubmit(m_meshes[model.mesh], _pass, _program, mtx);
  544. }
  545. // Draw ground
  546. const float white[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
  547. bgfx::setUniform(u_tint, white);
  548. float mtxScale[16];
  549. float scale = 10.0;
  550. bx::mtxScale(mtxScale
  551. , scale
  552. , scale
  553. , scale
  554. );
  555. float mtxTrans[16];
  556. bx::mtxTranslate(mtxTrans
  557. , 0.0f
  558. , -10.0f
  559. , 0.0f
  560. );
  561. float mtx[16];
  562. bx::mtxMul(mtx, mtxScale, mtxTrans);
  563. meshSubmit(m_ground, _pass, _program, mtx);
  564. }
  565. void updateLightDir()
  566. {
  567. float el = m_lightElevation * (bx::pi/180.0f);
  568. float az = m_lightAzimuth * (bx::pi/180.0f);
  569. m_lightDir[0] = bx::fcos(el)*bx::fcos(az);
  570. m_lightDir[2] = bx::fcos(el)*bx::fsin(az);
  571. m_lightDir[1] = bx::fsin(el);
  572. m_lightDir[3] = 0.0f;
  573. }
  574. uint32_t m_width;
  575. uint32_t m_height;
  576. uint32_t m_debug;
  577. uint32_t m_reset;
  578. entry::MouseState m_mouseState;
  579. Mesh* m_ground;
  580. Mesh* m_lightSphere; // Unit sphere
  581. // Resource handles
  582. bgfx::ProgramHandle m_gbufferProgram;
  583. bgfx::ProgramHandle m_shadowProgram;
  584. bgfx::ProgramHandle m_lightProgram;
  585. bgfx::ProgramHandle m_combineProgram;
  586. bgfx::FrameBufferHandle m_gbuffer;
  587. bgfx::FrameBufferHandle m_lightBuffer;
  588. bgfx::FrameBufferHandle m_shadowBuffer;
  589. // Shader uniforms
  590. bgfx::UniformHandle u_tint;
  591. bgfx::UniformHandle u_invMvp;
  592. bgfx::UniformHandle u_invMvpShadow;
  593. bgfx::UniformHandle u_lightMtx;
  594. bgfx::UniformHandle u_lightDir;
  595. bgfx::UniformHandle u_sphereInfo;
  596. bgfx::UniformHandle u_shadowDimsInv;
  597. bgfx::UniformHandle u_rsmAmount;
  598. // Uniforms to identify texture samples
  599. bgfx::UniformHandle s_normal;
  600. bgfx::UniformHandle s_depth;
  601. bgfx::UniformHandle s_color;
  602. bgfx::UniformHandle s_light;
  603. bgfx::UniformHandle s_shadowMap;
  604. bgfx::UniformHandle s_rsm;
  605. // Various render targets
  606. bgfx::TextureHandle m_gbufferTex[3];
  607. bgfx::TextureHandle m_lightBufferTex;
  608. bgfx::TextureHandle m_shadowBufferTex[2];
  609. const bgfx::Caps* m_caps;
  610. struct Model
  611. {
  612. uint32_t mesh; // Index of mesh in m_meshes
  613. float color[4];
  614. float position[3];
  615. };
  616. Model m_models[MODEL_COUNT];
  617. Mesh * m_meshes[BX_COUNTOF(s_meshPaths)];
  618. uint32_t m_reading;
  619. uint32_t m_currFrame;
  620. // UI
  621. bool m_cameraSpin;
  622. // Light position;
  623. float m_lightDir[4];
  624. float m_lightElevation;
  625. float m_lightAzimuth;
  626. float m_rsmAmount; // Amount of rsm
  627. float m_vplRadius; // Radius of virtual point light
  628. float m_texelHalf;
  629. };
  630. ENTRY_IMPLEMENT_MAIN(ExampleRSM);