webgl_postprocessing_dof2.html 13 KB

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