screen_space_shadows.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. /*
  2. * Copyright 2021 elven cache. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * Implement screen space shadows as bgfx example. Goal is to explore various
  7. * options and parameters.
  8. *
  9. * radius
  10. * ======
  11. * Use radius/shadow distance defined in screen space pixels or world units.
  12. *
  13. * In world uints, the screen distance will shrink as objects get farther away.
  14. * This can provide more natural looking shadows and fade out the effect at a
  15. * distance, leaving screen space shadows as an added detail effect near the
  16. * camera.
  17. *
  18. * Screen space units mean that objects will cast the same length of shadow
  19. * regardless of how far they are away from the camera. Pull back the camera
  20. * and objects' shadows will appear to grow. On the other hand, this can be
  21. * desired because it will allow objects at the horizon like hills and trees to
  22. * cast a shadow. Depending on your scene, such far objects may be outside of
  23. * the area affected by regular shadow maps. Even with multiple cascades, you
  24. * may not be able to afford shadow maps across the entire scene.
  25. *
  26. * This sample does not put effort into avoiding the initial pixel or avoiding
  27. * resampling the same value if the step size is relatively smaller than the
  28. * sampled distance in screen space. May want to set a minimum distance so each
  29. * sample covers a unique value or take care to select a neighboring pixel for
  30. * the first sample.
  31. *
  32. * soft contact shadows
  33. * ====================
  34. * If hard screen space shadows are added to a scene that already has soft
  35. * shadows via shadow maps, the hard edge can look out of place. Additionally,
  36. * it is common for screen space shadows to not quite line up with other
  37. * shadows. This is because the depth buffer does not specify thickness,
  38. * leaving some pixels incorrectly occluded. For example, you would not want
  39. * some thin feature like a pipe to cast a shadow as if you were seeing the
  40. * side of a metal wall.
  41. *
  42. * These soft contact shadows are an attempt to minimize the problems described
  43. * above. By adding a smoother falloff, they may blend into the scene better.
  44. * Inspired by screen space ambient occlusion, this sample takes into account
  45. * distance from shadowed pixel to its occluders.
  46. *
  47. * - hard If there's any occluder found, mark the source pixel as shadowed.
  48. *
  49. * - soft Modulate shadow by distance to the first occluder. Assuming a
  50. * nearby pixel is closer and more likely to represent an accurate
  51. * shadow, it is darker. If the first pixel to be an occluder is far
  52. * away, it should likely cast a softer shadow.
  53. *
  54. * - very In addition to the same modulation used by soft mode, also
  55. * soft reduce the occlusion contribution from pixels that are farther
  56. * away. This sample compares the depth difference to the shadow
  57. * radius, a 1D distance, instead of comparing the actually
  58. * distance in 3D space.
  59. */
  60. #include <common.h>
  61. #include <camera.h>
  62. #include <bgfx_utils.h>
  63. #include <imgui/imgui.h>
  64. #include <bx/rng.h>
  65. #include <bx/os.h>
  66. namespace {
  67. // Gbuffer has multiple render targets
  68. #define GBUFFER_RT_COLOR 0
  69. #define GBUFFER_RT_NORMAL 1
  70. #define GBUFFER_RT_DEPTH 2
  71. #define GBUFFER_RENDER_TARGETS 3
  72. #define MODEL_COUNT 100
  73. static const char * s_meshPaths[] =
  74. {
  75. "meshes/unit_sphere.bin",
  76. "meshes/column.bin",
  77. "meshes/tree.bin",
  78. "meshes/hollowcube.bin",
  79. "meshes/bunny.bin"
  80. };
  81. static const float s_meshScale[] =
  82. {
  83. 0.25f,
  84. 0.05f,
  85. 0.15f,
  86. 0.25f,
  87. 0.25f
  88. };
  89. // Vertex decl for our screen space quad (used in deferred rendering)
  90. struct PosTexCoord0Vertex
  91. {
  92. float m_x;
  93. float m_y;
  94. float m_z;
  95. float m_u;
  96. float m_v;
  97. static void init()
  98. {
  99. ms_layout
  100. .begin()
  101. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  102. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  103. .end();
  104. }
  105. static bgfx::VertexLayout ms_layout;
  106. };
  107. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  108. struct Uniforms
  109. {
  110. enum { NumVec4 = 12 };
  111. void init() {
  112. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  113. };
  114. void submit() const {
  115. bgfx::setUniform(u_params, m_params, NumVec4);
  116. }
  117. void destroy() {
  118. bgfx::destroy(u_params);
  119. }
  120. union
  121. {
  122. struct
  123. {
  124. /* 0 */ struct { float m_frameIdx; float m_shadowRadius; float m_shadowSteps; float m_useNoiseOffset; };
  125. /* 1 */ struct { float m_depthUnpackConsts[2]; float m_contactShadowsMode; float m_useScreenSpaceRadius; };
  126. /* 2 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  127. /* 3 */ struct { float m_lightPosition[3]; float m_displayShadows; };
  128. /* 4-7 */ struct { float m_worldToView[16]; }; // built-in u_view will be transform for quad during screen passes
  129. /* 8-11 */ struct { float m_viewToProj[16]; }; // built-in u_proj will be transform for quad during screen passes
  130. };
  131. float m_params[NumVec4 * 4];
  132. };
  133. bgfx::UniformHandle u_params;
  134. };
  135. struct RenderTarget
  136. {
  137. void init(uint32_t _width, uint32_t _height, bgfx::TextureFormat::Enum _format, uint64_t _flags)
  138. {
  139. m_texture = bgfx::createTexture2D(uint16_t(_width), uint16_t(_height), false, 1, _format, _flags);
  140. const bool destroyTextures = true;
  141. m_buffer = bgfx::createFrameBuffer(1, &m_texture, destroyTextures);
  142. }
  143. void destroy()
  144. {
  145. // also responsible for destroying texture
  146. bgfx::destroy(m_buffer);
  147. }
  148. bgfx::TextureHandle m_texture;
  149. bgfx::FrameBufferHandle m_buffer;
  150. };
  151. void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  152. {
  153. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  154. {
  155. bgfx::TransientVertexBuffer vb;
  156. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  157. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  158. const float minx = -_width;
  159. const float maxx = _width;
  160. const float miny = 0.0f;
  161. const float maxy = _height * 2.0f;
  162. const float texelHalfW = _texelHalf / _textureWidth;
  163. const float texelHalfH = _texelHalf / _textureHeight;
  164. const float minu = -1.0f + texelHalfW;
  165. const float maxu = 1.0f + texelHalfW;
  166. const float zz = 0.0f;
  167. float minv = texelHalfH;
  168. float maxv = 2.0f + texelHalfH;
  169. if (_originBottomLeft)
  170. {
  171. float temp = minv;
  172. minv = maxv;
  173. maxv = temp;
  174. minv -= 1.0f;
  175. maxv -= 1.0f;
  176. }
  177. vertex[0].m_x = minx;
  178. vertex[0].m_y = miny;
  179. vertex[0].m_z = zz;
  180. vertex[0].m_u = minu;
  181. vertex[0].m_v = minv;
  182. vertex[1].m_x = maxx;
  183. vertex[1].m_y = miny;
  184. vertex[1].m_z = zz;
  185. vertex[1].m_u = maxu;
  186. vertex[1].m_v = minv;
  187. vertex[2].m_x = maxx;
  188. vertex[2].m_y = maxy;
  189. vertex[2].m_z = zz;
  190. vertex[2].m_u = maxu;
  191. vertex[2].m_v = maxv;
  192. bgfx::setVertexBuffer(0, &vb);
  193. }
  194. }
  195. void vec2Set(float* _v, float _x, float _y)
  196. {
  197. _v[0] = _x;
  198. _v[1] = _y;
  199. }
  200. void mat4Set(float * _m, const float * _src)
  201. {
  202. const uint32_t MAT4_FLOATS = 16;
  203. for (uint32_t ii = 0; ii < MAT4_FLOATS; ++ii) {
  204. _m[ii] = _src[ii];
  205. }
  206. }
  207. class ExampleScreenSpaceShadows : public entry::AppI
  208. {
  209. public:
  210. ExampleScreenSpaceShadows(const char* _name, const char* _description)
  211. : entry::AppI(_name, _description)
  212. , m_currFrame(UINT32_MAX)
  213. , m_texelHalf(0.0f)
  214. {
  215. }
  216. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  217. {
  218. Args args(_argc, _argv);
  219. m_width = _width;
  220. m_height = _height;
  221. m_debug = BGFX_DEBUG_NONE;
  222. m_reset = BGFX_RESET_VSYNC;
  223. bgfx::Init init;
  224. init.type = args.m_type;
  225. init.vendorId = args.m_pciId;
  226. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  227. init.platformData.ndt = entry::getNativeDisplayHandle();
  228. init.resolution.width = m_width;
  229. init.resolution.height = m_height;
  230. init.resolution.reset = m_reset;
  231. bgfx::init(init);
  232. // Enable debug text.
  233. bgfx::setDebug(m_debug);
  234. // Create uniforms
  235. m_uniforms.init();
  236. // Create texture sampler uniforms (used when we bind textures)
  237. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler); // Model's source albedo
  238. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler); // Color (albedo) gbuffer, default color input
  239. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler); // Normal gbuffer, Model's source normal
  240. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler); // Depth gbuffer
  241. s_shadows = bgfx::createUniform("s_shadows", bgfx::UniformType::Sampler);
  242. // Create program from shaders.
  243. m_gbufferProgram = loadProgram("vs_sss_gbuffer", "fs_sss_gbuffer"); // Fill gbuffer
  244. m_sphereProgram = loadProgram("vs_sss_gbuffer", "fs_sss_unlit");
  245. m_linearDepthProgram = loadProgram("vs_sss_screenquad", "fs_sss_linear_depth");
  246. m_shadowsProgram = loadProgram("vs_sss_screenquad", "fs_screen_space_shadows");
  247. m_combineProgram = loadProgram("vs_sss_screenquad", "fs_sss_deferred_combine"); // Compute lighting from gbuffer
  248. // Load some meshes
  249. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  250. {
  251. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  252. }
  253. // sphere is first mesh
  254. m_lightModel.mesh = 0;
  255. // Randomly create some models
  256. bx::RngMwc mwc;
  257. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  258. {
  259. Model& model = m_models[ii];
  260. model.mesh = mwc.gen() % BX_COUNTOF(s_meshPaths);
  261. model.position[0] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  262. model.position[1] = 0;
  263. model.position[2] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  264. }
  265. // Load ground, just use the cube
  266. m_ground = meshLoad("meshes/cube.bin");
  267. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  268. m_normalTexture = loadTexture("textures/fieldstone-n.dds");
  269. m_recreateFrameBuffers = false;
  270. createFramebuffers();
  271. // Vertex decl
  272. PosTexCoord0Vertex::init();
  273. // Init camera
  274. cameraCreate();
  275. cameraSetPosition({ 0.0f, 1.5f, -4.0f });
  276. cameraSetVerticalAngle(-0.3f);
  277. m_fovY = 60.0f;
  278. cameraGetViewMtx(m_view);
  279. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  280. // Track whether previous results are valid
  281. m_havePrevious = false;
  282. // Get renderer capabilities info.
  283. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  284. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  285. imguiCreate();
  286. }
  287. int32_t shutdown() override
  288. {
  289. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  290. {
  291. meshUnload(m_meshes[ii]);
  292. }
  293. meshUnload(m_ground);
  294. bgfx::destroy(m_normalTexture);
  295. bgfx::destroy(m_groundTexture);
  296. bgfx::destroy(m_gbufferProgram);
  297. bgfx::destroy(m_sphereProgram);
  298. bgfx::destroy(m_linearDepthProgram);
  299. bgfx::destroy(m_shadowsProgram);
  300. bgfx::destroy(m_combineProgram);
  301. m_uniforms.destroy();
  302. bgfx::destroy(s_albedo);
  303. bgfx::destroy(s_color);
  304. bgfx::destroy(s_normal);
  305. bgfx::destroy(s_depth);
  306. bgfx::destroy(s_shadows);
  307. destroyFramebuffers();
  308. cameraDestroy();
  309. imguiDestroy();
  310. bgfx::shutdown();
  311. return 0;
  312. }
  313. bool update() override
  314. {
  315. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  316. {
  317. // skip processing when minimized, otherwise crashing
  318. if (0 == m_width
  319. || 0 == m_height)
  320. {
  321. return true;
  322. }
  323. // Update frame timer
  324. int64_t now = bx::getHPCounter();
  325. static int64_t last = now;
  326. const int64_t frameTime = now - last;
  327. last = now;
  328. const double freq = double(bx::getHPFrequency());
  329. const float deltaTime = float(frameTime / freq);
  330. const bgfx::Caps* caps = bgfx::getCaps();
  331. if (m_size[0] != (int32_t)m_width
  332. || m_size[1] != (int32_t)m_height
  333. || m_recreateFrameBuffers)
  334. {
  335. destroyFramebuffers();
  336. createFramebuffers();
  337. m_recreateFrameBuffers = false;
  338. }
  339. // rotate light
  340. const float rotationSpeed = m_moveLight ? 0.75f : 0.0f;
  341. m_lightRotation += deltaTime * rotationSpeed;
  342. if (bx::kPi2 < m_lightRotation)
  343. {
  344. m_lightRotation -= bx::kPi2;
  345. }
  346. m_lightModel.position[0] = bx::cos(m_lightRotation) * 3.0f;
  347. m_lightModel.position[1] = 1.5f;
  348. m_lightModel.position[2] = bx::sin(m_lightRotation) * 3.0f;
  349. // Update camera
  350. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  351. // Set up matrices for gbuffer
  352. cameraGetViewMtx(m_view);
  353. updateUniforms();
  354. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  355. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  356. bgfx::ViewId view = 0;
  357. // Draw everything into gbuffer
  358. {
  359. bgfx::setViewName(view, "gbuffer");
  360. bgfx::setViewClear(view
  361. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  362. , 0
  363. , 1.0f
  364. , 0
  365. );
  366. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  367. bgfx::setViewTransform(view, m_view, m_proj);
  368. // Make sure when we draw it goes into gbuffer and not backbuffer
  369. bgfx::setViewFrameBuffer(view, m_gbuffer);
  370. bgfx::setState(0
  371. | BGFX_STATE_WRITE_RGB
  372. | BGFX_STATE_WRITE_A
  373. | BGFX_STATE_WRITE_Z
  374. | BGFX_STATE_DEPTH_TEST_LESS
  375. );
  376. drawAllModels(view, m_gbufferProgram, m_uniforms);
  377. // draw sphere to visualize light
  378. {
  379. const float scale = s_meshScale[m_lightModel.mesh];
  380. float mtx[16];
  381. bx::mtxSRT(mtx
  382. , scale
  383. , scale
  384. , scale
  385. , 0.0f
  386. , 0.0f
  387. , 0.0f
  388. , m_lightModel.position[0]
  389. , m_lightModel.position[1]
  390. , m_lightModel.position[2]
  391. );
  392. m_uniforms.submit();
  393. meshSubmit(m_meshes[m_lightModel.mesh], view, m_sphereProgram, mtx);
  394. }
  395. ++view;
  396. }
  397. float orthoProj[16];
  398. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  399. {
  400. // clear out transform stack
  401. float identity[16];
  402. bx::mtxIdentity(identity);
  403. bgfx::setTransform(identity);
  404. }
  405. // Convert depth to linear depth for shadow depth compare
  406. {
  407. bgfx::setViewName(view, "linear depth");
  408. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  409. bgfx::setViewTransform(view, NULL, orthoProj);
  410. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  411. bgfx::setState(0
  412. | BGFX_STATE_WRITE_RGB
  413. | BGFX_STATE_WRITE_A
  414. | BGFX_STATE_DEPTH_TEST_ALWAYS
  415. );
  416. bgfx::setTexture(0, s_depth, m_gbufferTex[GBUFFER_RT_DEPTH]);
  417. m_uniforms.submit();
  418. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  419. bgfx::submit(view, m_linearDepthProgram);
  420. ++view;
  421. }
  422. // Do screen space shadows
  423. {
  424. bgfx::setViewName(view, "screen space shadows");
  425. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  426. bgfx::setViewTransform(view, NULL, orthoProj);
  427. bgfx::setViewFrameBuffer(view, m_shadows.m_buffer);
  428. bgfx::setState(0
  429. | BGFX_STATE_WRITE_RGB
  430. | BGFX_STATE_WRITE_A
  431. | BGFX_STATE_DEPTH_TEST_ALWAYS
  432. );
  433. bgfx::setTexture(0, s_depth, m_linearDepth.m_texture);
  434. m_uniforms.submit();
  435. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  436. bgfx::submit(view, m_shadowsProgram);
  437. ++view;
  438. }
  439. // Shade gbuffer
  440. {
  441. bgfx::setViewName(view, "combine");
  442. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  443. bgfx::setViewTransform(view, NULL, orthoProj);
  444. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  445. bgfx::setState(0
  446. | BGFX_STATE_WRITE_RGB
  447. | BGFX_STATE_WRITE_A
  448. | BGFX_STATE_DEPTH_TEST_ALWAYS
  449. );
  450. bgfx::setTexture(0, s_color, m_gbufferTex[GBUFFER_RT_COLOR]);
  451. bgfx::setTexture(1, s_normal, m_gbufferTex[GBUFFER_RT_NORMAL]);
  452. bgfx::setTexture(2, s_depth, m_linearDepth.m_texture);
  453. bgfx::setTexture(3, s_shadows, m_shadows.m_texture);
  454. m_uniforms.submit();
  455. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  456. bgfx::submit(view, m_combineProgram);
  457. ++view;
  458. }
  459. // Draw UI
  460. imguiBeginFrame(m_mouseState.m_mx
  461. , m_mouseState.m_my
  462. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  463. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  464. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  465. , m_mouseState.m_mz
  466. , uint16_t(m_width)
  467. , uint16_t(m_height)
  468. );
  469. showExampleDialog(this);
  470. ImGui::SetNextWindowPos(
  471. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  472. , ImGuiCond_FirstUseEver
  473. );
  474. ImGui::SetNextWindowSize(
  475. ImVec2(m_width / 4.0f, m_height / 2.3f)
  476. , ImGuiCond_FirstUseEver
  477. );
  478. ImGui::Begin("Settings"
  479. , NULL
  480. , 0
  481. );
  482. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  483. {
  484. ImGui::Text("shadow controls:");
  485. ImGui::Checkbox("screen space radius", &m_useScreenSpaceRadius);
  486. if (ImGui::IsItemHovered())
  487. ImGui::SetTooltip("define radius in pixels or world units");
  488. if (m_useScreenSpaceRadius)
  489. {
  490. ImGui::SliderFloat("radius in pixels", &m_shadowRadiusPixels, 1.0f, 100.0f);
  491. }
  492. else
  493. {
  494. ImGui::SliderFloat("radius in world units", &m_shadowRadius, 1e-3f, 1.0f);
  495. }
  496. ImGui::SliderInt("shadow steps", &m_shadowSteps, 1, 64);
  497. if (ImGui::IsItemHovered())
  498. ImGui::SetTooltip("number of steps/samples to take between shaded pixel and radius");
  499. ImGui::Combo("contact shadows mode", &m_contactShadowsMode, "hard\0soft\0very soft\0\0");
  500. if (ImGui::IsItemHovered())
  501. {
  502. ImGui::BeginTooltip();
  503. ImGui::Text("hard");
  504. ImGui::BulletText("any occluder, fully shadowed");
  505. ImGui::Text("soft");
  506. ImGui::BulletText("modulate shadow by distance to first occluder");
  507. ImGui::Text("very soft");
  508. ImGui::BulletText("also reduce each shadow contribution by distance");
  509. ImGui::EndTooltip();
  510. }
  511. ImGui::Checkbox("add random offset to initial position", &m_useNoiseOffset);
  512. if (ImGui::IsItemHovered())
  513. ImGui::SetTooltip("hide banding with noise");
  514. ImGui::Checkbox("use different offset each frame", &m_dynamicNoise);
  515. ImGui::Separator();
  516. ImGui::Text("scene controls:");
  517. ImGui::Checkbox("display shadows only", &m_displayShadows);
  518. ImGui::Checkbox("move light", &m_moveLight);
  519. }
  520. ImGui::End();
  521. imguiEndFrame();
  522. // Advance to next frame. Rendering thread will be kicked to
  523. // process submitted rendering primitives.
  524. m_currFrame = bgfx::frame();
  525. return true;
  526. }
  527. return false;
  528. }
  529. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, const Uniforms & _uniforms)
  530. {
  531. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  532. {
  533. const Model& model = m_models[ii];
  534. // Set up transform matrix for each model
  535. const float scale = s_meshScale[model.mesh];
  536. float mtx[16];
  537. bx::mtxSRT(mtx
  538. , scale
  539. , scale
  540. , scale
  541. , 0.0f
  542. , 0.0f
  543. , 0.0f
  544. , model.position[0]
  545. , model.position[1]
  546. , model.position[2]
  547. );
  548. // Submit mesh to gbuffer
  549. bgfx::setTexture(0, s_albedo, m_groundTexture);
  550. bgfx::setTexture(1, s_normal, m_normalTexture);
  551. _uniforms.submit();
  552. meshSubmit(m_meshes[model.mesh], _pass, _program, mtx);
  553. }
  554. // Draw ground
  555. float mtxScale[16];
  556. const float scale = 10.0f;
  557. bx::mtxScale(mtxScale, scale, scale, scale);
  558. float mtxTranslate[16];
  559. bx::mtxTranslate(mtxTranslate
  560. , 0.0f
  561. , -10.0f
  562. , 0.0f
  563. );
  564. float mtx[16];
  565. bx::mtxMul(mtx, mtxScale, mtxTranslate);
  566. bgfx::setTexture(0, s_albedo, m_groundTexture);
  567. bgfx::setTexture(1, s_normal, m_normalTexture);
  568. _uniforms.submit();
  569. meshSubmit(m_ground, _pass, _program, mtx);
  570. }
  571. void createFramebuffers()
  572. {
  573. m_size[0] = m_width;
  574. m_size[1] = m_height;
  575. const uint64_t pointSampleFlags = 0
  576. | BGFX_TEXTURE_RT
  577. | BGFX_SAMPLER_U_CLAMP
  578. | BGFX_SAMPLER_V_CLAMP
  579. | BGFX_SAMPLER_MIN_POINT
  580. | BGFX_SAMPLER_MAG_POINT
  581. | BGFX_SAMPLER_MIP_POINT
  582. ;
  583. m_gbufferTex[GBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, pointSampleFlags);
  584. m_gbufferTex[GBUFFER_RT_NORMAL] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, pointSampleFlags);
  585. m_gbufferTex[GBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, pointSampleFlags);
  586. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_gbufferTex), m_gbufferTex, true);
  587. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, pointSampleFlags);
  588. m_shadows.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, pointSampleFlags);
  589. }
  590. // all buffers set to destroy their textures
  591. void destroyFramebuffers()
  592. {
  593. bgfx::destroy(m_gbuffer);
  594. m_linearDepth.destroy();
  595. m_shadows.destroy();
  596. }
  597. void updateUniforms()
  598. {
  599. m_uniforms.m_displayShadows = m_displayShadows ? 1.0f : 0.0f;
  600. m_uniforms.m_frameIdx = m_dynamicNoise
  601. ? float(m_currFrame % 8)
  602. : 0.0f;
  603. m_uniforms.m_shadowRadius = m_useScreenSpaceRadius ? m_shadowRadiusPixels : m_shadowRadius;
  604. m_uniforms.m_shadowSteps = float(m_shadowSteps);
  605. m_uniforms.m_useNoiseOffset = m_useNoiseOffset ? 1.0f : 0.0f;
  606. m_uniforms.m_contactShadowsMode = float(m_contactShadowsMode);
  607. m_uniforms.m_useScreenSpaceRadius = m_useScreenSpaceRadius ? 1.0f : 0.0f;
  608. mat4Set(m_uniforms.m_worldToView, m_view);
  609. mat4Set(m_uniforms.m_viewToProj, m_proj);
  610. // from assao sample, cs_assao_prepare_depths.sc
  611. {
  612. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  613. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  614. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  615. float depthLinearizeMul = -m_proj2[3*4+2];
  616. float depthLinearizeAdd = m_proj2[2*4+2];
  617. if (depthLinearizeMul * depthLinearizeAdd < 0)
  618. {
  619. depthLinearizeAdd = -depthLinearizeAdd;
  620. }
  621. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  622. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  623. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  624. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  625. {
  626. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  627. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  628. }
  629. else
  630. {
  631. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  632. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  633. }
  634. }
  635. {
  636. float lightPosition[4];
  637. bx::memCopy(lightPosition, m_lightModel.position, 3*sizeof(float));
  638. lightPosition[3] = 1.0f;
  639. float viewSpaceLightPosition[4];
  640. bx::vec4MulMtx(viewSpaceLightPosition, lightPosition, m_view);
  641. bx::memCopy(m_uniforms.m_lightPosition, viewSpaceLightPosition, 3*sizeof(float));
  642. }
  643. }
  644. uint32_t m_width;
  645. uint32_t m_height;
  646. uint32_t m_debug;
  647. uint32_t m_reset;
  648. entry::MouseState m_mouseState;
  649. // Resource handles
  650. bgfx::ProgramHandle m_gbufferProgram;
  651. bgfx::ProgramHandle m_sphereProgram;
  652. bgfx::ProgramHandle m_linearDepthProgram;
  653. bgfx::ProgramHandle m_shadowsProgram;
  654. bgfx::ProgramHandle m_combineProgram;
  655. // Shader uniforms
  656. Uniforms m_uniforms;
  657. // Uniforms to identify texture samplers
  658. bgfx::UniformHandle s_albedo;
  659. bgfx::UniformHandle s_color;
  660. bgfx::UniformHandle s_normal;
  661. bgfx::UniformHandle s_depth;
  662. bgfx::UniformHandle s_shadows;
  663. bgfx::FrameBufferHandle m_gbuffer;
  664. bgfx::TextureHandle m_gbufferTex[GBUFFER_RENDER_TARGETS];
  665. RenderTarget m_linearDepth;
  666. RenderTarget m_shadows;
  667. struct Model
  668. {
  669. uint32_t mesh; // Index of mesh in m_meshes
  670. float position[3];
  671. };
  672. Model m_lightModel;
  673. Model m_models[MODEL_COUNT];
  674. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  675. Mesh* m_ground;
  676. bgfx::TextureHandle m_groundTexture;
  677. bgfx::TextureHandle m_normalTexture;
  678. uint32_t m_currFrame;
  679. float m_lightRotation = 0.0f;
  680. float m_texelHalf = 0.0f;
  681. float m_fovY = 60.0f;
  682. bool m_recreateFrameBuffers = false;
  683. bool m_havePrevious = false;
  684. float m_view[16];
  685. float m_proj[16];
  686. float m_proj2[16];
  687. int32_t m_size[2];
  688. // UI parameters
  689. bool m_displayShadows = false;
  690. bool m_useNoiseOffset = true;
  691. bool m_dynamicNoise = true;
  692. float m_shadowRadius = 0.25f;
  693. float m_shadowRadiusPixels = 25.0f;
  694. int32_t m_shadowSteps = 8;
  695. bool m_moveLight = true;
  696. int32_t m_contactShadowsMode = 0;
  697. bool m_useScreenSpaceRadius = false;
  698. };
  699. } // namespace
  700. ENTRY_IMPLEMENT_MAIN(
  701. ExampleScreenSpaceShadows
  702. , "44-sss"
  703. , "Screen Space Shadows."
  704. );