bokeh.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. /*
  2. * Copyright 2021 elven cache. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  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(float _textureWidth, float _textureHeight, float _texelHalf, 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 texelHalfW = _texelHalf / _textureWidth;
  146. const float texelHalfH = _texelHalf / _textureHeight;
  147. const float minu = -1.0f + texelHalfW;
  148. const float maxu = 1.0f + texelHalfW;
  149. const float zz = 0.0f;
  150. float minv = texelHalfH;
  151. float maxv = 2.0f + texelHalfH;
  152. if (_originBottomLeft)
  153. {
  154. float temp = minv;
  155. minv = maxv;
  156. maxv = temp;
  157. minv -= 1.0f;
  158. maxv -= 1.0f;
  159. }
  160. vertex[0].m_x = minx;
  161. vertex[0].m_y = miny;
  162. vertex[0].m_z = zz;
  163. vertex[0].m_u = minu;
  164. vertex[0].m_v = minv;
  165. vertex[1].m_x = maxx;
  166. vertex[1].m_y = miny;
  167. vertex[1].m_z = zz;
  168. vertex[1].m_u = maxu;
  169. vertex[1].m_v = minv;
  170. vertex[2].m_x = maxx;
  171. vertex[2].m_y = maxy;
  172. vertex[2].m_z = zz;
  173. vertex[2].m_u = maxu;
  174. vertex[2].m_v = maxv;
  175. bgfx::setVertexBuffer(0, &vb);
  176. }
  177. }
  178. void vec2Set(float* _v, float _x, float _y)
  179. {
  180. _v[0] = _x;
  181. _v[1] = _y;
  182. }
  183. class ExampleBokeh : public entry::AppI
  184. {
  185. public:
  186. ExampleBokeh(const char* _name, const char* _description)
  187. : entry::AppI(_name, _description)
  188. , m_currFrame(UINT32_MAX)
  189. , m_texelHalf(0.0f)
  190. {
  191. }
  192. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  193. {
  194. Args args(_argc, _argv);
  195. m_width = _width;
  196. m_height = _height;
  197. m_debug = BGFX_DEBUG_NONE;
  198. m_reset = BGFX_RESET_VSYNC;
  199. bgfx::Init init;
  200. init.type = args.m_type;
  201. init.vendorId = args.m_pciId;
  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. // Get renderer capabilities info.
  248. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  249. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  250. m_bokehTexture.idx = bgfx::kInvalidHandle;
  251. updateDisplayBokehTexture(m_radiusScale, m_maxBlurSize, m_lobeCount, (1.0f-m_lobePinch), 1.0f, m_lobeRotation);
  252. imguiCreate();
  253. }
  254. int32_t shutdown() override
  255. {
  256. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  257. {
  258. meshUnload(m_meshes[ii]);
  259. }
  260. bgfx::destroy(m_normalTexture);
  261. bgfx::destroy(m_groundTexture);
  262. bgfx::destroy(m_bokehTexture);
  263. bgfx::destroy(m_forwardProgram);
  264. bgfx::destroy(m_gridProgram);
  265. bgfx::destroy(m_copyProgram);
  266. bgfx::destroy(m_copyLinearToGammaProgram);
  267. bgfx::destroy(m_linearDepthProgram);
  268. bgfx::destroy(m_dofSinglePassProgram);
  269. bgfx::destroy(m_dofDownsampleProgram);
  270. bgfx::destroy(m_dofQuarterProgram);
  271. bgfx::destroy(m_dofCombineProgram);
  272. bgfx::destroy(m_dofDebugProgram);
  273. m_uniforms.destroy();
  274. m_modelUniforms.destroy();
  275. bgfx::destroy(s_albedo);
  276. bgfx::destroy(s_color);
  277. bgfx::destroy(s_normal);
  278. bgfx::destroy(s_depth);
  279. bgfx::destroy(s_blurredColor);
  280. destroyFramebuffers();
  281. cameraDestroy();
  282. imguiDestroy();
  283. bgfx::shutdown();
  284. return 0;
  285. }
  286. bool update() override
  287. {
  288. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  289. {
  290. // skip processing when minimized, otherwise crashing
  291. if (0 == m_width || 0 == m_height)
  292. {
  293. return true;
  294. }
  295. // Update frame timer
  296. int64_t now = bx::getHPCounter();
  297. static int64_t last = now;
  298. const int64_t frameTime = now - last;
  299. last = now;
  300. const double freq = double(bx::getHPFrequency());
  301. const float deltaTime = float(frameTime / freq);
  302. const bgfx::Caps* caps = bgfx::getCaps();
  303. if (m_size[0] != (int32_t)m_width
  304. || m_size[1] != (int32_t)m_height
  305. || m_recreateFrameBuffers)
  306. {
  307. destroyFramebuffers();
  308. createFramebuffers();
  309. m_recreateFrameBuffers = false;
  310. }
  311. // update animation time
  312. const float rotationSpeed = 0.75f;
  313. m_animationTime += deltaTime * rotationSpeed;
  314. if (bx::kPi2 < m_animationTime)
  315. {
  316. m_animationTime -= bx::kPi2;
  317. }
  318. // Update camera
  319. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  320. cameraGetViewMtx(m_view);
  321. updateUniforms();
  322. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  323. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  324. bgfx::ViewId view = 0;
  325. // Draw models into scene
  326. {
  327. bgfx::setViewName(view, "forward scene");
  328. bgfx::setViewClear(view
  329. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  330. , 0x7fb8ffff // clear to a sky blue
  331. , 1.0f
  332. , 0
  333. );
  334. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  335. bgfx::setViewTransform(view, m_view, m_proj);
  336. bgfx::setViewFrameBuffer(view, m_frameBuffer);
  337. bgfx::setState(0
  338. | BGFX_STATE_WRITE_RGB
  339. | BGFX_STATE_WRITE_A
  340. | BGFX_STATE_WRITE_Z
  341. | BGFX_STATE_DEPTH_TEST_LESS
  342. );
  343. drawAllModels(view, m_forwardProgram, m_modelUniforms);
  344. ++view;
  345. }
  346. float orthoProj[16];
  347. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  348. {
  349. // clear out transform stack
  350. float identity[16];
  351. bx::mtxIdentity(identity);
  352. bgfx::setTransform(identity);
  353. }
  354. // Convert depth to linear depth for shadow depth compare
  355. {
  356. bgfx::setViewName(view, "linear depth");
  357. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  358. bgfx::setViewTransform(view, NULL, orthoProj);
  359. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  360. bgfx::setState(0
  361. | BGFX_STATE_WRITE_RGB
  362. | BGFX_STATE_WRITE_A
  363. | BGFX_STATE_DEPTH_TEST_ALWAYS
  364. );
  365. bgfx::setTexture(0, s_depth, m_frameBufferTex[FRAMEBUFFER_RT_DEPTH]);
  366. m_uniforms.submit();
  367. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  368. bgfx::submit(view, m_linearDepthProgram);
  369. ++view;
  370. }
  371. // optionally, apply dof
  372. const bool useOrDebugDof = m_useBokehDof || m_showDebugVisualization;
  373. if (useOrDebugDof)
  374. {
  375. view = drawDepthOfField(view, m_frameBufferTex[FRAMEBUFFER_RT_COLOR], orthoProj, caps->originBottomLeft);
  376. }
  377. else
  378. {
  379. bgfx::setViewName(view, "display");
  380. bgfx::setViewClear(view
  381. , BGFX_CLEAR_NONE
  382. , 0
  383. , 1.0f
  384. , 0
  385. );
  386. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  387. bgfx::setViewTransform(view, NULL, orthoProj);
  388. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  389. bgfx::setState(0
  390. | BGFX_STATE_WRITE_RGB
  391. | BGFX_STATE_WRITE_A
  392. );
  393. bgfx::setTexture(0, s_color, m_frameBufferTex[FRAMEBUFFER_RT_COLOR]);
  394. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  395. bgfx::submit(view, m_copyLinearToGammaProgram);
  396. ++view;
  397. }
  398. // Draw UI
  399. imguiBeginFrame(m_mouseState.m_mx
  400. , m_mouseState.m_my
  401. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  402. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  403. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  404. , m_mouseState.m_mz
  405. , uint16_t(m_width)
  406. , uint16_t(m_height)
  407. );
  408. showExampleDialog(this);
  409. ImGui::SetNextWindowPos(
  410. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  411. , ImGuiCond_FirstUseEver
  412. );
  413. ImGui::SetNextWindowSize(
  414. ImVec2(m_width / 4.0f, m_height / 1.35f)
  415. , ImGuiCond_FirstUseEver
  416. );
  417. ImGui::Begin("Settings"
  418. , NULL
  419. , 0
  420. );
  421. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  422. {
  423. ImGui::Checkbox("use bokeh dof", &m_useBokehDof);
  424. if (ImGui::IsItemHovered())
  425. ImGui::SetTooltip("turn effect on and off");
  426. ImGui::Checkbox("use single pass at full res", &m_useSinglePassBokehDof);
  427. if (ImGui::IsItemHovered())
  428. {
  429. ImGui::BeginTooltip();
  430. ImGui::Text("calculate in a single pass at full resolution or use");
  431. ImGui::Text("multiple passes to compute at lower res and composite");
  432. ImGui::EndTooltip();
  433. }
  434. ImGui::Checkbox("show debug vis", &m_showDebugVisualization);
  435. if (ImGui::IsItemHovered())
  436. {
  437. ImGui::BeginTooltip();
  438. ImGui::Text("apply coloration to screen. fades from grey to orange with");
  439. ImGui::Text("increasing foreground blur. from grey to blue in background");
  440. ImGui::EndTooltip();
  441. }
  442. ImGui::Separator();
  443. bool isChanged = false;
  444. ImGui::Text("blur controls:");
  445. isChanged |= ImGui::SliderFloat("max blur size", &m_maxBlurSize, 10.0f, 50.0f);
  446. if (ImGui::IsItemHovered())
  447. ImGui::SetTooltip("maximum blur size in screen pixels");
  448. ImGui::SliderFloat("focusPoint", &m_focusPoint, 1.0f, 20.0f);
  449. if (ImGui::IsItemHovered())
  450. ImGui::SetTooltip("distance to focus plane");
  451. ImGui::SliderFloat("focusScale", &m_focusScale, 0.0f, 10.0f);
  452. if (ImGui::IsItemHovered())
  453. ImGui::SetTooltip("multiply focus calculation, larger=tighter focus");
  454. ImGui::Separator();
  455. ImGui::Text("bokeh shape and sample controls:");
  456. isChanged |= ImGui::SliderFloat("radiusScale", &m_radiusScale, 0.5f, 4.0f);
  457. if (ImGui::IsItemHovered())
  458. ImGui::SetTooltip("controls number of samples taken");
  459. isChanged |= ImGui::SliderInt("lobe count", &m_lobeCount, 1, 8);
  460. if (ImGui::IsItemHovered())
  461. ImGui::SetTooltip("using triangle lobes to emulate aperture blades");
  462. isChanged |= ImGui::SliderFloat("lobe pinch", &m_lobePinch, 0.0f, 1.0f);
  463. if (ImGui::IsItemHovered())
  464. ImGui::SetTooltip("adjust lobe shape, 0=round, 1=starry");
  465. isChanged |= ImGui::SliderFloat("lobe rotation", &m_lobeRotation, -1.0f, 1.0f);
  466. if (isChanged)
  467. {
  468. updateDisplayBokehTexture(m_radiusScale, m_maxBlurSize, m_lobeCount, (1.0f-m_lobePinch), 1.0f, m_lobeRotation);
  469. }
  470. ImGui::Text("number of samples taken: %d", m_sampleCount);
  471. if (ImGui::IsItemHovered())
  472. ImGui::SetTooltip("number of sample taps as determined by radiusScale and maxBlurSize");
  473. ImGui::Image(m_bokehTexture, ImVec2(128.0f, 128.0f) );
  474. }
  475. ImGui::End();
  476. imguiEndFrame();
  477. // Advance to next frame. Rendering thread will be kicked to
  478. // process submitted rendering primitives.
  479. m_currFrame = bgfx::frame();
  480. return true;
  481. }
  482. return false;
  483. }
  484. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, ModelUniforms & _uniforms)
  485. {
  486. const int32_t width = 6;
  487. const int32_t length = 20;
  488. float c0[] = { 72.0f/255.0f, 126.0f/255.0f, 149.0f/255.0f }; // blue
  489. float c1[] = { 235.0f/255.0f, 146.0f/255.0f, 251.0f/255.0f }; // purple
  490. float c2[] = { 199.0f/255.0f, 0.0f/255.0f, 57.0f/255.0f }; // pink
  491. for (int32_t zz = 0; zz < length; ++zz)
  492. {
  493. // make a color gradient, nothing special about this for example
  494. float * ca = c0;
  495. float * cb = c1;
  496. float lerpVal = float(zz) / float(length);
  497. if (0.5f <= lerpVal)
  498. {
  499. ca = c1;
  500. cb = c2;
  501. }
  502. lerpVal = bx::fract(2.0f*lerpVal);
  503. float r = bx::lerp(ca[0], cb[0], lerpVal);
  504. float g = bx::lerp(ca[1], cb[1], lerpVal);
  505. float b = bx::lerp(ca[2], cb[2], lerpVal);
  506. for (int32_t xx = 0; xx < width; ++xx)
  507. {
  508. const float angle = m_animationTime + float(zz)*(bx::kPi2/length) + float(xx)*(bx::kPiHalf/width);
  509. const float posX = 2.0f * xx - width + 1.0f;
  510. const float posY = bx::sin(angle);
  511. const float posZ = 2.0f * zz - length + 1.0f;
  512. const float scale = s_meshScale[MeshHollowCube];
  513. float mtx[16];
  514. bx::mtxSRT(mtx
  515. , scale
  516. , scale
  517. , scale
  518. , 0.0f
  519. , 0.0f
  520. , 0.0f
  521. , posX
  522. , posY
  523. , posZ
  524. );
  525. bgfx::setTexture(0, s_albedo, m_groundTexture);
  526. bgfx::setTexture(1, s_normal, m_normalTexture);
  527. _uniforms.m_color[0] = r;
  528. _uniforms.m_color[1] = g;
  529. _uniforms.m_color[2] = b;
  530. _uniforms.submit();
  531. meshSubmit(m_meshes[MeshHollowCube], _pass, _program, mtx);
  532. }
  533. }
  534. // draw box as ground plane
  535. {
  536. const float posY = -2.0f;
  537. const float scale = length;
  538. float mtx[16];
  539. bx::mtxSRT(mtx
  540. , scale
  541. , scale
  542. , scale
  543. , 0.0f
  544. , 0.0f
  545. , 0.0f
  546. , 0.0f
  547. , -scale + posY
  548. , 0.0f
  549. );
  550. _uniforms.m_color[0] = 0.5f;
  551. _uniforms.m_color[1] = 0.5f;
  552. _uniforms.m_color[2] = 0.5f;
  553. _uniforms.submit();
  554. meshSubmit(m_meshes[MeshCube], _pass, m_gridProgram, mtx);
  555. }
  556. }
  557. bgfx::ViewId drawDepthOfField(bgfx::ViewId _pass, bgfx::TextureHandle _colorTexture, float* _orthoProj, bool _originBottomLeft)
  558. {
  559. bgfx::ViewId view = _pass;
  560. bgfx::TextureHandle lastTex = _colorTexture;
  561. if (m_showDebugVisualization)
  562. {
  563. bgfx::setViewName(view, "bokeh dof debug pass");
  564. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  565. bgfx::setViewTransform(view, NULL, _orthoProj);
  566. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  567. bgfx::setState(0
  568. | BGFX_STATE_WRITE_RGB
  569. | BGFX_STATE_WRITE_A
  570. | BGFX_STATE_DEPTH_TEST_ALWAYS
  571. );
  572. bgfx::setTexture(0, s_color, lastTex);
  573. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  574. m_uniforms.submit();
  575. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  576. bgfx::submit(view, m_dofDebugProgram);
  577. ++view;
  578. }
  579. else if (m_useSinglePassBokehDof)
  580. {
  581. bgfx::setViewName(view, "bokeh dof single pass");
  582. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  583. bgfx::setViewTransform(view, NULL, _orthoProj);
  584. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  585. bgfx::setState(0
  586. | BGFX_STATE_WRITE_RGB
  587. | BGFX_STATE_WRITE_A
  588. | BGFX_STATE_DEPTH_TEST_ALWAYS
  589. );
  590. bgfx::setTexture(0, s_color, lastTex);
  591. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  592. m_uniforms.submit();
  593. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  594. bgfx::submit(view, m_dofSinglePassProgram);
  595. ++view;
  596. }
  597. else
  598. {
  599. unsigned halfWidth = (m_width/2);
  600. unsigned halfHeight = (m_height/2);
  601. bgfx::setViewName(view, "bokeh dof downsample");
  602. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  603. bgfx::setViewTransform(view, NULL, _orthoProj);
  604. bgfx::setViewFrameBuffer(view, m_dofQuarterInput.m_buffer);
  605. bgfx::setState(0
  606. | BGFX_STATE_WRITE_RGB
  607. | BGFX_STATE_WRITE_A
  608. | BGFX_STATE_DEPTH_TEST_ALWAYS
  609. );
  610. bgfx::setTexture(0, s_color, lastTex);
  611. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  612. m_uniforms.submit();
  613. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  614. bgfx::submit(view, m_dofDownsampleProgram);
  615. ++view;
  616. lastTex = m_dofQuarterInput.m_texture;
  617. /*
  618. replace the copy with bokeh dof combine
  619. able to read circle of confusion and color from downsample pass
  620. along with full res color and depth?
  621. do we need half res depth? i'm confused about that...
  622. */
  623. bgfx::setViewName(view, "bokeh dof quarter");
  624. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  625. bgfx::setViewTransform(view, NULL, _orthoProj);
  626. bgfx::setViewFrameBuffer(view, m_dofQuarterOutput.m_buffer);
  627. bgfx::setState(0
  628. | BGFX_STATE_WRITE_RGB
  629. | BGFX_STATE_WRITE_A
  630. | BGFX_STATE_DEPTH_TEST_ALWAYS
  631. );
  632. bgfx::setTexture(0, s_color, lastTex);
  633. m_uniforms.submit();
  634. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  635. bgfx::submit(view, m_dofQuarterProgram);
  636. ++view;
  637. lastTex = m_dofQuarterOutput.m_texture;
  638. bgfx::setViewName(view, "bokeh dof combine");
  639. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  640. bgfx::setViewTransform(view, NULL, _orthoProj);
  641. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  642. bgfx::setState(0
  643. | BGFX_STATE_WRITE_RGB
  644. | BGFX_STATE_WRITE_A
  645. | BGFX_STATE_DEPTH_TEST_ALWAYS
  646. );
  647. bgfx::setTexture(0, s_color, _colorTexture);
  648. bgfx::setTexture(1, s_blurredColor, lastTex);
  649. m_uniforms.submit();
  650. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  651. bgfx::submit(view, m_dofCombineProgram);
  652. ++view;
  653. }
  654. return view;
  655. }
  656. void createFramebuffers()
  657. {
  658. m_size[0] = m_width;
  659. m_size[1] = m_height;
  660. const uint64_t bilinearFlags = 0
  661. | BGFX_TEXTURE_RT
  662. | BGFX_SAMPLER_U_CLAMP
  663. | BGFX_SAMPLER_V_CLAMP
  664. ;
  665. m_frameBufferTex[FRAMEBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  666. m_frameBufferTex[FRAMEBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, bilinearFlags);
  667. m_frameBuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_frameBufferTex), m_frameBufferTex, true);
  668. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, bilinearFlags);
  669. unsigned halfWidth = m_size[0]/2;
  670. unsigned halfHeight = m_size[1]/2;
  671. m_dofQuarterInput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  672. m_dofQuarterOutput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  673. }
  674. // all buffers set to destroy their textures
  675. void destroyFramebuffers()
  676. {
  677. bgfx::destroy(m_frameBuffer);
  678. m_linearDepth.destroy();
  679. m_dofQuarterInput.destroy();
  680. m_dofQuarterOutput.destroy();
  681. }
  682. void updateUniforms()
  683. {
  684. // from assao sample, cs_assao_prepare_depths.sc
  685. {
  686. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  687. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  688. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  689. float depthLinearizeMul = -m_proj2[3*4+2];
  690. float depthLinearizeAdd = m_proj2[2*4+2];
  691. if (depthLinearizeMul * depthLinearizeAdd < 0)
  692. {
  693. depthLinearizeAdd = -depthLinearizeAdd;
  694. }
  695. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  696. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  697. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  698. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  699. {
  700. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  701. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  702. }
  703. else
  704. {
  705. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  706. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  707. }
  708. }
  709. m_uniforms.m_frameIdx = float(m_currFrame % 8);
  710. {
  711. float lightPosition[] = { 0.0f, 6.0f, 10.0f };
  712. bx::memCopy(m_modelUniforms.m_lightPosition, lightPosition, 3*sizeof(float));
  713. }
  714. // bokeh depth of field
  715. {
  716. // reduce dimensions by half to go along with smaller render target
  717. const float blurScale = (m_useSinglePassBokehDof) ? 1.0f : 0.5f;
  718. m_uniforms.m_blurSteps = m_blurSteps;
  719. m_uniforms.m_lobeCount = float(m_lobeCount);
  720. m_uniforms.m_lobeRadiusMin = (1.0f - m_lobePinch);
  721. m_uniforms.m_lobeRadiusDelta2x = 2.0f * m_lobePinch;
  722. m_uniforms.m_maxBlurSize = m_maxBlurSize * blurScale;
  723. m_uniforms.m_focusPoint = m_focusPoint;
  724. m_uniforms.m_focusScale = m_focusScale;
  725. m_uniforms.m_radiusScale = m_radiusScale * blurScale;
  726. m_uniforms.m_lobeRotation = m_lobeRotation;
  727. }
  728. }
  729. static float bokehShapeFromAngle (int _lobeCount, float _radiusMin, float _radiusDelta2x, float _rotation, float _theta)
  730. {
  731. // don't shape for 0, 1 blades...
  732. if (_lobeCount <= 1)
  733. {
  734. return 1.0f;
  735. }
  736. // divide edge into some number of lobes
  737. const float invPeriod = float(_lobeCount) / (bx::kPi2);
  738. float periodFraction = bx::fract(_theta * invPeriod + _rotation);
  739. // apply triangle shape to each lobe to approximate blades of a camera aperture
  740. periodFraction = bx::abs(periodFraction - 0.5f);
  741. return periodFraction * _radiusDelta2x + _radiusMin;
  742. }
  743. void updateDisplayBokehTexture(
  744. float _radiusScale,
  745. float _maxBlurSize,
  746. int _lobeCount,
  747. float _lobeRadiusMin,
  748. float _lobeRadiusMax,
  749. float _lobeRotation)
  750. {
  751. if (m_bokehTexture.idx != bgfx::kInvalidHandle)
  752. {
  753. bgfx::destroy(m_bokehTexture);
  754. }
  755. BX_ASSERT(0 < _lobeCount, "");
  756. const int32_t bokehSize = 128;
  757. const bgfx::Memory* mem = bgfx::alloc(bokehSize*bokehSize*4);
  758. bx::memSet(mem->data, 0x00, bokehSize*bokehSize*4);
  759. const float thetaStep = 2.39996323f; // golden angle
  760. float loopValue = _radiusScale;
  761. const float loopEnd = _maxBlurSize;
  762. float theta = 0.0f;
  763. // bokeh shape function multiples this by half later
  764. const float radiusDelta2x = 2.0f * (_lobeRadiusMax - _lobeRadiusMin);
  765. int32_t counter = 0;
  766. while (loopValue < loopEnd)
  767. {
  768. float radius = loopValue;
  769. // apply shape to circular distribution
  770. const float shapeScale = bokehShapeFromAngle(_lobeCount, _lobeRadiusMin, radiusDelta2x, _lobeRotation, theta);
  771. BX_ASSERT(_lobeRadiusMin <= shapeScale, "");
  772. float spiralCoordX = bx::cos(theta) * (radius * shapeScale);
  773. float spiralCoordY = bx::sin(theta) * (radius * shapeScale);
  774. // normalize for texture display
  775. spiralCoordX /= _maxBlurSize;
  776. spiralCoordY /= _maxBlurSize;
  777. // scale from -1,1 into 0,1 normalized texture space
  778. spiralCoordX = spiralCoordX * 0.5f + 0.5f;
  779. spiralCoordY = spiralCoordY * 0.5f + 0.5f;
  780. // convert to pixel coordinates
  781. int32_t pixelCoordX = int32_t(bx::floor(spiralCoordX * float(bokehSize-1) + 0.5f));
  782. int32_t pixelCoordY = int32_t(bx::floor(spiralCoordY * float(bokehSize-1) + 0.5f));
  783. BX_ASSERT(0 <= pixelCoordX, "");
  784. BX_ASSERT(0 <= pixelCoordY, "");
  785. BX_ASSERT(pixelCoordX < bokehSize, "");
  786. BX_ASSERT(pixelCoordY < bokehSize, "");
  787. // plot sample position, track for total samples
  788. uint32_t offset = (pixelCoordY * bokehSize + pixelCoordX) * 4;
  789. mem->data[offset + 0] = 0xff;
  790. mem->data[offset + 1] = 0xff;
  791. mem->data[offset + 2] = 0xff;
  792. mem->data[offset + 3] = 0xff;
  793. ++counter;
  794. theta += thetaStep;
  795. loopValue += (_radiusScale / loopValue);
  796. }
  797. m_sampleCount = counter;
  798. // hoping texture deals with mem
  799. m_bokehTexture = bgfx::createTexture2D(bokehSize, bokehSize, false, 1
  800. , bgfx::TextureFormat::BGRA8
  801. , 0
  802. | BGFX_SAMPLER_MIN_POINT
  803. | BGFX_SAMPLER_MIP_POINT
  804. | BGFX_SAMPLER_MAG_POINT
  805. , mem
  806. );
  807. }
  808. uint32_t m_width;
  809. uint32_t m_height;
  810. uint32_t m_debug;
  811. uint32_t m_reset;
  812. entry::MouseState m_mouseState;
  813. // Resource handles
  814. bgfx::ProgramHandle m_forwardProgram;
  815. bgfx::ProgramHandle m_gridProgram;
  816. bgfx::ProgramHandle m_copyProgram;
  817. bgfx::ProgramHandle m_copyLinearToGammaProgram;
  818. bgfx::ProgramHandle m_linearDepthProgram;
  819. bgfx::ProgramHandle m_dofSinglePassProgram;
  820. bgfx::ProgramHandle m_dofDownsampleProgram;
  821. bgfx::ProgramHandle m_dofQuarterProgram;
  822. bgfx::ProgramHandle m_dofCombineProgram;
  823. bgfx::ProgramHandle m_dofDebugProgram;
  824. // Shader uniforms
  825. PassUniforms m_uniforms;
  826. ModelUniforms m_modelUniforms;
  827. // Uniforms to indentify texture samplers
  828. bgfx::UniformHandle s_albedo;
  829. bgfx::UniformHandle s_color;
  830. bgfx::UniformHandle s_normal;
  831. bgfx::UniformHandle s_depth;
  832. bgfx::UniformHandle s_blurredColor;
  833. bgfx::FrameBufferHandle m_frameBuffer;
  834. bgfx::TextureHandle m_frameBufferTex[FRAMEBUFFER_RENDER_TARGETS];
  835. RenderTarget m_linearDepth;
  836. RenderTarget m_dofQuarterInput;
  837. RenderTarget m_dofQuarterOutput;
  838. struct Model
  839. {
  840. uint32_t mesh; // Index of mesh in m_meshes
  841. float position[3];
  842. };
  843. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  844. bgfx::TextureHandle m_groundTexture;
  845. bgfx::TextureHandle m_normalTexture;
  846. bgfx::TextureHandle m_bokehTexture;
  847. uint32_t m_currFrame;
  848. float m_lightRotation = 0.0f;
  849. float m_texelHalf = 0.0f;
  850. float m_fovY = 60.0f;
  851. bool m_recreateFrameBuffers = false;
  852. float m_animationTime = 0.0f;
  853. float m_view[16];
  854. float m_proj[16];
  855. float m_proj2[16];
  856. int32_t m_size[2];
  857. // UI parameters
  858. bool m_useBokehDof = true;
  859. bool m_useSinglePassBokehDof = false;
  860. float m_maxBlurSize = 20.0f;
  861. float m_focusPoint = 5.0f;
  862. float m_focusScale = 3.0f;
  863. float m_radiusScale = 0.5f;
  864. float m_blurSteps = 50.0f;
  865. bool m_showDebugVisualization = false;
  866. int32_t m_lobeCount = 6;
  867. float m_lobePinch = 0.2f;
  868. float m_lobeRotation = 0.0f;
  869. int32_t m_sampleCount = 0;
  870. };
  871. } // namespace
  872. ENTRY_IMPLEMENT_MAIN(ExampleBokeh, "45-bokeh", "Bokeh Depth of Field");