1
0

webgl_postprocessing_dof2.html 13 KB

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