reflectiveshadowmap.cpp 22 KB

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