webgl_postprocessing_dof2.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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.autoClear = false;
  60. container.appendChild( renderer.domElement );
  61. const depthShader = BokehDepthShader;
  62. materialDepth = new THREE.ShaderMaterial( {
  63. uniforms: depthShader.uniforms,
  64. vertexShader: depthShader.vertexShader,
  65. fragmentShader: depthShader.fragmentShader
  66. } );
  67. materialDepth.uniforms[ 'mNear' ].value = camera.near;
  68. materialDepth.uniforms[ 'mFar' ].value = camera.far;
  69. // skybox
  70. const r = 'textures/cube/Bridge2/';
  71. const urls = [ r + 'posx.jpg', r + 'negx.jpg',
  72. r + 'posy.jpg', r + 'negy.jpg',
  73. r + 'posz.jpg', r + 'negz.jpg' ];
  74. const textureCube = new THREE.CubeTextureLoader().load( urls );
  75. scene.background = textureCube;
  76. // plane particles
  77. const planePiece = new THREE.PlaneGeometry( 10, 10, 1, 1 );
  78. const planeMat = new THREE.MeshPhongMaterial( {
  79. color: 0xffffff * 0.4,
  80. shininess: 0.5,
  81. specular: 0xffffff,
  82. envMap: textureCube,
  83. side: THREE.DoubleSide
  84. } );
  85. const rand = Math.random;
  86. for ( let i = 0; i < leaves; i ++ ) {
  87. const plane = new THREE.Mesh( planePiece, planeMat );
  88. plane.rotation.set( rand(), rand(), rand() );
  89. plane.rotation.dx = rand() * 0.1;
  90. plane.rotation.dy = rand() * 0.1;
  91. plane.rotation.dz = rand() * 0.1;
  92. plane.position.set( rand() * 150, 0 + rand() * 300, rand() * 150 );
  93. plane.position.dx = ( rand() - 0.5 );
  94. plane.position.dz = ( rand() - 0.5 );
  95. scene.add( plane );
  96. planes.push( plane );
  97. }
  98. // adding Monkeys
  99. const loader2 = new THREE.BufferGeometryLoader();
  100. loader2.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  101. geometry.computeVertexNormals();
  102. const material = new THREE.MeshPhongMaterial( {
  103. specular: 0xffffff,
  104. envMap: textureCube,
  105. shininess: 50,
  106. reflectivity: 1.0,
  107. flatShading: true
  108. } );
  109. const monkeys = 20;
  110. for ( let i = 0; i < monkeys; i ++ ) {
  111. const mesh = new THREE.Mesh( geometry, material );
  112. mesh.position.z = Math.cos( i / monkeys * Math.PI * 2 ) * 200;
  113. mesh.position.y = Math.sin( i / monkeys * Math.PI * 3 ) * 20;
  114. mesh.position.x = Math.sin( i / monkeys * Math.PI * 2 ) * 200;
  115. mesh.rotation.y = i / monkeys * Math.PI * 2;
  116. mesh.scale.setScalar( 30 );
  117. scene.add( mesh );
  118. }
  119. } );
  120. // add balls
  121. const geometry = new THREE.SphereGeometry( 1, 20, 20 );
  122. for ( let i = 0; i < 20; i ++ ) {
  123. const ballmaterial = new THREE.MeshPhongMaterial( {
  124. color: 0xffffff * Math.random(),
  125. shininess: 0.5,
  126. specular: 0xffffff,
  127. envMap: textureCube } );
  128. const mesh = new THREE.Mesh( geometry, ballmaterial );
  129. mesh.position.x = ( Math.random() - 0.5 ) * 200;
  130. mesh.position.y = Math.random() * 50;
  131. mesh.position.z = ( Math.random() - 0.5 ) * 200;
  132. mesh.scale.multiplyScalar( 10 );
  133. scene.add( mesh );
  134. }
  135. // lights
  136. scene.add( new THREE.AmbientLight( 0x222222 ) );
  137. const directionalLight1 = new THREE.DirectionalLight( 0xffffff, 2 );
  138. directionalLight1.position.set( 2, 1.2, 10 ).normalize();
  139. scene.add( directionalLight1 );
  140. const directionalLight2 = new THREE.DirectionalLight( 0xffffff, 1 );
  141. directionalLight2.position.set( - 2, 1.2, - 10 ).normalize();
  142. scene.add( directionalLight2 );
  143. initPostprocessing();
  144. stats = new Stats();
  145. container.appendChild( stats.dom );
  146. container.style.touchAction = 'none';
  147. container.addEventListener( 'pointermove', onPointerMove );
  148. effectController = {
  149. enabled: true,
  150. jsDepthCalculation: true,
  151. shaderFocus: false,
  152. fstop: 2.2,
  153. maxblur: 1.0,
  154. showFocus: false,
  155. focalDepth: 2.8,
  156. manualdof: false,
  157. vignetting: false,
  158. depthblur: false,
  159. threshold: 0.5,
  160. gain: 2.0,
  161. bias: 0.5,
  162. fringe: 0.7,
  163. focalLength: 35,
  164. noise: true,
  165. pentagon: false,
  166. dithering: 0.0001
  167. };
  168. const matChanger = function () {
  169. for ( const e in effectController ) {
  170. if ( e in postprocessing.bokeh_uniforms ) {
  171. postprocessing.bokeh_uniforms[ e ].value = effectController[ e ];
  172. }
  173. }
  174. postprocessing.enabled = effectController.enabled;
  175. postprocessing.bokeh_uniforms[ 'znear' ].value = camera.near;
  176. postprocessing.bokeh_uniforms[ 'zfar' ].value = camera.far;
  177. camera.setFocalLength( effectController.focalLength );
  178. };
  179. const gui = new GUI();
  180. gui.add( effectController, 'enabled' ).onChange( matChanger );
  181. gui.add( effectController, 'jsDepthCalculation' ).onChange( matChanger );
  182. gui.add( effectController, 'shaderFocus' ).onChange( matChanger );
  183. gui.add( effectController, 'focalDepth', 0.0, 200.0 ).listen().onChange( matChanger );
  184. gui.add( effectController, 'fstop', 0.1, 22, 0.001 ).onChange( matChanger );
  185. gui.add( effectController, 'maxblur', 0.0, 5.0, 0.025 ).onChange( matChanger );
  186. gui.add( effectController, 'showFocus' ).onChange( matChanger );
  187. gui.add( effectController, 'manualdof' ).onChange( matChanger );
  188. gui.add( effectController, 'vignetting' ).onChange( matChanger );
  189. gui.add( effectController, 'depthblur' ).onChange( matChanger );
  190. gui.add( effectController, 'threshold', 0, 1, 0.001 ).onChange( matChanger );
  191. gui.add( effectController, 'gain', 0, 100, 0.001 ).onChange( matChanger );
  192. gui.add( effectController, 'bias', 0, 3, 0.001 ).onChange( matChanger );
  193. gui.add( effectController, 'fringe', 0, 5, 0.001 ).onChange( matChanger );
  194. gui.add( effectController, 'focalLength', 16, 80, 0.001 ).onChange( matChanger );
  195. gui.add( effectController, 'noise' ).onChange( matChanger );
  196. gui.add( effectController, 'dithering', 0, 0.001, 0.0001 ).onChange( matChanger );
  197. gui.add( effectController, 'pentagon' ).onChange( matChanger );
  198. gui.add( shaderSettings, 'rings', 1, 8 ).step( 1 ).onChange( shaderUpdate );
  199. gui.add( shaderSettings, 'samples', 1, 13 ).step( 1 ).onChange( shaderUpdate );
  200. matChanger();
  201. window.addEventListener( 'resize', onWindowResize );
  202. }
  203. function onWindowResize() {
  204. camera.aspect = window.innerWidth / window.innerHeight;
  205. camera.updateProjectionMatrix();
  206. windowHalfX = window.innerWidth / 2;
  207. windowHalfY = window.innerHeight / 2;
  208. postprocessing.rtTextureDepth.setSize( window.innerWidth, window.innerHeight );
  209. postprocessing.rtTextureColor.setSize( window.innerWidth, window.innerHeight );
  210. postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth;
  211. postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight;
  212. renderer.setSize( window.innerWidth, window.innerHeight );
  213. }
  214. function onPointerMove( event ) {
  215. if ( event.isPrimary === false ) return;
  216. mouse.x = ( event.clientX - windowHalfX ) / windowHalfX;
  217. mouse.y = - ( event.clientY - windowHalfY ) / windowHalfY;
  218. postprocessing.bokeh_uniforms[ 'focusCoords' ].value.set( event.clientX / window.innerWidth, 1 - ( event.clientY / window.innerHeight ) );
  219. }
  220. function initPostprocessing() {
  221. postprocessing.scene = new THREE.Scene();
  222. postprocessing.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 );
  223. postprocessing.camera.position.z = 100;
  224. postprocessing.scene.add( postprocessing.camera );
  225. postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
  226. postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
  227. const bokeh_shader = BokehShader;
  228. postprocessing.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );
  229. postprocessing.bokeh_uniforms[ 'tColor' ].value = postprocessing.rtTextureColor.texture;
  230. postprocessing.bokeh_uniforms[ 'tDepth' ].value = postprocessing.rtTextureDepth.texture;
  231. postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth;
  232. postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight;
  233. postprocessing.materialBokeh = new THREE.ShaderMaterial( {
  234. uniforms: postprocessing.bokeh_uniforms,
  235. vertexShader: bokeh_shader.vertexShader,
  236. fragmentShader: bokeh_shader.fragmentShader,
  237. defines: {
  238. RINGS: shaderSettings.rings,
  239. SAMPLES: shaderSettings.samples
  240. }
  241. } );
  242. postprocessing.quad = new THREE.Mesh( new THREE.PlaneGeometry( window.innerWidth, window.innerHeight ), postprocessing.materialBokeh );
  243. postprocessing.quad.position.z = - 500;
  244. postprocessing.scene.add( postprocessing.quad );
  245. }
  246. function shaderUpdate() {
  247. postprocessing.materialBokeh.defines.RINGS = shaderSettings.rings;
  248. postprocessing.materialBokeh.defines.SAMPLES = shaderSettings.samples;
  249. postprocessing.materialBokeh.needsUpdate = true;
  250. }
  251. function animate() {
  252. requestAnimationFrame( animate, renderer.domElement );
  253. render();
  254. stats.update();
  255. }
  256. function linearize( depth ) {
  257. const zfar = camera.far;
  258. const znear = camera.near;
  259. return - zfar * znear / ( depth * ( zfar - znear ) - zfar );
  260. }
  261. function smoothstep( near, far, depth ) {
  262. const x = saturate( ( depth - near ) / ( far - near ) );
  263. return x * x * ( 3 - 2 * x );
  264. }
  265. function saturate( x ) {
  266. return Math.max( 0, Math.min( 1, x ) );
  267. }
  268. function render() {
  269. const time = Date.now() * 0.00015;
  270. camera.position.x = Math.cos( time ) * 400;
  271. camera.position.z = Math.sin( time ) * 500;
  272. camera.position.y = Math.sin( time / 1.4 ) * 100;
  273. camera.lookAt( target );
  274. camera.updateMatrixWorld();
  275. if ( effectController.jsDepthCalculation ) {
  276. raycaster.setFromCamera( mouse, camera );
  277. const intersects = raycaster.intersectObjects( scene.children, true );
  278. const targetDistance = ( intersects.length > 0 ) ? intersects[ 0 ].distance : 1000;
  279. distance += ( targetDistance - distance ) * 0.03;
  280. const sdistance = smoothstep( camera.near, camera.far, distance );
  281. const ldistance = linearize( 1 - sdistance );
  282. postprocessing.bokeh_uniforms[ 'focalDepth' ].value = ldistance;
  283. effectController[ 'focalDepth' ] = ldistance;
  284. }
  285. for ( let i = 0; i < leaves; i ++ ) {
  286. const plane = planes[ i ];
  287. plane.rotation.x += plane.rotation.dx;
  288. plane.rotation.y += plane.rotation.dy;
  289. plane.rotation.z += plane.rotation.dz;
  290. plane.position.y -= 2;
  291. plane.position.x += plane.position.dx;
  292. plane.position.z += plane.position.dz;
  293. if ( plane.position.y < 0 ) plane.position.y += 300;
  294. }
  295. if ( postprocessing.enabled ) {
  296. renderer.clear();
  297. // render scene into texture
  298. renderer.setRenderTarget( postprocessing.rtTextureColor );
  299. renderer.clear();
  300. renderer.render( scene, camera );
  301. // render depth into texture
  302. scene.overrideMaterial = materialDepth;
  303. renderer.setRenderTarget( postprocessing.rtTextureDepth );
  304. renderer.clear();
  305. renderer.render( scene, camera );
  306. scene.overrideMaterial = null;
  307. // render bokeh composite
  308. renderer.setRenderTarget( null );
  309. renderer.render( postprocessing.scene, postprocessing.camera );
  310. } else {
  311. scene.overrideMaterial = null;
  312. renderer.setRenderTarget( null );
  313. renderer.clear();
  314. renderer.render( scene, camera );
  315. }
  316. }
  317. </script>
  318. </body>
  319. </html>