bokeh.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. /*
  2. * Copyright 2021 elven cache. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * Implement bokeh depth of field as described in the blog post here:
  7. * https://web.archive.org/web/20201215123940/https://blog.tuxedolabs.com/2018/05/04/bokeh-depth-of-field-in-single-pass.html
  8. *
  9. * Additionally, implement the optimizations discussed in the closing paragraph.
  10. * Apply the effect in multiple passes. Calculate the circle of confusion and store
  11. * in the alpha channel while downsampling the image. Then compute depth of field
  12. * at this lower res, storing sample size in alpha. Then composite the blurred image,
  13. * based on the sample size. Compositing the lower res like this can lead to blocky
  14. * edges where there's a depth discontinuity and the blur is just enough. May be
  15. * an area to improve on.
  16. *
  17. * Provide an alternate means of determining radius of current sample when blurring.
  18. * I find the blog post's sample pattern to be difficult to directly reason about. It
  19. * is not obvious, given the parameters, how many samples will be taken. And it can
  20. * be very many samples. Though the results are good. The 'sqrt' pattern chosen here
  21. * looks alright and allows for the number of samples to be set directly. If you are
  22. * going to use this in a project, may be worth exploring additional sample patterns.
  23. * And certainly update the shader to remove the pattern choice from inside the
  24. * sample loop.
  25. */
  26. #include <common.h>
  27. #include <camera.h>
  28. #include <bgfx_utils.h>
  29. #include <imgui/imgui.h>
  30. #include <bx/rng.h>
  31. #include <bx/os.h>
  32. namespace {
  33. #define FRAMEBUFFER_RT_COLOR 0
  34. #define FRAMEBUFFER_RT_DEPTH 1
  35. #define FRAMEBUFFER_RENDER_TARGETS 2
  36. enum Meshes
  37. {
  38. MeshCube = 0,
  39. MeshHollowCube
  40. };
  41. static const char * s_meshPaths[] =
  42. {
  43. "meshes/cube.bin",
  44. "meshes/hollowcube.bin"
  45. };
  46. static const float s_meshScale[] =
  47. {
  48. 0.45f,
  49. 0.30f
  50. };
  51. // Vertex decl 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. struct PassUniforms
  71. {
  72. enum { NumVec4 = 4 };
  73. void init() {
  74. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  75. };
  76. void submit() const {
  77. bgfx::setUniform(u_params, m_params, NumVec4);
  78. }
  79. void destroy() {
  80. bgfx::destroy(u_params);
  81. }
  82. union
  83. {
  84. struct
  85. {
  86. /* 0 */ struct { float m_depthUnpackConsts[2]; float m_frameIdx; float m_lobeRotation; };
  87. /* 1 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  88. /* 2 */ struct { float m_blurSteps; float m_lobeCount; float m_lobeRadiusMin; float m_lobeRadiusDelta2x; };
  89. /* 3 */ struct { float m_maxBlurSize; float m_focusPoint; float m_focusScale; float m_radiusScale; };
  90. };
  91. float m_params[NumVec4 * 4];
  92. };
  93. bgfx::UniformHandle u_params;
  94. };
  95. struct ModelUniforms
  96. {
  97. enum { NumVec4 = 2 };
  98. void init() {
  99. u_params = bgfx::createUniform("u_modelParams", bgfx::UniformType::Vec4, NumVec4);
  100. };
  101. void submit() const {
  102. bgfx::setUniform(u_params, m_params, NumVec4);
  103. };
  104. void destroy() {
  105. bgfx::destroy(u_params);
  106. }
  107. union
  108. {
  109. struct
  110. {
  111. /* 0 */ struct { float m_color[3]; float m_unused0; };
  112. /* 1 */ struct { float m_lightPosition[3]; float m_unused1; };
  113. };
  114. float m_params[NumVec4 * 4];
  115. };
  116. bgfx::UniformHandle u_params;
  117. };
  118. struct RenderTarget
  119. {
  120. void init(uint32_t _width, uint32_t _height, bgfx::TextureFormat::Enum _format, uint64_t _flags)
  121. {
  122. m_texture = bgfx::createTexture2D(uint16_t(_width), uint16_t(_height), false, 1, _format, _flags);
  123. const bool destroyTextures = true;
  124. m_buffer = bgfx::createFrameBuffer(1, &m_texture, destroyTextures);
  125. }
  126. void destroy()
  127. {
  128. // also responsible for destroying texture
  129. bgfx::destroy(m_buffer);
  130. }
  131. bgfx::TextureHandle m_texture;
  132. bgfx::FrameBufferHandle m_buffer;
  133. };
  134. void screenSpaceQuad(bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  135. {
  136. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  137. {
  138. bgfx::TransientVertexBuffer vb;
  139. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  140. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  141. const float minx = -_width;
  142. const float maxx = _width;
  143. const float miny = 0.0f;
  144. const float maxy = _height * 2.0f;
  145. const float minu = -1.0f;
  146. const float maxu = 1.0f;
  147. const float zz = 0.0f;
  148. float minv = 0.0f;
  149. float maxv = 2.0f;
  150. if (_originBottomLeft)
  151. {
  152. float temp = minv;
  153. minv = maxv;
  154. maxv = temp;
  155. minv -= 1.0f;
  156. maxv -= 1.0f;
  157. }
  158. vertex[0].m_x = minx;
  159. vertex[0].m_y = miny;
  160. vertex[0].m_z = zz;
  161. vertex[0].m_u = minu;
  162. vertex[0].m_v = minv;
  163. vertex[1].m_x = maxx;
  164. vertex[1].m_y = miny;
  165. vertex[1].m_z = zz;
  166. vertex[1].m_u = maxu;
  167. vertex[1].m_v = minv;
  168. vertex[2].m_x = maxx;
  169. vertex[2].m_y = maxy;
  170. vertex[2].m_z = zz;
  171. vertex[2].m_u = maxu;
  172. vertex[2].m_v = maxv;
  173. bgfx::setVertexBuffer(0, &vb);
  174. }
  175. }
  176. void vec2Set(float* _v, float _x, float _y)
  177. {
  178. _v[0] = _x;
  179. _v[1] = _y;
  180. }
  181. class ExampleBokeh : public entry::AppI
  182. {
  183. public:
  184. ExampleBokeh(const char* _name, const char* _description)
  185. : entry::AppI(_name, _description)
  186. , m_currFrame(UINT32_MAX)
  187. {
  188. }
  189. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  190. {
  191. Args args(_argc, _argv);
  192. m_width = _width;
  193. m_height = _height;
  194. m_debug = BGFX_DEBUG_NONE;
  195. m_reset = BGFX_RESET_VSYNC;
  196. bgfx::Init init;
  197. init.type = args.m_type;
  198. init.vendorId = args.m_pciId;
  199. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  200. init.platformData.ndt = entry::getNativeDisplayHandle();
  201. init.platformData.type = entry::getNativeWindowHandleType();
  202. init.resolution.width = m_width;
  203. init.resolution.height = m_height;
  204. init.resolution.reset = m_reset;
  205. bgfx::init(init);
  206. // Enable debug text.
  207. bgfx::setDebug(m_debug);
  208. // Create uniforms for screen passes and models
  209. m_uniforms.init();
  210. m_modelUniforms.init();
  211. // Create texture sampler uniforms (used when we bind textures)
  212. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  213. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler);
  214. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler);
  215. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
  216. s_blurredColor = bgfx::createUniform("s_blurredColor", bgfx::UniformType::Sampler);
  217. // Create program from shaders.
  218. m_forwardProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward");
  219. m_gridProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward_grid");
  220. m_copyProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_copy");
  221. m_copyLinearToGammaProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_copy_linear_to_gamma");
  222. m_linearDepthProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_linear_depth");
  223. m_dofSinglePassProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_single_pass");
  224. m_dofDownsampleProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_downsample");
  225. m_dofQuarterProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_second_pass");
  226. m_dofCombineProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_combine");
  227. m_dofDebugProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_debug");
  228. // Load some meshes
  229. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  230. {
  231. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  232. }
  233. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  234. m_normalTexture = loadTexture("textures/fieldstone-n.dds");
  235. m_recreateFrameBuffers = false;
  236. createFramebuffers();
  237. // Vertex decl
  238. PosTexCoord0Vertex::init();
  239. // Init camera
  240. cameraCreate();
  241. cameraSetPosition({ 0.0f, 2.5f, -20.0f });
  242. cameraSetVerticalAngle(-0.3f);
  243. m_fovY = 60.0f;
  244. // Init "prev" matrices, will be same for first frame
  245. cameraGetViewMtx(m_view);
  246. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  247. m_bokehTexture.idx = bgfx::kInvalidHandle;
  248. updateDisplayBokehTexture(m_radiusScale, m_maxBlurSize, m_lobeCount, (1.0f-m_lobePinch), 1.0f, m_lobeRotation);
  249. imguiCreate();
  250. }
  251. int32_t shutdown() override
  252. {
  253. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  254. {
  255. meshUnload(m_meshes[ii]);
  256. }
  257. bgfx::destroy(m_normalTexture);
  258. bgfx::destroy(m_groundTexture);
  259. bgfx::destroy(m_bokehTexture);
  260. bgfx::destroy(m_forwardProgram);
  261. bgfx::destroy(m_gridProgram);
  262. bgfx::destroy(m_copyProgram);
  263. bgfx::destroy(m_copyLinearToGammaProgram);
  264. bgfx::destroy(m_linearDepthProgram);
  265. bgfx::destroy(m_dofSinglePassProgram);
  266. bgfx::destroy(m_dofDownsampleProgram);
  267. bgfx::destroy(m_dofQuarterProgram);
  268. bgfx::destroy(m_dofCombineProgram);
  269. bgfx::destroy(m_dofDebugProgram);
  270. m_uniforms.destroy();
  271. m_modelUniforms.destroy();
  272. bgfx::destroy(s_albedo);
  273. bgfx::destroy(s_color);
  274. bgfx::destroy(s_normal);
  275. bgfx::destroy(s_depth);
  276. bgfx::destroy(s_blurredColor);
  277. destroyFramebuffers();
  278. cameraDestroy();
  279. imguiDestroy();
  280. bgfx::shutdown();
  281. return 0;
  282. }
  283. bool update() override
  284. {
  285. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  286. {
  287. // skip processing when minimized, otherwise crashing
  288. if (0 == m_width || 0 == m_height)
  289. {
  290. return true;
  291. }
  292. // Update frame timer
  293. int64_t now = bx::getHPCounter();
  294. static int64_t last = now;
  295. const int64_t frameTime = now - last;
  296. last = now;
  297. const double freq = double(bx::getHPFrequency());
  298. const float deltaTime = float(frameTime / freq);
  299. const bgfx::Caps* caps = bgfx::getCaps();
  300. if (m_size[0] != (int32_t)m_width
  301. || m_size[1] != (int32_t)m_height
  302. || m_recreateFrameBuffers)
  303. {
  304. destroyFramebuffers();
  305. createFramebuffers();
  306. m_recreateFrameBuffers = false;
  307. }
  308. // update animation time
  309. const float rotationSpeed = 0.75f;
  310. m_animationTime += deltaTime * rotationSpeed;
  311. if (bx::kPi2 < m_animationTime)
  312. {
  313. m_animationTime -= bx::kPi2;
  314. }
  315. // Update camera
  316. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  317. cameraGetViewMtx(m_view);
  318. updateUniforms();
  319. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  320. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  321. bgfx::ViewId view = 0;
  322. // Draw models into scene
  323. {
  324. bgfx::setViewName(view, "forward scene");
  325. bgfx::setViewClear(view
  326. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  327. , 0x7fb8ffff // clear to a sky blue
  328. , 1.0f
  329. , 0
  330. );
  331. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  332. bgfx::setViewTransform(view, m_view, m_proj);
  333. bgfx::setViewFrameBuffer(view, m_frameBuffer);
  334. bgfx::setState(0
  335. | BGFX_STATE_WRITE_RGB
  336. | BGFX_STATE_WRITE_A
  337. | BGFX_STATE_WRITE_Z
  338. | BGFX_STATE_DEPTH_TEST_LESS
  339. );
  340. drawAllModels(view, m_forwardProgram, m_modelUniforms);
  341. ++view;
  342. }
  343. float orthoProj[16];
  344. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  345. {
  346. // clear out transform stack
  347. float identity[16];
  348. bx::mtxIdentity(identity);
  349. bgfx::setTransform(identity);
  350. }
  351. // Convert depth to linear depth for shadow depth compare
  352. {
  353. bgfx::setViewName(view, "linear depth");
  354. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  355. bgfx::setViewTransform(view, NULL, orthoProj);
  356. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  357. bgfx::setState(0
  358. | BGFX_STATE_WRITE_RGB
  359. | BGFX_STATE_WRITE_A
  360. | BGFX_STATE_DEPTH_TEST_ALWAYS
  361. );
  362. bgfx::setTexture(0, s_depth, m_frameBufferTex[FRAMEBUFFER_RT_DEPTH]);
  363. m_uniforms.submit();
  364. screenSpaceQuad(caps->originBottomLeft);
  365. bgfx::submit(view, m_linearDepthProgram);
  366. ++view;
  367. }
  368. // optionally, apply dof
  369. const bool useOrDebugDof = m_useBokehDof || m_showDebugVisualization;
  370. if (useOrDebugDof)
  371. {
  372. view = drawDepthOfField(view, m_frameBufferTex[FRAMEBUFFER_RT_COLOR], orthoProj, caps->originBottomLeft);
  373. }
  374. else
  375. {
  376. bgfx::setViewName(view, "display");
  377. bgfx::setViewClear(view
  378. , BGFX_CLEAR_NONE
  379. , 0
  380. , 1.0f
  381. , 0
  382. );
  383. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  384. bgfx::setViewTransform(view, NULL, orthoProj);
  385. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  386. bgfx::setState(0
  387. | BGFX_STATE_WRITE_RGB
  388. | BGFX_STATE_WRITE_A
  389. );
  390. bgfx::setTexture(0, s_color, m_frameBufferTex[FRAMEBUFFER_RT_COLOR]);
  391. screenSpaceQuad(caps->originBottomLeft);
  392. bgfx::submit(view, m_copyLinearToGammaProgram);
  393. ++view;
  394. }
  395. // Draw UI
  396. imguiBeginFrame(m_mouseState.m_mx
  397. , m_mouseState.m_my
  398. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  399. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  400. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  401. , m_mouseState.m_mz
  402. , uint16_t(m_width)
  403. , uint16_t(m_height)
  404. );
  405. showExampleDialog(this);
  406. ImGui::SetNextWindowPos(
  407. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  408. , ImGuiCond_FirstUseEver
  409. );
  410. ImGui::SetNextWindowSize(
  411. ImVec2(m_width / 4.0f, m_height / 1.35f)
  412. , ImGuiCond_FirstUseEver
  413. );
  414. ImGui::Begin("Settings"
  415. , NULL
  416. , 0
  417. );
  418. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  419. {
  420. ImGui::Checkbox("use bokeh dof", &m_useBokehDof);
  421. if (ImGui::IsItemHovered())
  422. ImGui::SetTooltip("turn effect on and off");
  423. ImGui::Checkbox("use single pass at full res", &m_useSinglePassBokehDof);
  424. if (ImGui::IsItemHovered())
  425. {
  426. ImGui::BeginTooltip();
  427. ImGui::Text("calculate in a single pass at full resolution or use");
  428. ImGui::Text("multiple passes to compute at lower res and composite");
  429. ImGui::EndTooltip();
  430. }
  431. ImGui::Checkbox("show debug vis", &m_showDebugVisualization);
  432. if (ImGui::IsItemHovered())
  433. {
  434. ImGui::BeginTooltip();
  435. ImGui::Text("apply coloration to screen. fades from grey to orange with");
  436. ImGui::Text("increasing foreground blur. from grey to blue in background");
  437. ImGui::EndTooltip();
  438. }
  439. ImGui::Separator();
  440. bool isChanged = false;
  441. ImGui::Text("blur controls:");
  442. isChanged |= ImGui::SliderFloat("max blur size", &m_maxBlurSize, 10.0f, 50.0f);
  443. if (ImGui::IsItemHovered())
  444. ImGui::SetTooltip("maximum blur size in screen pixels");
  445. ImGui::SliderFloat("focusPoint", &m_focusPoint, 1.0f, 20.0f);
  446. if (ImGui::IsItemHovered())
  447. ImGui::SetTooltip("distance to focus plane");
  448. ImGui::SliderFloat("focusScale", &m_focusScale, 0.0f, 10.0f);
  449. if (ImGui::IsItemHovered())
  450. ImGui::SetTooltip("multiply focus calculation, larger=tighter focus");
  451. ImGui::Separator();
  452. ImGui::Text("bokeh shape and sample controls:");
  453. isChanged |= ImGui::SliderFloat("radiusScale", &m_radiusScale, 0.5f, 4.0f);
  454. if (ImGui::IsItemHovered())
  455. ImGui::SetTooltip("controls number of samples taken");
  456. isChanged |= ImGui::SliderInt("lobe count", &m_lobeCount, 1, 8);
  457. if (ImGui::IsItemHovered())
  458. ImGui::SetTooltip("using triangle lobes to emulate aperture blades");
  459. isChanged |= ImGui::SliderFloat("lobe pinch", &m_lobePinch, 0.0f, 1.0f);
  460. if (ImGui::IsItemHovered())
  461. ImGui::SetTooltip("adjust lobe shape, 0=round, 1=starry");
  462. isChanged |= ImGui::SliderFloat("lobe rotation", &m_lobeRotation, -1.0f, 1.0f);
  463. if (isChanged)
  464. {
  465. updateDisplayBokehTexture(m_radiusScale, m_maxBlurSize, m_lobeCount, (1.0f-m_lobePinch), 1.0f, m_lobeRotation);
  466. }
  467. ImGui::Text("number of samples taken: %d", m_sampleCount);
  468. if (ImGui::IsItemHovered())
  469. ImGui::SetTooltip("number of sample taps as determined by radiusScale and maxBlurSize");
  470. ImGui::Image(m_bokehTexture, ImVec2(128.0f, 128.0f) );
  471. }
  472. ImGui::End();
  473. imguiEndFrame();
  474. // Advance to next frame. Rendering thread will be kicked to
  475. // process submitted rendering primitives.
  476. m_currFrame = bgfx::frame();
  477. return true;
  478. }
  479. return false;
  480. }
  481. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, ModelUniforms & _uniforms)
  482. {
  483. const int32_t width = 6;
  484. const int32_t length = 20;
  485. float c0[] = { 72.0f/255.0f, 126.0f/255.0f, 149.0f/255.0f }; // blue
  486. float c1[] = { 235.0f/255.0f, 146.0f/255.0f, 251.0f/255.0f }; // purple
  487. float c2[] = { 199.0f/255.0f, 0.0f/255.0f, 57.0f/255.0f }; // pink
  488. for (int32_t zz = 0; zz < length; ++zz)
  489. {
  490. // make a color gradient, nothing special about this for example
  491. float * ca = c0;
  492. float * cb = c1;
  493. float lerpVal = float(zz) / float(length);
  494. if (0.5f <= lerpVal)
  495. {
  496. ca = c1;
  497. cb = c2;
  498. }
  499. lerpVal = bx::fract(2.0f*lerpVal);
  500. float r = bx::lerp(ca[0], cb[0], lerpVal);
  501. float g = bx::lerp(ca[1], cb[1], lerpVal);
  502. float b = bx::lerp(ca[2], cb[2], lerpVal);
  503. for (int32_t xx = 0; xx < width; ++xx)
  504. {
  505. const float angle = m_animationTime + float(zz)*(bx::kPi2/length) + float(xx)*(bx::kPiHalf/width);
  506. const float posX = 2.0f * xx - width + 1.0f;
  507. const float posY = bx::sin(angle);
  508. const float posZ = 2.0f * zz - length + 1.0f;
  509. const float scale = s_meshScale[MeshHollowCube];
  510. float mtx[16];
  511. bx::mtxSRT(mtx
  512. , scale
  513. , scale
  514. , scale
  515. , 0.0f
  516. , 0.0f
  517. , 0.0f
  518. , posX
  519. , posY
  520. , posZ
  521. );
  522. bgfx::setTexture(0, s_albedo, m_groundTexture);
  523. bgfx::setTexture(1, s_normal, m_normalTexture);
  524. _uniforms.m_color[0] = r;
  525. _uniforms.m_color[1] = g;
  526. _uniforms.m_color[2] = b;
  527. _uniforms.submit();
  528. meshSubmit(m_meshes[MeshHollowCube], _pass, _program, mtx);
  529. }
  530. }
  531. // draw box as ground plane
  532. {
  533. const float posY = -2.0f;
  534. const float scale = length;
  535. float mtx[16];
  536. bx::mtxSRT(mtx
  537. , scale
  538. , scale
  539. , scale
  540. , 0.0f
  541. , 0.0f
  542. , 0.0f
  543. , 0.0f
  544. , -scale + posY
  545. , 0.0f
  546. );
  547. _uniforms.m_color[0] = 0.5f;
  548. _uniforms.m_color[1] = 0.5f;
  549. _uniforms.m_color[2] = 0.5f;
  550. _uniforms.submit();
  551. meshSubmit(m_meshes[MeshCube], _pass, m_gridProgram, mtx);
  552. }
  553. }
  554. bgfx::ViewId drawDepthOfField(bgfx::ViewId _pass, bgfx::TextureHandle _colorTexture, float* _orthoProj, bool _originBottomLeft)
  555. {
  556. bgfx::ViewId view = _pass;
  557. bgfx::TextureHandle lastTex = _colorTexture;
  558. if (m_showDebugVisualization)
  559. {
  560. bgfx::setViewName(view, "bokeh dof debug pass");
  561. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  562. bgfx::setViewTransform(view, NULL, _orthoProj);
  563. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  564. bgfx::setState(0
  565. | BGFX_STATE_WRITE_RGB
  566. | BGFX_STATE_WRITE_A
  567. | BGFX_STATE_DEPTH_TEST_ALWAYS
  568. );
  569. bgfx::setTexture(0, s_color, lastTex);
  570. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  571. m_uniforms.submit();
  572. screenSpaceQuad(_originBottomLeft);
  573. bgfx::submit(view, m_dofDebugProgram);
  574. ++view;
  575. }
  576. else if (m_useSinglePassBokehDof)
  577. {
  578. bgfx::setViewName(view, "bokeh dof single pass");
  579. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  580. bgfx::setViewTransform(view, NULL, _orthoProj);
  581. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  582. bgfx::setState(0
  583. | BGFX_STATE_WRITE_RGB
  584. | BGFX_STATE_WRITE_A
  585. | BGFX_STATE_DEPTH_TEST_ALWAYS
  586. );
  587. bgfx::setTexture(0, s_color, lastTex);
  588. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  589. m_uniforms.submit();
  590. screenSpaceQuad(_originBottomLeft);
  591. bgfx::submit(view, m_dofSinglePassProgram);
  592. ++view;
  593. }
  594. else
  595. {
  596. unsigned halfWidth = (m_width/2);
  597. unsigned halfHeight = (m_height/2);
  598. bgfx::setViewName(view, "bokeh dof downsample");
  599. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  600. bgfx::setViewTransform(view, NULL, _orthoProj);
  601. bgfx::setViewFrameBuffer(view, m_dofQuarterInput.m_buffer);
  602. bgfx::setState(0
  603. | BGFX_STATE_WRITE_RGB
  604. | BGFX_STATE_WRITE_A
  605. | BGFX_STATE_DEPTH_TEST_ALWAYS
  606. );
  607. bgfx::setTexture(0, s_color, lastTex);
  608. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  609. m_uniforms.submit();
  610. screenSpaceQuad(_originBottomLeft);
  611. bgfx::submit(view, m_dofDownsampleProgram);
  612. ++view;
  613. lastTex = m_dofQuarterInput.m_texture;
  614. /*
  615. replace the copy with bokeh dof combine
  616. able to read circle of confusion and color from downsample pass
  617. along with full res color and depth?
  618. do we need half res depth? i'm confused about that...
  619. */
  620. bgfx::setViewName(view, "bokeh dof quarter");
  621. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  622. bgfx::setViewTransform(view, NULL, _orthoProj);
  623. bgfx::setViewFrameBuffer(view, m_dofQuarterOutput.m_buffer);
  624. bgfx::setState(0
  625. | BGFX_STATE_WRITE_RGB
  626. | BGFX_STATE_WRITE_A
  627. | BGFX_STATE_DEPTH_TEST_ALWAYS
  628. );
  629. bgfx::setTexture(0, s_color, lastTex);
  630. m_uniforms.submit();
  631. screenSpaceQuad(_originBottomLeft);
  632. bgfx::submit(view, m_dofQuarterProgram);
  633. ++view;
  634. lastTex = m_dofQuarterOutput.m_texture;
  635. bgfx::setViewName(view, "bokeh dof combine");
  636. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  637. bgfx::setViewTransform(view, NULL, _orthoProj);
  638. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  639. bgfx::setState(0
  640. | BGFX_STATE_WRITE_RGB
  641. | BGFX_STATE_WRITE_A
  642. | BGFX_STATE_DEPTH_TEST_ALWAYS
  643. );
  644. bgfx::setTexture(0, s_color, _colorTexture);
  645. bgfx::setTexture(1, s_blurredColor, lastTex);
  646. m_uniforms.submit();
  647. screenSpaceQuad(_originBottomLeft);
  648. bgfx::submit(view, m_dofCombineProgram);
  649. ++view;
  650. }
  651. return view;
  652. }
  653. void createFramebuffers()
  654. {
  655. m_size[0] = m_width;
  656. m_size[1] = m_height;
  657. const uint64_t bilinearFlags = 0
  658. | BGFX_TEXTURE_RT
  659. | BGFX_SAMPLER_U_CLAMP
  660. | BGFX_SAMPLER_V_CLAMP
  661. ;
  662. m_frameBufferTex[FRAMEBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  663. m_frameBufferTex[FRAMEBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, bilinearFlags);
  664. m_frameBuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_frameBufferTex), m_frameBufferTex, true);
  665. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, bilinearFlags);
  666. unsigned halfWidth = m_size[0]/2;
  667. unsigned halfHeight = m_size[1]/2;
  668. m_dofQuarterInput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  669. m_dofQuarterOutput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  670. }
  671. // all buffers set to destroy their textures
  672. void destroyFramebuffers()
  673. {
  674. bgfx::destroy(m_frameBuffer);
  675. m_linearDepth.destroy();
  676. m_dofQuarterInput.destroy();
  677. m_dofQuarterOutput.destroy();
  678. }
  679. void updateUniforms()
  680. {
  681. // from assao sample, cs_assao_prepare_depths.sc
  682. {
  683. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  684. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  685. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  686. float depthLinearizeMul = -m_proj2[3*4+2];
  687. float depthLinearizeAdd = m_proj2[2*4+2];
  688. if (depthLinearizeMul * depthLinearizeAdd < 0)
  689. {
  690. depthLinearizeAdd = -depthLinearizeAdd;
  691. }
  692. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  693. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  694. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  695. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  696. {
  697. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  698. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  699. }
  700. else
  701. {
  702. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  703. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  704. }
  705. }
  706. m_uniforms.m_frameIdx = float(m_currFrame % 8);
  707. {
  708. float lightPosition[] = { 0.0f, 6.0f, 10.0f };
  709. bx::memCopy(m_modelUniforms.m_lightPosition, lightPosition, 3*sizeof(float));
  710. }
  711. // bokeh depth of field
  712. {
  713. // reduce dimensions by half to go along with smaller render target
  714. const float blurScale = (m_useSinglePassBokehDof) ? 1.0f : 0.5f;
  715. m_uniforms.m_blurSteps = m_blurSteps;
  716. m_uniforms.m_lobeCount = float(m_lobeCount);
  717. m_uniforms.m_lobeRadiusMin = (1.0f - m_lobePinch);
  718. m_uniforms.m_lobeRadiusDelta2x = 2.0f * m_lobePinch;
  719. m_uniforms.m_maxBlurSize = m_maxBlurSize * blurScale;
  720. m_uniforms.m_focusPoint = m_focusPoint;
  721. m_uniforms.m_focusScale = m_focusScale;
  722. m_uniforms.m_radiusScale = m_radiusScale * blurScale;
  723. m_uniforms.m_lobeRotation = m_lobeRotation;
  724. }
  725. }
  726. static float bokehShapeFromAngle (int _lobeCount, float _radiusMin, float _radiusDelta2x, float _rotation, float _theta)
  727. {
  728. // don't shape for 0, 1 blades...
  729. if (_lobeCount <= 1)
  730. {
  731. return 1.0f;
  732. }
  733. // divide edge into some number of lobes
  734. const float invPeriod = float(_lobeCount) / (bx::kPi2);
  735. float periodFraction = bx::fract(_theta * invPeriod + _rotation);
  736. // apply triangle shape to each lobe to approximate blades of a camera aperture
  737. periodFraction = bx::abs(periodFraction - 0.5f);
  738. return periodFraction * _radiusDelta2x + _radiusMin;
  739. }
  740. void updateDisplayBokehTexture(
  741. float _radiusScale,
  742. float _maxBlurSize,
  743. int _lobeCount,
  744. float _lobeRadiusMin,
  745. float _lobeRadiusMax,
  746. float _lobeRotation)
  747. {
  748. if (m_bokehTexture.idx != bgfx::kInvalidHandle)
  749. {
  750. bgfx::destroy(m_bokehTexture);
  751. }
  752. BX_ASSERT(0 < _lobeCount, "");
  753. const int32_t bokehSize = 128;
  754. const bgfx::Memory* mem = bgfx::alloc(bokehSize*bokehSize*4);
  755. bx::memSet(mem->data, 0x00, bokehSize*bokehSize*4);
  756. const float thetaStep = 2.39996323f; // golden angle
  757. float loopValue = _radiusScale;
  758. const float loopEnd = _maxBlurSize;
  759. float theta = 0.0f;
  760. // bokeh shape function multiples this by half later
  761. const float radiusDelta2x = 2.0f * (_lobeRadiusMax - _lobeRadiusMin);
  762. int32_t counter = 0;
  763. while (loopValue < loopEnd)
  764. {
  765. float radius = loopValue;
  766. // apply shape to circular distribution
  767. const float shapeScale = bokehShapeFromAngle(_lobeCount, _lobeRadiusMin, radiusDelta2x, _lobeRotation, theta);
  768. BX_ASSERT(_lobeRadiusMin <= shapeScale, "");
  769. float spiralCoordX = bx::cos(theta) * (radius * shapeScale);
  770. float spiralCoordY = bx::sin(theta) * (radius * shapeScale);
  771. // normalize for texture display
  772. spiralCoordX /= _maxBlurSize;
  773. spiralCoordY /= _maxBlurSize;
  774. // scale from -1,1 into 0,1 normalized texture space
  775. spiralCoordX = spiralCoordX * 0.5f + 0.5f;
  776. spiralCoordY = spiralCoordY * 0.5f + 0.5f;
  777. // convert to pixel coordinates
  778. int32_t pixelCoordX = int32_t(bx::floor(spiralCoordX * float(bokehSize-1) + 0.5f));
  779. int32_t pixelCoordY = int32_t(bx::floor(spiralCoordY * float(bokehSize-1) + 0.5f));
  780. BX_ASSERT(0 <= pixelCoordX, "");
  781. BX_ASSERT(0 <= pixelCoordY, "");
  782. BX_ASSERT(pixelCoordX < bokehSize, "");
  783. BX_ASSERT(pixelCoordY < bokehSize, "");
  784. // plot sample position, track for total samples
  785. uint32_t offset = (pixelCoordY * bokehSize + pixelCoordX) * 4;
  786. mem->data[offset + 0] = 0xff;
  787. mem->data[offset + 1] = 0xff;
  788. mem->data[offset + 2] = 0xff;
  789. mem->data[offset + 3] = 0xff;
  790. ++counter;
  791. theta += thetaStep;
  792. loopValue += (_radiusScale / loopValue);
  793. }
  794. m_sampleCount = counter;
  795. // hoping texture deals with mem
  796. m_bokehTexture = bgfx::createTexture2D(bokehSize, bokehSize, false, 1
  797. , bgfx::TextureFormat::BGRA8
  798. , 0
  799. | BGFX_SAMPLER_MIN_POINT
  800. | BGFX_SAMPLER_MIP_POINT
  801. | BGFX_SAMPLER_MAG_POINT
  802. , mem
  803. );
  804. }
  805. uint32_t m_width;
  806. uint32_t m_height;
  807. uint32_t m_debug;
  808. uint32_t m_reset;
  809. entry::MouseState m_mouseState;
  810. // Resource handles
  811. bgfx::ProgramHandle m_forwardProgram;
  812. bgfx::ProgramHandle m_gridProgram;
  813. bgfx::ProgramHandle m_copyProgram;
  814. bgfx::ProgramHandle m_copyLinearToGammaProgram;
  815. bgfx::ProgramHandle m_linearDepthProgram;
  816. bgfx::ProgramHandle m_dofSinglePassProgram;
  817. bgfx::ProgramHandle m_dofDownsampleProgram;
  818. bgfx::ProgramHandle m_dofQuarterProgram;
  819. bgfx::ProgramHandle m_dofCombineProgram;
  820. bgfx::ProgramHandle m_dofDebugProgram;
  821. // Shader uniforms
  822. PassUniforms m_uniforms;
  823. ModelUniforms m_modelUniforms;
  824. // Uniforms to identify texture samplers
  825. bgfx::UniformHandle s_albedo;
  826. bgfx::UniformHandle s_color;
  827. bgfx::UniformHandle s_normal;
  828. bgfx::UniformHandle s_depth;
  829. bgfx::UniformHandle s_blurredColor;
  830. bgfx::FrameBufferHandle m_frameBuffer;
  831. bgfx::TextureHandle m_frameBufferTex[FRAMEBUFFER_RENDER_TARGETS];
  832. RenderTarget m_linearDepth;
  833. RenderTarget m_dofQuarterInput;
  834. RenderTarget m_dofQuarterOutput;
  835. struct Model
  836. {
  837. uint32_t mesh; // Index of mesh in m_meshes
  838. float position[3];
  839. };
  840. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  841. bgfx::TextureHandle m_groundTexture;
  842. bgfx::TextureHandle m_normalTexture;
  843. bgfx::TextureHandle m_bokehTexture;
  844. uint32_t m_currFrame;
  845. float m_lightRotation = 0.0f;
  846. float m_fovY = 60.0f;
  847. bool m_recreateFrameBuffers = false;
  848. float m_animationTime = 0.0f;
  849. float m_view[16];
  850. float m_proj[16];
  851. float m_proj2[16];
  852. int32_t m_size[2];
  853. // UI parameters
  854. bool m_useBokehDof = true;
  855. bool m_useSinglePassBokehDof = false;
  856. float m_maxBlurSize = 20.0f;
  857. float m_focusPoint = 5.0f;
  858. float m_focusScale = 3.0f;
  859. float m_radiusScale = 0.5f;
  860. float m_blurSteps = 50.0f;
  861. bool m_showDebugVisualization = false;
  862. int32_t m_lobeCount = 6;
  863. float m_lobePinch = 0.2f;
  864. float m_lobeRotation = 0.0f;
  865. int32_t m_sampleCount = 0;
  866. };
  867. } // namespace
  868. ENTRY_IMPLEMENT_MAIN(ExampleBokeh, "45-bokeh", "Bokeh Depth of Field");