webgl_postprocessing_dof2.html 13 KB

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