webgl_postprocessing_dof2.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - postprocessing - depth-of-field</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl realistic depth-of-field bokeh example<br/>
  12. shader ported from <a href="http://blenderartists.org/forum/showthread.php?237488-GLSL-depth-of-field-with-bokeh-v2-4-(update)">Martins Upitis</a>
  13. </div>
  14. <!-- Import maps polyfill -->
  15. <!-- Remove this when import maps will be widely supported -->
  16. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.module.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import Stats from 'three/addons/libs/stats.module.js';
  28. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  29. import { BokehShader, BokehDepthShader } from 'three/addons/shaders/BokehShader2.js';
  30. let container, stats;
  31. let camera, scene, renderer, materialDepth;
  32. let windowHalfX = window.innerWidth / 2;
  33. let windowHalfY = window.innerHeight / 2;
  34. let distance = 100;
  35. let effectController;
  36. const postprocessing = { enabled: true };
  37. const shaderSettings = {
  38. rings: 3,
  39. samples: 4
  40. };
  41. const mouse = new THREE.Vector2();
  42. const raycaster = new THREE.Raycaster();
  43. const target = new THREE.Vector3( 0, 20, - 50 );
  44. const planes = [];
  45. const leaves = 100;
  46. init();
  47. animate();
  48. function init() {
  49. container = document.createElement( 'div' );
  50. document.body.appendChild( container );
  51. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 3000 );
  52. camera.position.y = 150;
  53. camera.position.z = 450;
  54. scene = new THREE.Scene();
  55. scene.add( camera );
  56. renderer = new THREE.WebGLRenderer();
  57. renderer.setPixelRatio( window.devicePixelRatio );
  58. renderer.setSize( window.innerWidth, window.innerHeight );
  59. renderer.useLegacyLights = false;
  60. renderer.autoClear = false;
  61. container.appendChild( renderer.domElement );
  62. const depthShader = BokehDepthShader;
  63. materialDepth = new THREE.ShaderMaterial( {
  64. uniforms: depthShader.uniforms,
  65. vertexShader: depthShader.vertexShader,
  66. fragmentShader: depthShader.fragmentShader
  67. } );
  68. materialDepth.uniforms[ 'mNear' ].value = camera.near;
  69. materialDepth.uniforms[ 'mFar' ].value = camera.far;
  70. // skybox
  71. const r = 'textures/cube/Bridge2/';
  72. const urls = [ r + 'posx.jpg', r + 'negx.jpg',
  73. r + 'posy.jpg', r + 'negy.jpg',
  74. r + 'posz.jpg', r + 'negz.jpg' ];
  75. const textureCube = new THREE.CubeTextureLoader().load( urls );
  76. scene.background = textureCube;
  77. // plane particles
  78. const planePiece = new THREE.PlaneGeometry( 10, 10, 1, 1 );
  79. const planeMat = new THREE.MeshPhongMaterial( {
  80. color: 0xffffff * 0.4,
  81. shininess: 0.5,
  82. specular: 0xffffff,
  83. envMap: textureCube,
  84. side: THREE.DoubleSide,
  85. forceSinglePass: true
  86. } );
  87. const rand = Math.random;
  88. for ( let i = 0; i < leaves; i ++ ) {
  89. const plane = new THREE.Mesh( planePiece, planeMat );
  90. plane.rotation.set( rand(), rand(), rand() );
  91. plane.rotation.dx = rand() * 0.1;
  92. plane.rotation.dy = rand() * 0.1;
  93. plane.rotation.dz = rand() * 0.1;
  94. plane.position.set( rand() * 150, 0 + rand() * 300, rand() * 150 );
  95. plane.position.dx = ( rand() - 0.5 );
  96. plane.position.dz = ( rand() - 0.5 );
  97. scene.add( plane );
  98. planes.push( plane );
  99. }
  100. // adding Monkeys
  101. const loader2 = new THREE.BufferGeometryLoader();
  102. loader2.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  103. geometry.computeVertexNormals();
  104. const material = new THREE.MeshPhongMaterial( {
  105. specular: 0xffffff,
  106. envMap: textureCube,
  107. shininess: 50,
  108. reflectivity: 1.0,
  109. flatShading: true
  110. } );
  111. const monkeys = 20;
  112. for ( let i = 0; i < monkeys; i ++ ) {
  113. const mesh = new THREE.Mesh( geometry, material );
  114. mesh.position.z = Math.cos( i / monkeys * Math.PI * 2 ) * 200;
  115. mesh.position.y = Math.sin( i / monkeys * Math.PI * 3 ) * 20;
  116. mesh.position.x = Math.sin( i / monkeys * Math.PI * 2 ) * 200;
  117. mesh.rotation.y = i / monkeys * Math.PI * 2;
  118. mesh.scale.setScalar( 30 );
  119. scene.add( mesh );
  120. }
  121. } );
  122. // add balls
  123. const geometry = new THREE.SphereGeometry( 1, 20, 20 );
  124. for ( let i = 0; i < 20; i ++ ) {
  125. const ballmaterial = new THREE.MeshPhongMaterial( {
  126. color: 0xffffff * Math.random(),
  127. shininess: 0.5,
  128. specular: 0xffffff,
  129. envMap: textureCube } );
  130. const mesh = new THREE.Mesh( geometry, ballmaterial );
  131. mesh.position.x = ( Math.random() - 0.5 ) * 200;
  132. mesh.position.y = Math.random() * 50;
  133. mesh.position.z = ( Math.random() - 0.5 ) * 200;
  134. mesh.scale.multiplyScalar( 10 );
  135. scene.add( mesh );
  136. }
  137. // lights
  138. scene.add( new THREE.AmbientLight( 0xcccccc ) );
  139. const directionalLight1 = new THREE.DirectionalLight( 0xffffff, 6 );
  140. directionalLight1.position.set( 2, 1.2, 10 ).normalize();
  141. scene.add( directionalLight1 );
  142. const directionalLight2 = new THREE.DirectionalLight( 0xffffff, 3 );
  143. directionalLight2.position.set( - 2, 1.2, - 10 ).normalize();
  144. scene.add( directionalLight2 );
  145. initPostprocessing();
  146. stats = new Stats();
  147. container.appendChild( stats.dom );
  148. container.style.touchAction = 'none';
  149. container.addEventListener( 'pointermove', onPointerMove );
  150. effectController = {
  151. enabled: true,
  152. jsDepthCalculation: true,
  153. shaderFocus: false,
  154. fstop: 2.2,
  155. maxblur: 1.0,
  156. showFocus: false,
  157. focalDepth: 2.8,
  158. manualdof: false,
  159. vignetting: false,
  160. depthblur: false,
  161. threshold: 0.5,
  162. gain: 2.0,
  163. bias: 0.5,
  164. fringe: 0.7,
  165. focalLength: 35,
  166. noise: true,
  167. pentagon: false,
  168. dithering: 0.0001
  169. };
  170. const matChanger = function () {
  171. for ( const e in effectController ) {
  172. if ( e in postprocessing.bokeh_uniforms ) {
  173. postprocessing.bokeh_uniforms[ e ].value = effectController[ e ];
  174. }
  175. }
  176. postprocessing.enabled = effectController.enabled;
  177. postprocessing.bokeh_uniforms[ 'znear' ].value = camera.near;
  178. postprocessing.bokeh_uniforms[ 'zfar' ].value = camera.far;
  179. camera.setFocalLength( effectController.focalLength );
  180. };
  181. const gui = new GUI();
  182. gui.add( effectController, 'enabled' ).onChange( matChanger );
  183. gui.add( effectController, 'jsDepthCalculation' ).onChange( matChanger );
  184. gui.add( effectController, 'shaderFocus' ).onChange( matChanger );
  185. gui.add( effectController, 'focalDepth', 0.0, 200.0 ).listen().onChange( matChanger );
  186. gui.add( effectController, 'fstop', 0.1, 22, 0.001 ).onChange( matChanger );
  187. gui.add( effectController, 'maxblur', 0.0, 5.0, 0.025 ).onChange( matChanger );
  188. gui.add( effectController, 'showFocus' ).onChange( matChanger );
  189. gui.add( effectController, 'manualdof' ).onChange( matChanger );
  190. gui.add( effectController, 'vignetting' ).onChange( matChanger );
  191. gui.add( effectController, 'depthblur' ).onChange( matChanger );
  192. gui.add( effectController, 'threshold', 0, 1, 0.001 ).onChange( matChanger );
  193. gui.add( effectController, 'gain', 0, 100, 0.001 ).onChange( matChanger );
  194. gui.add( effectController, 'bias', 0, 3, 0.001 ).onChange( matChanger );
  195. gui.add( effectController, 'fringe', 0, 5, 0.001 ).onChange( matChanger );
  196. gui.add( effectController, 'focalLength', 16, 80, 0.001 ).onChange( matChanger );
  197. gui.add( effectController, 'noise' ).onChange( matChanger );
  198. gui.add( effectController, 'dithering', 0, 0.001, 0.0001 ).onChange( matChanger );
  199. gui.add( effectController, 'pentagon' ).onChange( matChanger );
  200. gui.add( shaderSettings, 'rings', 1, 8 ).step( 1 ).onChange( shaderUpdate );
  201. gui.add( shaderSettings, 'samples', 1, 13 ).step( 1 ).onChange( shaderUpdate );
  202. matChanger();
  203. window.addEventListener( 'resize', onWindowResize );
  204. }
  205. function onWindowResize() {
  206. camera.aspect = window.innerWidth / window.innerHeight;
  207. camera.updateProjectionMatrix();
  208. windowHalfX = window.innerWidth / 2;
  209. windowHalfY = window.innerHeight / 2;
  210. postprocessing.rtTextureDepth.setSize( window.innerWidth, window.innerHeight );
  211. postprocessing.rtTextureColor.setSize( window.innerWidth, window.innerHeight );
  212. postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth;
  213. postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight;
  214. renderer.setSize( window.innerWidth, window.innerHeight );
  215. }
  216. function onPointerMove( event ) {
  217. if ( event.isPrimary === false ) return;
  218. mouse.x = ( event.clientX - windowHalfX ) / windowHalfX;
  219. mouse.y = - ( event.clientY - windowHalfY ) / windowHalfY;
  220. postprocessing.bokeh_uniforms[ 'focusCoords' ].value.set( event.clientX / window.innerWidth, 1 - ( event.clientY / window.innerHeight ) );
  221. }
  222. function initPostprocessing() {
  223. postprocessing.scene = new THREE.Scene();
  224. postprocessing.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 );
  225. postprocessing.camera.position.z = 100;
  226. postprocessing.scene.add( postprocessing.camera );
  227. postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, { type: THREE.HalfFloatType } );
  228. postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, { type: THREE.HalfFloatType } );
  229. const bokeh_shader = BokehShader;
  230. postprocessing.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );
  231. postprocessing.bokeh_uniforms[ 'tColor' ].value = postprocessing.rtTextureColor.texture;
  232. postprocessing.bokeh_uniforms[ 'tDepth' ].value = postprocessing.rtTextureDepth.texture;
  233. postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth;
  234. postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight;
  235. postprocessing.materialBokeh = new THREE.ShaderMaterial( {
  236. uniforms: postprocessing.bokeh_uniforms,
  237. vertexShader: bokeh_shader.vertexShader,
  238. fragmentShader: bokeh_shader.fragmentShader,
  239. defines: {
  240. RINGS: shaderSettings.rings,
  241. SAMPLES: shaderSettings.samples
  242. }
  243. } );
  244. postprocessing.quad = new THREE.Mesh( new THREE.PlaneGeometry( window.innerWidth, window.innerHeight ), postprocessing.materialBokeh );
  245. postprocessing.quad.position.z = - 500;
  246. postprocessing.scene.add( postprocessing.quad );
  247. }
  248. function shaderUpdate() {
  249. postprocessing.materialBokeh.defines.RINGS = shaderSettings.rings;
  250. postprocessing.materialBokeh.defines.SAMPLES = shaderSettings.samples;
  251. postprocessing.materialBokeh.needsUpdate = true;
  252. }
  253. function animate() {
  254. requestAnimationFrame( animate, renderer.domElement );
  255. render();
  256. stats.update();
  257. }
  258. function linearize( depth ) {
  259. const zfar = camera.far;
  260. const znear = camera.near;
  261. return - zfar * znear / ( depth * ( zfar - znear ) - zfar );
  262. }
  263. function smoothstep( near, far, depth ) {
  264. const x = saturate( ( depth - near ) / ( far - near ) );
  265. return x * x * ( 3 - 2 * x );
  266. }
  267. function saturate( x ) {
  268. return Math.max( 0, Math.min( 1, x ) );
  269. }
  270. function render() {
  271. const time = Date.now() * 0.00015;
  272. camera.position.x = Math.cos( time ) * 400;
  273. camera.position.z = Math.sin( time ) * 500;
  274. camera.position.y = Math.sin( time / 1.4 ) * 100;
  275. camera.lookAt( target );
  276. camera.updateMatrixWorld();
  277. if ( effectController.jsDepthCalculation ) {
  278. raycaster.setFromCamera( mouse, camera );
  279. const intersects = raycaster.intersectObjects( scene.children, true );
  280. const targetDistance = ( intersects.length > 0 ) ? intersects[ 0 ].distance : 1000;
  281. distance += ( targetDistance - distance ) * 0.03;
  282. const sdistance = smoothstep( camera.near, camera.far, distance );
  283. const ldistance = linearize( 1 - sdistance );
  284. postprocessing.bokeh_uniforms[ 'focalDepth' ].value = ldistance;
  285. effectController[ 'focalDepth' ] = ldistance;
  286. }
  287. for ( let i = 0; i < leaves; i ++ ) {
  288. const plane = planes[ i ];
  289. plane.rotation.x += plane.rotation.dx;
  290. plane.rotation.y += plane.rotation.dy;
  291. plane.rotation.z += plane.rotation.dz;
  292. plane.position.y -= 2;
  293. plane.position.x += plane.position.dx;
  294. plane.position.z += plane.position.dz;
  295. if ( plane.position.y < 0 ) plane.position.y += 300;
  296. }
  297. if ( postprocessing.enabled ) {
  298. renderer.clear();
  299. // render scene into texture
  300. renderer.setRenderTarget( postprocessing.rtTextureColor );
  301. renderer.clear();
  302. renderer.render( scene, camera );
  303. // render depth into texture
  304. scene.overrideMaterial = materialDepth;
  305. renderer.setRenderTarget( postprocessing.rtTextureDepth );
  306. renderer.clear();
  307. renderer.render( scene, camera );
  308. scene.overrideMaterial = null;
  309. // render bokeh composite
  310. renderer.setRenderTarget( null );
  311. renderer.render( postprocessing.scene, postprocessing.camera );
  312. } else {
  313. scene.overrideMaterial = null;
  314. renderer.setRenderTarget( null );
  315. renderer.clear();
  316. renderer.render( scene, camera );
  317. }
  318. }
  319. </script>
  320. </body>
  321. </html>