assao.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. /*
  2. * Copyright 2018 Attila Kocsis. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. /*
  6. * Reference(s):
  7. * - ASSAO is a SSAO implementation tuned for scalability and flexibility.
  8. * https://web.archive.org/web/20181214222937/https://software.intel.com/en-us/articles/adaptive-screen-space-ambient-occlusion
  9. * https://github.com/GameTechDev/ASSAO
  10. */
  11. #include <common.h>
  12. #include <camera.h>
  13. #include <bgfx_utils.h>
  14. #include <imgui/imgui.h>
  15. #include <bx/rng.h>
  16. #include <bx/os.h>
  17. #define USE_ASSAO 0
  18. namespace
  19. {
  20. // Render passes
  21. #define RENDER_PASS_GBUFFER 0 // GBuffer for normals and albedo
  22. #define RENDER_PASS_COMBINE 1 // Directional light and final result
  23. // Gbuffer has multiple render targets
  24. #define GBUFFER_RT_NORMAL 0
  25. #define GBUFFER_RT_COLOR 1
  26. #define GBUFFER_RT_DEPTH 2
  27. // Random meshes we draw
  28. #define MODEL_COUNT 120 // In this demo, a model is a mesh plus a transform
  29. #define SAMPLER_POINT_CLAMP (BGFX_SAMPLER_POINT|BGFX_SAMPLER_UVW_CLAMP)
  30. #define SAMPLER_POINT_MIRROR (BGFX_SAMPLER_POINT|BGFX_SAMPLER_UVW_MIRROR)
  31. #define SAMPLER_LINEAR_CLAMP (BGFX_SAMPLER_UVW_CLAMP)
  32. #define SSAO_DEPTH_MIP_LEVELS 4
  33. static const char * s_meshPaths[] =
  34. {
  35. "meshes/cube.bin",
  36. "meshes/orb.bin",
  37. "meshes/column.bin",
  38. "meshes/bunny_decimated.bin",
  39. "meshes/tree.bin",
  40. "meshes/hollowcube.bin"
  41. };
  42. static const float s_meshScale[] =
  43. {
  44. 0.25f,
  45. 0.5f,
  46. 0.05f,
  47. 0.5f,
  48. 0.05f,
  49. 0.25f
  50. };
  51. // Vertex layout for our screen space quad (used in deferred rendering)
  52. struct PosTexCoord0Vertex
  53. {
  54. float m_x;
  55. float m_y;
  56. float m_z;
  57. float m_u;
  58. float m_v;
  59. static void init()
  60. {
  61. ms_layout
  62. .begin()
  63. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  64. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  65. .end();
  66. }
  67. static bgfx::VertexLayout ms_layout;
  68. };
  69. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  70. // Utility function to draw a screen space quad for deferred rendering
  71. void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  72. {
  73. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  74. {
  75. bgfx::TransientVertexBuffer vb;
  76. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  77. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  78. const float minx = -_width;
  79. const float maxx = _width;
  80. const float miny = 0.0f;
  81. const float maxy = _height * 2.0f;
  82. const float texelHalfW = _texelHalf / _textureWidth;
  83. const float texelHalfH = _texelHalf / _textureHeight;
  84. const float minu = -1.0f + texelHalfW;
  85. const float maxu = 1.0f + texelHalfH;
  86. const float zz = 0.0f;
  87. float minv = texelHalfH;
  88. float maxv = 2.0f + texelHalfH;
  89. if (_originBottomLeft)
  90. {
  91. float temp = minv;
  92. minv = maxv;
  93. maxv = temp;
  94. minv -= 1.0f;
  95. maxv -= 1.0f;
  96. }
  97. vertex[0].m_x = minx;
  98. vertex[0].m_y = miny;
  99. vertex[0].m_z = zz;
  100. vertex[0].m_u = minu;
  101. vertex[0].m_v = minv;
  102. vertex[1].m_x = maxx;
  103. vertex[1].m_y = miny;
  104. vertex[1].m_z = zz;
  105. vertex[1].m_u = maxu;
  106. vertex[1].m_v = minv;
  107. vertex[2].m_x = maxx;
  108. vertex[2].m_y = maxy;
  109. vertex[2].m_z = zz;
  110. vertex[2].m_u = maxu;
  111. vertex[2].m_v = maxv;
  112. bgfx::setVertexBuffer(0, &vb);
  113. }
  114. }
  115. struct Settings
  116. {
  117. float m_radius; // [0.0, ~ ] World (view) space size of the occlusion sphere.
  118. float m_shadowMultiplier; // [0.0, 5.0] Effect strength linear multiplier
  119. float m_shadowPower; // [0.5, 5.0] Effect strength pow modifier
  120. float m_shadowClamp; // [0.0, 1.0] Effect max limit (applied after multiplier but before blur)
  121. float m_horizonAngleThreshold; // [0.0, 0.2] Limits self-shadowing (makes the sampling area less of a hemisphere, more of a spherical cone, to avoid self-shadowing and various artifacts due to low tessellation and depth buffer imprecision, etc.)
  122. float m_fadeOutFrom; // [0.0, ~ ] Distance to start start fading out the effect.
  123. float m_fadeOutTo; // [0.0, ~ ] Distance at which the effect is faded out.
  124. int32_t m_qualityLevel; // [ -1, 3 ] Effect quality; -1 - lowest (low, half res checkerboard), 0 - low, 1 - medium, 2 - high, 3 - very high / adaptive; each quality level is roughly 2x more costly than the previous, except the q3 which is variable but, in general, above q2.
  125. float m_adaptiveQualityLimit; // [0.0, 1.0] (only for Quality Level 3)
  126. int32_t m_blurPassCount; // [ 0, 6] Number of edge-sensitive smart blur passes to apply. Quality 0 is an exception with only one 'dumb' blur pass used.
  127. float m_sharpness; // [0.0, 1.0] (How much to bleed over edges; 1: not at all, 0.5: half-half; 0.0: completely ignore edges)
  128. float m_temporalSupersamplingAngleOffset; // [0.0, PI] Used to rotate sampling kernel; If using temporal AA / supersampling, suggested to rotate by ( (frame%3)/3.0*PI ) or similar. Kernel is already symmetrical, which is why we use PI and not 2*PI.
  129. float m_temporalSupersamplingRadiusOffset; // [0.0, 2.0] Used to scale sampling kernel; If using temporal AA / supersampling, suggested to scale by ( 1.0f + (((frame%3)-1.0)/3.0)*0.1 ) or similar.
  130. float m_detailShadowStrength; // [0.0, 5.0] Used for high-res detail AO using neighboring depth pixels: adds a lot of detail but also reduces temporal stability (adds aliasing).
  131. bool m_generateNormals; // [true/false] If true normals will be generated from depth.
  132. Settings()
  133. {
  134. m_radius = 1.2f;
  135. m_shadowMultiplier = 1.0f;
  136. m_shadowPower = 1.50f;
  137. m_shadowClamp = 0.98f;
  138. m_horizonAngleThreshold = 0.06f;
  139. m_fadeOutFrom = 50.0f;
  140. m_fadeOutTo = 200.0f;
  141. m_adaptiveQualityLimit = 0.45f;
  142. m_qualityLevel = 3;
  143. m_blurPassCount = 2;
  144. m_sharpness = 0.98f;
  145. m_temporalSupersamplingAngleOffset = 0.0f;
  146. m_temporalSupersamplingRadiusOffset = 1.0f;
  147. m_detailShadowStrength = 0.5f;
  148. m_generateNormals = true;
  149. }
  150. };
  151. struct Uniforms
  152. {
  153. enum { NumVec4 = 19 };
  154. void init()
  155. {
  156. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  157. }
  158. void submit()
  159. {
  160. bgfx::setUniform(u_params, m_params, NumVec4);
  161. }
  162. void destroy()
  163. {
  164. bgfx::destroy(u_params);
  165. }
  166. union
  167. {
  168. struct
  169. {
  170. /* 0 */ struct { float m_viewportPixelSize[2]; float m_halfViewportPixelSize[2]; };
  171. /* 1 */ struct { float m_depthUnpackConsts[2]; float m_unused0[2]; };
  172. /* 2 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  173. /* 3 */ struct { float m_perPassFullResCoordOffset[2]; float m_perPassFullResUVOffset[2]; };
  174. /* 4 */ struct { float m_viewport2xPixelSize[2]; float m_viewport2xPixelSize_x_025[2]; };
  175. /* 5 */ struct { float m_effectRadius; float m_effectShadowStrength; float m_effectShadowPow; float m_effectShadowClamp; };
  176. /* 6 */ struct { float m_effectFadeOutMul; float m_effectFadeOutAdd; float m_effectHorizonAngleThreshold; float m_effectSamplingRadiusNearLimitRec; };
  177. /* 7 */ struct { float m_depthPrecisionOffsetMod; float m_negRecEffectRadius; float m_loadCounterAvgDiv; float m_adaptiveSampleCountLimit; };
  178. /* 8 */ struct { float m_invSharpness; float m_passIndex; float m_quarterResPixelSize[2]; };
  179. /* 9-13 */ struct { float m_patternRotScaleMatrices[5][4]; };
  180. /* 14 */ struct { float m_normalsUnpackMul; float m_normalsUnpackAdd; float m_detailAOStrength; float m_layer; };
  181. /* 15-18 */ struct { float m_normalsWorldToViewspaceMatrix[16]; };
  182. };
  183. float m_params[NumVec4 * 4];
  184. };
  185. bgfx::UniformHandle u_params;
  186. };
  187. void vec2Set(float* _v, float _x, float _y)
  188. {
  189. _v[0] = _x;
  190. _v[1] = _y;
  191. }
  192. void vec4Set(float* _v, float _x, float _y, float _z, float _w)
  193. {
  194. _v[0] = _x;
  195. _v[1] = _y;
  196. _v[2] = _z;
  197. _v[3] = _w;
  198. }
  199. void vec4iSet(int32_t* _v, int32_t _x, int32_t _y, int32_t _z, int32_t _w)
  200. {
  201. _v[0] = _x;
  202. _v[1] = _y;
  203. _v[2] = _z;
  204. _v[3] = _w;
  205. }
  206. static const int32_t cMaxBlurPassCount = 6;
  207. class ExampleASSAO : public entry::AppI
  208. {
  209. public:
  210. ExampleASSAO(const char* _name, const char* _description, const char* _url)
  211. : entry::AppI(_name, _description, _url)
  212. , m_currFrame(UINT32_MAX)
  213. , m_enableSSAO(true)
  214. , m_enableTexturing(true)
  215. , m_texelHalf(0.0f)
  216. , m_framebufferGutter(true)
  217. {
  218. }
  219. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  220. {
  221. Args args(_argc, _argv);
  222. m_width = _width;
  223. m_height = _height;
  224. m_debug = BGFX_DEBUG_NONE;
  225. m_reset = BGFX_RESET_VSYNC;
  226. bgfx::Init init;
  227. init.type = args.m_type;
  228. init.vendorId = args.m_pciId;
  229. init.resolution.width = m_width;
  230. init.resolution.height = m_height;
  231. init.resolution.reset = m_reset;
  232. bgfx::init(init);
  233. // Enable debug text.
  234. bgfx::setDebug(m_debug);
  235. // Labeling for renderdoc captures, etc
  236. bgfx::setViewName(RENDER_PASS_GBUFFER, "gbuffer");
  237. bgfx::setViewName(RENDER_PASS_COMBINE, "post combine");
  238. // Set up screen clears
  239. bgfx::setViewClear(RENDER_PASS_GBUFFER
  240. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  241. , 0
  242. , 1.0f
  243. , 0
  244. );
  245. // Create uniforms
  246. u_combineParams = bgfx::createUniform("u_combineParams", bgfx::UniformType::Vec4, 2);
  247. u_rect = bgfx::createUniform("u_rect", bgfx::UniformType::Vec4); // viewport/scissor rect for compute
  248. m_uniforms.init();
  249. // Create texture sampler uniforms (used when we bind textures)
  250. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler); // Normal gbuffer
  251. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler); // Normal gbuffer
  252. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler); // Color (albedo) gbuffer
  253. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  254. s_ao = bgfx::createUniform("s_ao", bgfx::UniformType::Sampler);
  255. s_blurInput = bgfx::createUniform("s_blurInput", bgfx::UniformType::Sampler);
  256. s_finalSSAO = bgfx::createUniform("s_finalSSAO", bgfx::UniformType::Sampler);
  257. s_depthSource = bgfx::createUniform("s_depthSource", bgfx::UniformType::Sampler);
  258. s_viewspaceDepthSource = bgfx::createUniform("s_viewspaceDepthSource", bgfx::UniformType::Sampler);
  259. s_viewspaceDepthSourceMirror = bgfx::createUniform("s_viewspaceDepthSourceMirror", bgfx::UniformType::Sampler);
  260. s_importanceMap = bgfx::createUniform("s_importanceMap", bgfx::UniformType::Sampler);
  261. // Create program from shaders.
  262. m_gbufferProgram = loadProgram("vs_assao_gbuffer", "fs_assao_gbuffer"); // Gbuffer
  263. m_combineProgram = loadProgram("vs_assao", "fs_assao_deferred_combine");
  264. m_prepareDepthsProgram = loadProgram("cs_assao_prepare_depths", NULL);
  265. m_prepareDepthsAndNormalsProgram = loadProgram("cs_assao_prepare_depths_and_normals", NULL);
  266. m_prepareDepthsHalfProgram = loadProgram("cs_assao_prepare_depths_half", NULL);
  267. m_prepareDepthsAndNormalsHalfProgram = loadProgram("cs_assao_prepare_depths_and_normals_half", NULL);
  268. m_prepareDepthMipProgram = loadProgram("cs_assao_prepare_depth_mip", NULL);
  269. m_generateQ0Program = loadProgram("cs_assao_generate_q0", NULL);
  270. m_generateQ1Program = loadProgram("cs_assao_generate_q1", NULL);
  271. m_generateQ2Program = loadProgram("cs_assao_generate_q2", NULL);
  272. m_generateQ3Program = loadProgram("cs_assao_generate_q3", NULL);
  273. m_generateQ3BaseProgram = loadProgram("cs_assao_generate_q3base", NULL);
  274. m_smartBlurProgram = loadProgram("cs_assao_smart_blur", NULL);
  275. m_smartBlurWideProgram = loadProgram("cs_assao_smart_blur_wide", NULL);
  276. m_nonSmartBlurProgram = loadProgram("cs_assao_non_smart_blur", NULL);
  277. m_applyProgram = loadProgram("cs_assao_apply", NULL);
  278. m_nonSmartApplyProgram = loadProgram("cs_assao_non_smart_apply", NULL);
  279. m_nonSmartHalfApplyProgram = loadProgram("cs_assao_non_smart_half_apply", NULL);
  280. m_generateImportanceMapProgram = loadProgram("cs_assao_generate_importance_map", NULL);
  281. m_postprocessImportanceMapAProgram = loadProgram("cs_assao_postprocess_importance_map_a", NULL);
  282. m_postprocessImportanceMapBProgram = loadProgram("cs_assao_postprocess_importance_map_b", NULL);
  283. m_loadCounterClearProgram = loadProgram("cs_assao_load_counter_clear", NULL);
  284. // Load some meshes
  285. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  286. {
  287. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  288. }
  289. // Randomly create some models
  290. bx::RngMwc mwc; // Random number generator
  291. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  292. {
  293. Model& model = m_models[ii];
  294. model.mesh = 1 + mwc.gen() % (BX_COUNTOF(s_meshPaths) - 1);
  295. model.position[0] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  296. model.position[1] = 0;
  297. model.position[2] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  298. }
  299. // Load ground. We'll just use the cube since I don't have a ground model right now
  300. m_ground = meshLoad("meshes/cube.bin");
  301. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  302. const bgfx::Memory* mem = bgfx::alloc(4);
  303. bx::memSet(mem->data, 0xc0, 4);
  304. m_modelTexture = bgfx::createTexture2D(1,1, false, 1, bgfx::TextureFormat::RGBA8, 0, mem);
  305. m_recreateFrameBuffers = false;
  306. createFramebuffers();
  307. m_loadCounter = bgfx::createDynamicIndexBuffer(1, BGFX_BUFFER_COMPUTE_READ_WRITE | BGFX_BUFFER_INDEX32);
  308. // Vertex layout
  309. PosTexCoord0Vertex::init();
  310. // Init camera
  311. cameraCreate();
  312. cameraSetPosition({ 0.0f, 1.5f, 0.0f });
  313. cameraSetVerticalAngle(-0.3f);
  314. m_fovY = 60.0f;
  315. // Get renderer capabilities info.
  316. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  317. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  318. imguiCreate();
  319. }
  320. int32_t shutdown() 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. bgfx::destroy(m_groundTexture);
  328. bgfx::destroy(m_modelTexture);
  329. // Cleanup.
  330. bgfx::destroy(m_gbufferProgram);
  331. bgfx::destroy(m_combineProgram);
  332. bgfx::destroy(m_prepareDepthsProgram);
  333. bgfx::destroy(m_prepareDepthsAndNormalsProgram);
  334. bgfx::destroy(m_prepareDepthsHalfProgram);
  335. bgfx::destroy(m_prepareDepthsAndNormalsHalfProgram);
  336. bgfx::destroy(m_prepareDepthMipProgram);
  337. bgfx::destroy(m_generateQ0Program);
  338. bgfx::destroy(m_generateQ1Program);
  339. bgfx::destroy(m_generateQ2Program);
  340. bgfx::destroy(m_generateQ3Program);
  341. bgfx::destroy(m_generateQ3BaseProgram);
  342. bgfx::destroy(m_smartBlurProgram);
  343. bgfx::destroy(m_smartBlurWideProgram);
  344. bgfx::destroy(m_nonSmartBlurProgram);
  345. bgfx::destroy(m_applyProgram);
  346. bgfx::destroy(m_nonSmartApplyProgram);
  347. bgfx::destroy(m_nonSmartHalfApplyProgram);
  348. bgfx::destroy(m_generateImportanceMapProgram);
  349. bgfx::destroy(m_postprocessImportanceMapAProgram);
  350. bgfx::destroy(m_postprocessImportanceMapBProgram);
  351. bgfx::destroy(m_loadCounterClearProgram);
  352. bgfx::destroy(m_combineProgram);
  353. m_uniforms.destroy();
  354. bgfx::destroy(u_combineParams);
  355. bgfx::destroy(u_rect);
  356. bgfx::destroy(s_normal);
  357. bgfx::destroy(s_depth);
  358. bgfx::destroy(s_color);
  359. bgfx::destroy(s_albedo);
  360. bgfx::destroy(s_ao);
  361. bgfx::destroy(s_blurInput);
  362. bgfx::destroy(s_finalSSAO);
  363. bgfx::destroy(s_depthSource);
  364. bgfx::destroy(s_viewspaceDepthSource);
  365. bgfx::destroy(s_viewspaceDepthSourceMirror);
  366. bgfx::destroy(s_importanceMap);
  367. bgfx::destroy(m_loadCounter);
  368. destroyFramebuffers();
  369. cameraDestroy();
  370. imguiDestroy();
  371. // Shutdown bgfx.
  372. bgfx::shutdown();
  373. return 0;
  374. }
  375. bool update() override
  376. {
  377. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  378. {
  379. // Update frame timer
  380. int64_t now = bx::getHPCounter();
  381. static int64_t last = now;
  382. const int64_t frameTime = now - last;
  383. last = now;
  384. const double freq = double(bx::getHPFrequency());
  385. const float deltaTime = float(frameTime / freq);
  386. const bgfx::Caps* caps = bgfx::getCaps();
  387. if (m_size[0] != (int32_t)m_width + 2*m_border
  388. || m_size[1] != (int32_t)m_height + 2*m_border
  389. || m_recreateFrameBuffers)
  390. {
  391. destroyFramebuffers();
  392. createFramebuffers();
  393. m_recreateFrameBuffers = false;
  394. }
  395. // Update camera
  396. cameraUpdate(deltaTime*0.15f, m_mouseState);
  397. // Set up matrices for gbuffer
  398. cameraGetViewMtx(m_view);
  399. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  400. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.1f, 100.0f, false);
  401. bgfx::setViewRect(RENDER_PASS_GBUFFER, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  402. bgfx::setViewTransform(RENDER_PASS_GBUFFER, m_view, m_proj);
  403. // Make sure when we draw it goes into gbuffer and not backbuffer
  404. bgfx::setViewFrameBuffer(RENDER_PASS_GBUFFER, m_gbuffer);
  405. // Draw everything into g-buffer
  406. drawAllModels(RENDER_PASS_GBUFFER, m_gbufferProgram);
  407. // Set up transform matrix for fullscreen quad
  408. #if USE_ASSAO == 1
  409. float orthoProj[16];
  410. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  411. bgfx::setViewTransform(RENDER_PASS_COMBINE, NULL, orthoProj);
  412. bgfx::setViewRect(RENDER_PASS_COMBINE, 0, 0, uint16_t(m_width), uint16_t(m_height));
  413. // Bind vertex buffer and draw quad
  414. screenSpaceQuad((float)m_width, (float)m_height, m_texelHalf, caps->originBottomLeft);
  415. //bgfx::submit(RENDER_PASS_COMBINE, m_combineProgram);
  416. bgfx::touch(RENDER_PASS_COMBINE);
  417. BX_UNUSED(orthoProj, caps)
  418. #endif
  419. // ASSAO passes
  420. #if USE_ASSAO == 0
  421. updateUniforms(0);
  422. bgfx::ViewId view = 2;
  423. bgfx::setViewName(view, "ASSAO");
  424. {
  425. bgfx::setTexture(0, s_depthSource, bgfx::getTexture(m_gbuffer, GBUFFER_RT_DEPTH), SAMPLER_POINT_CLAMP);
  426. m_uniforms.submit();
  427. if (m_settings.m_generateNormals)
  428. {
  429. bgfx::setImage(5, m_normals, 0, bgfx::Access::Write, bgfx::TextureFormat::RGBA8);
  430. }
  431. if (m_settings.m_qualityLevel < 0)
  432. {
  433. for (int32_t j = 0; j < 2; ++j)
  434. {
  435. bgfx::setImage((uint8_t)(j + 1), m_halfDepths[j == 0 ? 0 : 3], 0, bgfx::Access::Write, bgfx::TextureFormat::R16F);
  436. }
  437. bgfx::dispatch(view, m_settings.m_generateNormals ? m_prepareDepthsAndNormalsHalfProgram : m_prepareDepthsHalfProgram, (m_halfSize[0] + 7) / 8, (m_halfSize[1] + 7) / 8);
  438. }
  439. else
  440. {
  441. for(int32_t j = 0; j < 4; ++j)
  442. {
  443. bgfx::setImage((uint8_t)(j+1), m_halfDepths[j], 0, bgfx::Access::Write, bgfx::TextureFormat::R16F);
  444. }
  445. bgfx::dispatch(view, m_settings.m_generateNormals ? m_prepareDepthsAndNormalsProgram : m_prepareDepthsProgram, (m_halfSize[0] + 7) / 8, (m_halfSize[1] + 7) / 8);
  446. }
  447. }
  448. // only do mipmaps for higher quality levels (not beneficial on quality level 1, and detrimental on quality level 0)
  449. if (m_settings.m_qualityLevel > 1)
  450. {
  451. uint16_t mipWidth = (uint16_t)m_halfSize[0];
  452. uint16_t mipHeight = (uint16_t)m_halfSize[1];
  453. for (uint8_t i = 1; i < SSAO_DEPTH_MIP_LEVELS; i++)
  454. {
  455. mipWidth = (uint16_t)bx::max(1, mipWidth >> 1);
  456. mipHeight = (uint16_t)bx::max(1, mipHeight >> 1);
  457. for (uint8_t j = 0; j < 4; ++j)
  458. {
  459. bgfx::setImage(j, m_halfDepths[j], i-1, bgfx::Access::Read, bgfx::TextureFormat::R16F);
  460. bgfx::setImage(j + 4, m_halfDepths[j], i, bgfx::Access::Write, bgfx::TextureFormat::R16F);
  461. }
  462. m_uniforms.submit();
  463. float rect[4] = { 0.0f, 0.0f, (float)mipWidth, (float)mipHeight };
  464. bgfx::setUniform(u_rect, rect);
  465. bgfx::dispatch(view, m_prepareDepthMipProgram, (mipWidth + 7) / 8, (mipHeight + 7) / 8);
  466. }
  467. }
  468. // for adaptive quality, importance map pass
  469. for (int32_t ssaoPass = 0; ssaoPass < 2; ++ssaoPass)
  470. {
  471. if (ssaoPass == 0
  472. && m_settings.m_qualityLevel < 3)
  473. {
  474. continue;
  475. }
  476. bool adaptiveBasePass = (ssaoPass == 0);
  477. BX_UNUSED(adaptiveBasePass);
  478. int32_t passCount = 4;
  479. int32_t halfResNumX = (m_halfResOutScissorRect[2] - m_halfResOutScissorRect[0] + 7) / 8;
  480. int32_t halfResNumY = (m_halfResOutScissorRect[3] - m_halfResOutScissorRect[1] + 7) / 8;
  481. float halfResRect[4] = { (float)m_halfResOutScissorRect[0], (float)m_halfResOutScissorRect[1], (float)m_halfResOutScissorRect[2], (float)m_halfResOutScissorRect[3] };
  482. for (int32_t pass = 0; pass < passCount; pass++)
  483. {
  484. if (m_settings.m_qualityLevel < 0
  485. && (pass == 1 || pass == 2) )
  486. {
  487. continue;
  488. }
  489. int32_t blurPasses = m_settings.m_blurPassCount;
  490. blurPasses = bx::min(blurPasses, cMaxBlurPassCount);
  491. if (m_settings.m_qualityLevel == 3)
  492. {
  493. // if adaptive, at least one blur pass needed as the first pass needs to read the final texture results - kind of awkward
  494. if (adaptiveBasePass)
  495. {
  496. blurPasses = 0;
  497. }
  498. else
  499. {
  500. blurPasses = bx::max(1, blurPasses);
  501. }
  502. }
  503. else if (m_settings.m_qualityLevel <= 0)
  504. {
  505. // just one blur pass allowed for minimum quality
  506. blurPasses = bx::min(1, m_settings.m_blurPassCount);
  507. }
  508. updateUniforms(pass);
  509. bgfx::TextureHandle pPingRT = m_pingPongHalfResultA;
  510. bgfx::TextureHandle pPongRT = m_pingPongHalfResultB;
  511. // Generate
  512. {
  513. bgfx::setImage(6, blurPasses == 0 ? m_finalResults : pPingRT, 0, bgfx::Access::Write, bgfx::TextureFormat::RG8);
  514. bgfx::setUniform(u_rect, halfResRect);
  515. bgfx::setTexture(0, s_viewspaceDepthSource, m_halfDepths[pass], SAMPLER_POINT_CLAMP);
  516. bgfx::setTexture(1, s_viewspaceDepthSourceMirror, m_halfDepths[pass], SAMPLER_POINT_MIRROR);
  517. if (m_settings.m_generateNormals)
  518. bgfx::setImage(2, m_normals,0, bgfx::Access::Read, bgfx::TextureFormat::RGBA8);
  519. else
  520. bgfx::setImage(2, bgfx::getTexture(m_gbuffer, GBUFFER_RT_NORMAL), 0, bgfx::Access::Read, bgfx::TextureFormat::RGBA8);
  521. if (!adaptiveBasePass && (m_settings.m_qualityLevel == 3))
  522. {
  523. bgfx::setBuffer(3, m_loadCounter, bgfx::Access::Read);
  524. bgfx::setTexture(4, s_importanceMap, m_importanceMap, SAMPLER_LINEAR_CLAMP);
  525. bgfx::setImage(5, m_finalResults, 0, bgfx::Access::Read, bgfx::TextureFormat::RG8);
  526. }
  527. bgfx::ProgramHandle programs[5] = { m_generateQ0Program, m_generateQ1Program , m_generateQ2Program , m_generateQ3Program , m_generateQ3BaseProgram };
  528. int32_t programIndex = bx::max(0, (!adaptiveBasePass) ? (m_settings.m_qualityLevel) : (4));
  529. m_uniforms.m_layer = blurPasses == 0 ? (float)pass : 0.0f;
  530. m_uniforms.submit();
  531. bgfx::dispatch(view, programs[programIndex], halfResNumX, halfResNumY);
  532. }
  533. // Blur
  534. if (blurPasses > 0)
  535. {
  536. int32_t wideBlursRemaining = bx::max(0, blurPasses - 2);
  537. for (int32_t i = 0; i < blurPasses; i++)
  538. {
  539. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  540. bgfx::touch(view);
  541. m_uniforms.m_layer = ((i == (blurPasses - 1)) ? (float)pass : 0.0f);
  542. m_uniforms.submit();
  543. bgfx::setUniform(u_rect, halfResRect);
  544. bgfx::setImage(0, i == (blurPasses - 1) ? m_finalResults : pPongRT, 0, bgfx::Access::Write, bgfx::TextureFormat::RG8);
  545. bgfx::setTexture(1, s_blurInput, pPingRT, m_settings.m_qualityLevel > 0 ? SAMPLER_POINT_MIRROR : SAMPLER_LINEAR_CLAMP);
  546. if (m_settings.m_qualityLevel > 0)
  547. {
  548. if (wideBlursRemaining > 0)
  549. {
  550. bgfx::dispatch(view, m_smartBlurWideProgram, halfResNumX, halfResNumY);
  551. wideBlursRemaining--;
  552. }
  553. else
  554. {
  555. bgfx::dispatch(view, m_smartBlurProgram, halfResNumX, halfResNumY);
  556. }
  557. }
  558. else
  559. {
  560. bgfx::dispatch(view, m_nonSmartBlurProgram, halfResNumX, halfResNumY); // just for quality level 0 (and -1)
  561. }
  562. bgfx::TextureHandle temp = pPingRT;
  563. pPingRT = pPongRT;
  564. pPongRT = temp;
  565. }
  566. }
  567. }
  568. if (ssaoPass == 0 && m_settings.m_qualityLevel == 3)
  569. { // Generate importance map
  570. m_uniforms.submit();
  571. bgfx::setImage(0, m_importanceMap, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  572. bgfx::setTexture(1, s_finalSSAO, m_finalResults, SAMPLER_POINT_CLAMP);
  573. bgfx::dispatch(view, m_generateImportanceMapProgram, (m_quarterSize[0] + 7) / 8, (m_quarterSize[1] + 7) / 8);
  574. m_uniforms.submit();
  575. bgfx::setImage(0, m_importanceMapPong, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  576. bgfx::setTexture(1, s_importanceMap, m_importanceMap);
  577. bgfx::dispatch(view, m_postprocessImportanceMapAProgram, (m_quarterSize[0] + 7) / 8, (m_quarterSize[1] + 7) / 8);
  578. bgfx::setBuffer(0, m_loadCounter, bgfx::Access::ReadWrite);
  579. bgfx::dispatch(view, m_loadCounterClearProgram, 1,1);
  580. m_uniforms.submit();
  581. bgfx::setImage(0, m_importanceMap, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  582. bgfx::setTexture(1, s_importanceMap, m_importanceMapPong);
  583. bgfx::setBuffer(2, m_loadCounter, bgfx::Access::ReadWrite);
  584. bgfx::dispatch(view, m_postprocessImportanceMapBProgram, (m_quarterSize[0]+7) / 8, (m_quarterSize[1]+7) / 8);
  585. ++view;
  586. }
  587. }
  588. // Apply
  589. {
  590. // select 4 deinterleaved AO textures (texture array)
  591. bgfx::setImage(0, m_aoMap, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  592. bgfx::setTexture(1, s_finalSSAO, m_finalResults);
  593. m_uniforms.submit();
  594. float rect[4] = {(float)m_fullResOutScissorRect[0], (float)m_fullResOutScissorRect[1], (float)m_fullResOutScissorRect[2], (float)m_fullResOutScissorRect[3] };
  595. bgfx::setUniform(u_rect, rect);
  596. bgfx::ProgramHandle program;
  597. if (m_settings.m_qualityLevel < 0)
  598. program = m_nonSmartHalfApplyProgram;
  599. else if (m_settings.m_qualityLevel == 0)
  600. program = m_nonSmartApplyProgram;
  601. else
  602. program = m_applyProgram;
  603. bgfx::dispatch(view, program, (m_fullResOutScissorRect[2]- m_fullResOutScissorRect[0] + 7) / 8,
  604. (m_fullResOutScissorRect[3] - m_fullResOutScissorRect[1] + 7) / 8);
  605. ++view;
  606. }
  607. { // combine
  608. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  609. bgfx::setViewName(view, "Combine");
  610. bgfx::setViewRect(view, 0, 0, (uint16_t)m_width, (uint16_t)m_height);
  611. float orthoProj[16];
  612. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  613. bgfx::setViewTransform(view, NULL, orthoProj);
  614. bgfx::setTexture(0, s_color, bgfx::getTexture(m_gbuffer, GBUFFER_RT_COLOR), SAMPLER_POINT_CLAMP);
  615. bgfx::setTexture(1, s_normal, bgfx::getTexture(m_gbuffer, GBUFFER_RT_NORMAL), SAMPLER_POINT_CLAMP);
  616. bgfx::setTexture(2, s_ao, m_aoMap, SAMPLER_POINT_CLAMP);
  617. m_uniforms.submit();
  618. float combineParams[8] = { m_enableTexturing ? 1.0f : 0.0f, m_enableSSAO ? 1.0f : 0.0f, 0.0f,0.0f,
  619. (float)(m_size[0]-2*m_border) / (float)m_size[0], (float)(m_size[1] - 2 * m_border) / (float)m_size[1],
  620. (float)m_border / (float)m_size[0], (float)m_border / (float)m_size[1] };
  621. bgfx::setUniform(u_combineParams, combineParams, 2);
  622. screenSpaceQuad((float)m_width, (float)m_height, m_texelHalf, caps->originBottomLeft);
  623. bgfx::setState(BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A | BGFX_STATE_DEPTH_TEST_ALWAYS);
  624. bgfx::submit(view, m_combineProgram);
  625. ++view;
  626. }
  627. #endif
  628. // Draw UI
  629. imguiBeginFrame(m_mouseState.m_mx
  630. , m_mouseState.m_my
  631. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  632. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  633. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  634. , m_mouseState.m_mz
  635. , uint16_t(m_width)
  636. , uint16_t(m_height)
  637. );
  638. showExampleDialog(this);
  639. ImGui::SetNextWindowPos(
  640. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  641. , ImGuiCond_FirstUseEver
  642. );
  643. ImGui::SetNextWindowSize(
  644. ImVec2(m_width / 4.0f, m_height / 1.3f)
  645. , ImGuiCond_FirstUseEver
  646. );
  647. ImGui::Begin("Settings"
  648. , NULL
  649. , 0
  650. );
  651. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  652. ImGui::Checkbox("Enable SSAO", &m_enableSSAO);
  653. ImGui::Checkbox("Enable Texturing & Lighting", &m_enableTexturing);
  654. ImGui::Separator();
  655. int32_t quality = m_settings.m_qualityLevel + 1;
  656. if (ImGui::Combo("Quality Level", &quality, "Lowest (Half Resolution)\0Low\0Medium\0High\0Adaptive\0\0"))
  657. {
  658. m_settings.m_qualityLevel = quality - 1;
  659. }
  660. ImGui::Checkbox("Generate Normals", &m_settings.m_generateNormals);
  661. if (ImGui::Checkbox("Framebuffer Gutter", &m_framebufferGutter))
  662. {
  663. m_recreateFrameBuffers = true;
  664. }
  665. ImGui::SliderFloat("Effect Radius", &m_settings.m_radius, 0.0f, 4.0f);
  666. ImGui::SliderFloat("Effect Strength", &m_settings.m_shadowMultiplier, 0.0f, 5.0f);
  667. ImGui::SliderFloat("Effect Power", &m_settings.m_shadowPower, 0.5f, 4.0f);
  668. ImGui::SliderFloat("Effect Max Limit", &m_settings.m_shadowClamp, 0.0f, 1.0f);
  669. ImGui::SliderFloat("Horizon Angle Threshold", &m_settings.m_horizonAngleThreshold, 0.0f, 0.2f);
  670. ImGui::SliderFloat("Fade Out From", &m_settings.m_fadeOutFrom, 0.0f, 100.0f);
  671. ImGui::SliderFloat("Fade Out To", &m_settings.m_fadeOutTo, 0.0f, 300.0f);
  672. if (m_settings.m_qualityLevel == 3)
  673. {
  674. ImGui::SliderFloat("Adaptive Quality Limit", &m_settings.m_adaptiveQualityLimit, 0.0f, 1.0f);
  675. }
  676. ImGui::SliderInt("Blur Pass Count", &m_settings.m_blurPassCount, 0, 6);
  677. ImGui::SliderFloat("Sharpness", &m_settings.m_sharpness, 0.0f, 1.0f);
  678. ImGui::SliderFloat("Temporal Supersampling Angle Offset", &m_settings.m_temporalSupersamplingAngleOffset, 0.0f, bx::kPi);
  679. ImGui::SliderFloat("Temporal Supersampling Radius Offset", &m_settings.m_temporalSupersamplingRadiusOffset, 0.0f, 2.0f);
  680. ImGui::SliderFloat("Detail Shadow Strength", &m_settings.m_detailShadowStrength, 0.0f, 4.0f);
  681. ImGui::End();
  682. imguiEndFrame();
  683. // Advance to next frame. Rendering thread will be kicked to
  684. // process submitted rendering primitives.
  685. m_currFrame = bgfx::frame();
  686. return true;
  687. }
  688. return false;
  689. }
  690. void drawAllModels(uint8_t _pass, bgfx::ProgramHandle _program)
  691. {
  692. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  693. {
  694. const Model& model = m_models[ii];
  695. // Set up transform matrix for each model
  696. float scale = s_meshScale[model.mesh];
  697. float mtx[16];
  698. bx::mtxSRT(mtx
  699. , scale
  700. , scale
  701. , scale
  702. , 0.0f
  703. , 0.0f
  704. , 0.0f
  705. , model.position[0]
  706. , model.position[1]
  707. , model.position[2]
  708. );
  709. // Submit mesh to gbuffer
  710. bgfx::setTexture(0, s_albedo, m_modelTexture);
  711. meshSubmit(m_meshes[model.mesh], _pass, _program, mtx);
  712. }
  713. // Draw ground
  714. float mtxScale[16];
  715. const float scale = 10.0f;
  716. bx::mtxScale(mtxScale, scale, scale, scale);
  717. float mtxTrans[16];
  718. bx::mtxTranslate(mtxTrans
  719. , 0.0f
  720. , -10.0f
  721. , 0.0f
  722. );
  723. float mtx[16];
  724. bx::mtxMul(mtx, mtxScale, mtxTrans);
  725. bgfx::setTexture(0, s_albedo, m_groundTexture);
  726. meshSubmit(m_ground, _pass, _program, mtx);
  727. }
  728. void createFramebuffers()
  729. {
  730. // update resolution and camera FOV if there's border expansion
  731. const int32_t drawResolutionBorderExpansionFactor = 12; // will be expanded by Height / expansionFactor
  732. const float fovY = 60.0f;
  733. m_border = 0;
  734. if (m_framebufferGutter)
  735. {
  736. m_border = (bx::min(m_width, m_height) / drawResolutionBorderExpansionFactor) / 2 * 2;
  737. int32_t expandedSceneResolutionY = m_height + m_border * 2;
  738. float yScaleDueToBorder = (expandedSceneResolutionY * 0.5f) / (float)(m_height * 0.5f);
  739. float nonExpandedTan = bx::tan(bx::toRad(fovY / 2.0f));
  740. m_fovY = bx::toDeg(bx::atan(nonExpandedTan * yScaleDueToBorder) * 2.0f);
  741. }
  742. else
  743. {
  744. m_fovY = fovY;
  745. }
  746. m_size[0] = m_width + 2 * m_border;
  747. m_size[1] = m_height + 2 * m_border;
  748. m_halfSize[0] = (m_size[0] + 1) / 2;
  749. m_halfSize[1] = (m_size[1] + 1) / 2;
  750. m_quarterSize[0] = (m_halfSize[0] + 1) / 2;
  751. m_quarterSize[1] = (m_halfSize[1] + 1) / 2;
  752. vec4iSet(m_fullResOutScissorRect, m_border, m_border, m_width + m_border, m_height + m_border);
  753. vec4iSet(m_halfResOutScissorRect, m_fullResOutScissorRect[0] / 2, m_fullResOutScissorRect[1] / 2, (m_fullResOutScissorRect[2] + 1) / 2, (m_fullResOutScissorRect[3] + 1) / 2);
  754. int32_t blurEnlarge = cMaxBlurPassCount + bx::max(0, cMaxBlurPassCount - 2); // +1 for max normal blurs, +2 for wide blurs
  755. vec4iSet(m_halfResOutScissorRect, bx::max(0, m_halfResOutScissorRect[0] - blurEnlarge), bx::max(0, m_halfResOutScissorRect[1] - blurEnlarge),
  756. bx::min(m_halfSize[0], m_halfResOutScissorRect[2] + blurEnlarge), bx::min(m_halfSize[1], m_halfResOutScissorRect[3] + blurEnlarge));
  757. // Make gbuffer and related textures
  758. const uint64_t tsFlags = 0
  759. | BGFX_TEXTURE_RT
  760. | BGFX_SAMPLER_MIN_POINT
  761. | BGFX_SAMPLER_MAG_POINT
  762. | BGFX_SAMPLER_MIP_POINT
  763. | BGFX_SAMPLER_U_CLAMP
  764. | BGFX_SAMPLER_V_CLAMP
  765. ;
  766. bgfx::TextureHandle gbufferTex[3];
  767. gbufferTex[GBUFFER_RT_NORMAL] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, tsFlags);
  768. gbufferTex[GBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, tsFlags);
  769. gbufferTex[GBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D24, tsFlags);
  770. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(gbufferTex), gbufferTex, true);
  771. for (int32_t i = 0; i < 4; i++)
  772. {
  773. m_halfDepths[i] = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), true, 1, bgfx::TextureFormat::R16F, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_POINT_CLAMP);
  774. }
  775. m_pingPongHalfResultA = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), false, 2, bgfx::TextureFormat::RG8, BGFX_TEXTURE_COMPUTE_WRITE);
  776. m_pingPongHalfResultB = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), false, 2, bgfx::TextureFormat::RG8, BGFX_TEXTURE_COMPUTE_WRITE);
  777. m_finalResults = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), false, 4, bgfx::TextureFormat::RG8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_LINEAR_CLAMP);
  778. m_normals = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::RGBA8, BGFX_TEXTURE_COMPUTE_WRITE);
  779. m_importanceMap = bgfx::createTexture2D(uint16_t(m_quarterSize[0]), uint16_t(m_quarterSize[1]), false, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_LINEAR_CLAMP);
  780. m_importanceMapPong = bgfx::createTexture2D(uint16_t(m_quarterSize[0]), uint16_t(m_quarterSize[1]), false, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_LINEAR_CLAMP);
  781. m_aoMap = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_POINT_CLAMP);
  782. }
  783. void destroyFramebuffers()
  784. {
  785. bgfx::destroy(m_gbuffer);
  786. for (uint32_t ii = 0; ii < BX_COUNTOF(m_halfDepths); ++ii)
  787. {
  788. bgfx::destroy(m_halfDepths[ii]);
  789. }
  790. bgfx::destroy(m_pingPongHalfResultA);
  791. bgfx::destroy(m_pingPongHalfResultB);
  792. bgfx::destroy(m_finalResults);
  793. bgfx::destroy(m_normals);
  794. bgfx::destroy(m_aoMap);
  795. bgfx::destroy(m_importanceMap);
  796. bgfx::destroy(m_importanceMapPong);
  797. }
  798. void updateUniforms(int32_t _pass)
  799. {
  800. vec2Set(m_uniforms.m_viewportPixelSize, 1.0f / (float)m_size[0], 1.0f / (float)m_size[1]);
  801. vec2Set(m_uniforms.m_halfViewportPixelSize, 1.0f / (float)m_halfSize[0], 1.0f / (float)m_halfSize[1]);
  802. vec2Set(m_uniforms.m_viewport2xPixelSize, m_uniforms.m_viewportPixelSize[0] * 2.0f, m_uniforms.m_viewportPixelSize[1] * 2.0f);
  803. vec2Set(m_uniforms.m_viewport2xPixelSize_x_025, m_uniforms.m_viewport2xPixelSize[0] * 0.25f, m_uniforms.m_viewport2xPixelSize[1] * 0.25f);
  804. float depthLinearizeMul = -m_proj2[3*4+2]; // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  805. float depthLinearizeAdd = m_proj2[2*4+2]; // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  806. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  807. if (depthLinearizeMul * depthLinearizeAdd < 0)
  808. {
  809. depthLinearizeAdd = -depthLinearizeAdd;
  810. }
  811. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  812. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  813. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  814. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  815. {
  816. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  817. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  818. }
  819. else
  820. {
  821. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  822. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  823. }
  824. m_uniforms.m_effectRadius = bx::clamp(m_settings.m_radius, 0.0f, 100000.0f);
  825. m_uniforms.m_effectShadowStrength = bx::clamp(m_settings.m_shadowMultiplier * 4.3f, 0.0f, 10.0f);
  826. m_uniforms.m_effectShadowPow = bx::clamp(m_settings.m_shadowPower, 0.0f, 10.0f);
  827. m_uniforms.m_effectShadowClamp = bx::clamp(m_settings.m_shadowClamp, 0.0f, 1.0f);
  828. m_uniforms.m_effectFadeOutMul = -1.0f / (m_settings.m_fadeOutTo - m_settings.m_fadeOutFrom);
  829. m_uniforms.m_effectFadeOutAdd = m_settings.m_fadeOutFrom / (m_settings.m_fadeOutTo - m_settings.m_fadeOutFrom) + 1.0f;
  830. m_uniforms.m_effectHorizonAngleThreshold = bx::clamp(m_settings.m_horizonAngleThreshold, 0.0f, 1.0f);
  831. // 1.2 seems to be around the best trade off - 1.0 means on-screen radius will stop/slow growing when the camera is at 1.0 distance, so, depending on FOV, basically filling up most of the screen
  832. // This setting is viewspace-dependent and not screen size dependent intentionally, so that when you change FOV the effect stays (relatively) similar.
  833. float effectSamplingRadiusNearLimit = (m_settings.m_radius * 1.2f);
  834. // if the depth precision is switched to 32bit float, this can be set to something closer to 1 (0.9999 is fine)
  835. m_uniforms.m_depthPrecisionOffsetMod = 0.9992f;
  836. // used to get average load per pixel; 9.0 is there to compensate for only doing every 9th InterlockedAdd in PSPostprocessImportanceMapB for performance reasons
  837. m_uniforms.m_loadCounterAvgDiv = 9.0f / (float)(m_quarterSize[0] * m_quarterSize[1] * 255.0);
  838. // Special settings for lowest quality level - just nerf the effect a tiny bit
  839. if (m_settings.m_qualityLevel <= 0)
  840. {
  841. effectSamplingRadiusNearLimit *= 1.50f;
  842. if (m_settings.m_qualityLevel < 0)
  843. {
  844. m_uniforms.m_effectRadius *= 0.8f;
  845. }
  846. }
  847. effectSamplingRadiusNearLimit /= tanHalfFOVY; // to keep the effect same regardless of FOV
  848. m_uniforms.m_effectSamplingRadiusNearLimitRec = 1.0f / effectSamplingRadiusNearLimit;
  849. m_uniforms.m_adaptiveSampleCountLimit = m_settings.m_adaptiveQualityLimit;
  850. m_uniforms.m_negRecEffectRadius = -1.0f / m_uniforms.m_effectRadius;
  851. if (bgfx::getCaps()->originBottomLeft)
  852. {
  853. vec2Set(m_uniforms.m_perPassFullResCoordOffset, (float)(_pass % 2), 1.0f-(float)(_pass / 2));
  854. vec2Set(m_uniforms.m_perPassFullResUVOffset, ((_pass % 2) - 0.0f) / m_size[0], (1.0f-((_pass / 2) - 0.0f)) / m_size[1]);
  855. }
  856. else
  857. {
  858. vec2Set(m_uniforms.m_perPassFullResCoordOffset, (float)(_pass % 2), (float)(_pass / 2));
  859. vec2Set(m_uniforms.m_perPassFullResUVOffset, ((_pass % 2) - 0.0f) / m_size[0], ((_pass / 2) - 0.0f) / m_size[1]);
  860. }
  861. m_uniforms.m_invSharpness = bx::clamp(1.0f - m_settings.m_sharpness, 0.0f, 1.0f);
  862. m_uniforms.m_passIndex = (float)_pass;
  863. vec2Set(m_uniforms.m_quarterResPixelSize, 1.0f / (float)m_quarterSize[0], 1.0f / (float)m_quarterSize[1]);
  864. float additionalAngleOffset = m_settings.m_temporalSupersamplingAngleOffset; // if using temporal supersampling approach (like "Progressive Rendering Using Multi-frame Sampling" from GPU Pro 7, etc.)
  865. float additionalRadiusScale = m_settings.m_temporalSupersamplingRadiusOffset; // if using temporal supersampling approach (like "Progressive Rendering Using Multi-frame Sampling" from GPU Pro 7, etc.)
  866. const int32_t subPassCount = 5;
  867. for (int32_t subPass = 0; subPass < subPassCount; subPass++)
  868. {
  869. int32_t a = _pass;
  870. int32_t b = subPass;
  871. int32_t spmap[5]{ 0, 1, 4, 3, 2 };
  872. b = spmap[subPass];
  873. float ca, sa;
  874. float angle0 = ((float)a + (float)b / (float)subPassCount) * (3.1415926535897932384626433832795f) * 0.5f;
  875. angle0 += additionalAngleOffset;
  876. ca = bx::cos(angle0);
  877. sa = bx::sin(angle0);
  878. float scale = 1.0f + (a - 1.5f + (b - (subPassCount - 1.0f) * 0.5f) / (float)subPassCount) * 0.07f;
  879. scale *= additionalRadiusScale;
  880. vec4Set(m_uniforms.m_patternRotScaleMatrices[subPass], scale * ca, scale * -sa, -scale * sa, -scale * ca);
  881. }
  882. m_uniforms.m_normalsUnpackMul = 2.0f;
  883. m_uniforms.m_normalsUnpackAdd = -1.0f;
  884. m_uniforms.m_detailAOStrength = m_settings.m_detailShadowStrength;
  885. if (m_settings.m_generateNormals)
  886. {
  887. bx::mtxIdentity(m_uniforms.m_normalsWorldToViewspaceMatrix);
  888. }
  889. else
  890. {
  891. bx::mtxTranspose(m_uniforms.m_normalsWorldToViewspaceMatrix, m_view);
  892. }
  893. }
  894. uint32_t m_width;
  895. uint32_t m_height;
  896. uint32_t m_debug;
  897. uint32_t m_reset;
  898. entry::MouseState m_mouseState;
  899. Uniforms m_uniforms;
  900. // Resource handles
  901. bgfx::ProgramHandle m_gbufferProgram;
  902. bgfx::ProgramHandle m_combineProgram;
  903. bgfx::ProgramHandle m_prepareDepthsProgram;
  904. bgfx::ProgramHandle m_prepareDepthsAndNormalsProgram;
  905. bgfx::ProgramHandle m_prepareDepthsHalfProgram;
  906. bgfx::ProgramHandle m_prepareDepthsAndNormalsHalfProgram;
  907. bgfx::ProgramHandle m_prepareDepthMipProgram;
  908. bgfx::ProgramHandle m_generateQ0Program;
  909. bgfx::ProgramHandle m_generateQ1Program;
  910. bgfx::ProgramHandle m_generateQ2Program;
  911. bgfx::ProgramHandle m_generateQ3Program;
  912. bgfx::ProgramHandle m_generateQ3BaseProgram;
  913. bgfx::ProgramHandle m_smartBlurProgram;
  914. bgfx::ProgramHandle m_smartBlurWideProgram;
  915. bgfx::ProgramHandle m_nonSmartBlurProgram;
  916. bgfx::ProgramHandle m_applyProgram;
  917. bgfx::ProgramHandle m_nonSmartApplyProgram;
  918. bgfx::ProgramHandle m_nonSmartHalfApplyProgram;
  919. bgfx::ProgramHandle m_generateImportanceMapProgram;
  920. bgfx::ProgramHandle m_postprocessImportanceMapAProgram;
  921. bgfx::ProgramHandle m_postprocessImportanceMapBProgram;
  922. bgfx::ProgramHandle m_loadCounterClearProgram;
  923. bgfx::FrameBufferHandle m_gbuffer;
  924. // Shader uniforms
  925. bgfx::UniformHandle u_rect;
  926. bgfx::UniformHandle u_combineParams;
  927. // Uniforms to identify texture samples
  928. bgfx::UniformHandle s_normal;
  929. bgfx::UniformHandle s_depth;
  930. bgfx::UniformHandle s_color;
  931. bgfx::UniformHandle s_albedo;
  932. bgfx::UniformHandle s_ao;
  933. bgfx::UniformHandle s_blurInput;
  934. bgfx::UniformHandle s_finalSSAO;
  935. bgfx::UniformHandle s_depthSource;
  936. bgfx::UniformHandle s_viewspaceDepthSource;
  937. bgfx::UniformHandle s_viewspaceDepthSourceMirror;
  938. bgfx::UniformHandle s_importanceMap;
  939. // Various render targets
  940. bgfx::TextureHandle m_halfDepths[4];
  941. bgfx::TextureHandle m_pingPongHalfResultA;
  942. bgfx::TextureHandle m_pingPongHalfResultB;
  943. bgfx::TextureHandle m_finalResults;
  944. bgfx::TextureHandle m_aoMap;
  945. bgfx::TextureHandle m_normals;
  946. // Only needed for quality level 3 (adaptive quality)
  947. bgfx::TextureHandle m_importanceMap;
  948. bgfx::TextureHandle m_importanceMapPong;
  949. bgfx::DynamicIndexBufferHandle m_loadCounter;
  950. struct Model
  951. {
  952. uint32_t mesh; // Index of mesh in m_meshes
  953. float position[3];
  954. };
  955. Model m_models[MODEL_COUNT];
  956. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  957. Mesh* m_ground;
  958. bgfx::TextureHandle m_groundTexture;
  959. bgfx::TextureHandle m_modelTexture;
  960. uint32_t m_currFrame;
  961. // UI
  962. Settings m_settings;
  963. bool m_enableSSAO;
  964. bool m_enableTexturing;
  965. float m_texelHalf;
  966. float m_fovY;
  967. bool m_framebufferGutter;
  968. bool m_recreateFrameBuffers;
  969. float m_view[16];
  970. float m_proj[16];
  971. float m_proj2[16];
  972. int32_t m_size[2];
  973. int32_t m_halfSize[2];
  974. int32_t m_quarterSize[2];
  975. int32_t m_fullResOutScissorRect[4];
  976. int32_t m_halfResOutScissorRect[4];
  977. int32_t m_border;
  978. };
  979. } // namespace
  980. ENTRY_IMPLEMENT_MAIN(
  981. ExampleASSAO
  982. , "39-assao"
  983. , "Adaptive Screen Space Ambient Occlusion."
  984. , "https://bkaradzic.github.io/bgfx/examples.html#assao"
  985. );