webgl_postprocessing_dof2.html 13 KB

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