webgl_postprocessing_dof2.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. <style>
  8. body {
  9. background-color: #000000;
  10. margin: 0px;
  11. overflow: hidden;
  12. font-family:Monospace;
  13. font-size:13px;
  14. text-align:center;
  15. font-weight: bold;
  16. text-align:center;
  17. }
  18. a {
  19. color:#0078ff;
  20. }
  21. #info {
  22. color:#fff;
  23. position: relative;
  24. top: 0px;
  25. width: 100em;
  26. margin: 0 auto -2.1em;
  27. padding: 5px;
  28. z-index:100;
  29. }
  30. </style>
  31. </head>
  32. <!-- TODO
  33. Setup Number Focus Test Plates
  34. Use WEBGL Depth buffer support?
  35. -->
  36. <body>
  37. <script src="../build/three.js"></script>
  38. <script src="js/shaders/BokehShader2.js"></script>
  39. <script src="js/Detector.js"></script>
  40. <script src="js/libs/stats.min.js"></script>
  41. <script src='js/libs/dat.gui.min.js'></script>
  42. <div id="info">
  43. <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl realistic depth-of-field bokeh example -
  44. shader ported from <a href="http://blenderartists.org/forum/showthread.php?237488-GLSL-depth-of-field-with-bokeh-v2-4-(update)">Martins Upitis</a>
  45. </div>
  46. <script>
  47. if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
  48. var container, stats;
  49. var camera, scene, renderer,
  50. material_depth;
  51. var windowHalfX = window.innerWidth / 2;
  52. var windowHalfY = window.innerHeight / 2;
  53. var height = window.innerHeight;
  54. var postprocessing = { enabled : true };
  55. var shaderSettings = {
  56. rings: 3,
  57. samples: 4
  58. };
  59. var singleMaterial = false;
  60. var mouse = new THREE.Vector2();
  61. var raycaster = new THREE.Raycaster();
  62. var distance = 100;
  63. var target = new THREE.Vector3( 0, 20, -50 );
  64. var effectController;
  65. var planes = [];
  66. var leaves = 100;
  67. init();
  68. animate();
  69. function init() {
  70. container = document.createElement( 'div' );
  71. document.body.appendChild( container );
  72. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / height, 1, 3000 );
  73. camera.position.y = 150;
  74. camera.position.z = 450;
  75. scene = new THREE.Scene();
  76. scene.add( camera );
  77. renderer = new THREE.WebGLRenderer();
  78. renderer.setPixelRatio( window.devicePixelRatio );
  79. renderer.setSize( window.innerWidth, height );
  80. renderer.setClearColor( 0xffffff );
  81. renderer.setClearAlpha( 1.0 );
  82. container.appendChild( renderer.domElement );
  83. material_depth = new THREE.MeshDepthMaterial();
  84. material_depth.depthPacking = THREE.RGBADepthPacking;
  85. material_depth.blending = THREE.NoBlending;
  86. //
  87. var r = "textures/cube/Bridge2/";
  88. var urls = [ r + "posx.jpg", r + "negx.jpg",
  89. r + "posy.jpg", r + "negy.jpg",
  90. r + "posz.jpg", r + "negz.jpg" ];
  91. var textureCube = new THREE.CubeTextureLoader().load( urls );
  92. textureCube.format = THREE.RGBFormat;
  93. // Skybox
  94. var shader = THREE.ShaderLib[ "cube" ];
  95. shader.uniforms[ "tCube" ].value = textureCube;
  96. var material = new THREE.ShaderMaterial( {
  97. fragmentShader: shader.fragmentShader,
  98. vertexShader: shader.vertexShader,
  99. uniforms: shader.uniforms,
  100. depthWrite: false,
  101. side: THREE.BackSide
  102. } );
  103. var mesh = new THREE.Mesh( new THREE.BoxGeometry( 1000, 1000, 1000 ), material );
  104. camera.add( mesh );
  105. // Focusing Floor
  106. // var planeGeometry = new THREE.PlaneBufferGeometry( 500, 500, 1, 1 );
  107. // var planeMat = new THREE.MeshPhongMaterial(
  108. // { map: texture }
  109. // );
  110. // var plane = new THREE.Mesh(planeGeometry, planeMat );
  111. // plane.rotation.x = - Math.PI / 2;
  112. // plane.position.y = - 5;
  113. // scene.add(plane);
  114. // Plane particles
  115. var planePiece = new THREE.PlaneBufferGeometry( 10, 10, 1, 1 );
  116. var planeMat = new THREE.MeshPhongMaterial( {
  117. color: 0xffffff * 0.4,
  118. shininess: 0.5,
  119. specular: 0xffffff,
  120. envMap: textureCube,
  121. side: THREE.DoubleSide
  122. } );
  123. var rand = Math.random;
  124. for (var i=0;i<leaves;i++) {
  125. var plane = new THREE.Mesh(planePiece, planeMat);
  126. plane.rotation.set(rand(), rand(), rand());
  127. plane.rotation.dx = rand() * 0.1;
  128. plane.rotation.dy = rand() * 0.1;
  129. plane.rotation.dz = rand() * 0.1;
  130. plane.position.set(rand() * 150, 0 + rand() * 300, rand() * 150);
  131. plane.position.dx = (rand() - 0.5 );
  132. plane.position.dz = (rand() - 0.5 );
  133. scene.add(plane);
  134. planes.push(plane);
  135. }
  136. // Adding Monkeys
  137. var loader2 = new THREE.BufferGeometryLoader();
  138. loader2.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  139. geometry.computeVertexNormals();
  140. var material = new THREE.MeshPhongMaterial( {
  141. color: 0xffffff,
  142. specular:0xffffff,
  143. envMap: textureCube,
  144. combine: THREE.MultiplyOperation,
  145. shininess: 50,
  146. reflectivity: 1.0
  147. });
  148. var monkeys = 20;
  149. for ( var i = 0; i < monkeys; i ++ ) {
  150. var mesh = new THREE.Mesh( geometry, material );
  151. mesh.scale.multiplyScalar(30);
  152. mesh.position.z = Math.cos(i / monkeys * Math.PI * 2) * 200;
  153. mesh.position.y = Math.sin(i / monkeys * Math.PI * 3) * 20;
  154. mesh.position.x = Math.sin(i / monkeys * Math.PI * 2) * 200;
  155. mesh.rotation.y = -Math.PI / 2;
  156. mesh.rotation.z = -i / monkeys * Math.PI * 2;
  157. scene.add( mesh );
  158. }
  159. } );
  160. // Add Balls
  161. var geometry = new THREE.SphereGeometry( 1, 20, 20 );
  162. for ( var i = 0; i < 20; i ++ ) {
  163. // MeshPhongMaterial
  164. var ballmaterial = new THREE.MeshPhongMaterial( {
  165. color: 0xffffff * Math.random(),
  166. shininess: 0.5,
  167. specular: 0xffffff ,
  168. envMap: textureCube } );
  169. var mesh = new THREE.Mesh( geometry, ballmaterial );
  170. mesh.position.x = ( Math.random() - 0.5 ) * 200;
  171. mesh.position.y = Math.random() * 50;
  172. mesh.position.z = ( Math.random() - 0.5 ) * 200;
  173. mesh.scale.multiplyScalar( 10 );
  174. scene.add( mesh );
  175. }
  176. // Lights
  177. scene.add( new THREE.AmbientLight( 0x222222 ) );
  178. var directionalLight = new THREE.DirectionalLight( 0xffffff, 2 );
  179. directionalLight.position.set( 2, 1.2, 10 ).normalize();
  180. scene.add( directionalLight );
  181. var directionalLight = new THREE.DirectionalLight( 0xffffff, 1 );
  182. directionalLight.position.set( -2, 1.2, -10 ).normalize();
  183. scene.add( directionalLight );
  184. initPostprocessing();
  185. renderer.autoClear = false;
  186. renderer.domElement.style.position = 'absolute';
  187. renderer.domElement.style.left = "0px";
  188. stats = new Stats();
  189. container.appendChild( stats.dom );
  190. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  191. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  192. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  193. effectController = {
  194. enabled: true,
  195. jsDepthCalculation: true,
  196. shaderFocus: false,
  197. fstop: 2.2,
  198. maxblur: 1.0,
  199. showFocus: false,
  200. focalDepth: 2.8,
  201. manualdof: false,
  202. vignetting: false,
  203. depthblur: false,
  204. threshold: 0.5,
  205. gain: 2.0,
  206. bias: 0.5,
  207. fringe: 0.7,
  208. focalLength: 35,
  209. noise: true,
  210. pentagon: false,
  211. dithering: 0.0001
  212. };
  213. var matChanger = function( ) {
  214. for (var e in effectController) {
  215. if (e in postprocessing.bokeh_uniforms)
  216. postprocessing.bokeh_uniforms[ e ].value = effectController[ e ];
  217. }
  218. postprocessing.enabled = effectController.enabled;
  219. postprocessing.bokeh_uniforms[ 'znear' ].value = camera.near;
  220. postprocessing.bokeh_uniforms[ 'zfar' ].value = camera.far;
  221. camera.setFocalLength(effectController.focalLength);
  222. };
  223. var gui = new dat.GUI();
  224. gui.add( effectController, "enabled" ).onChange( matChanger );
  225. gui.add( effectController, "jsDepthCalculation" ).onChange( matChanger );
  226. gui.add( effectController, "shaderFocus" ).onChange( matChanger );
  227. gui.add( effectController, "focalDepth", 0.0, 200.0 ).listen().onChange( matChanger );
  228. gui.add( effectController, "fstop", 0.1, 22, 0.001 ).onChange( matChanger );
  229. gui.add( effectController, "maxblur", 0.0, 5.0, 0.025 ).onChange( matChanger );
  230. gui.add( effectController, "showFocus" ).onChange( matChanger );
  231. gui.add( effectController, "manualdof" ).onChange( matChanger );
  232. gui.add( effectController, "vignetting" ).onChange( matChanger );
  233. gui.add( effectController, "depthblur" ).onChange( matChanger );
  234. gui.add( effectController, "threshold", 0, 1, 0.001 ).onChange( matChanger );
  235. gui.add( effectController, "gain", 0, 100, 0.001 ).onChange( matChanger );
  236. gui.add( effectController, "bias", 0,3, 0.001 ).onChange( matChanger );
  237. gui.add( effectController, "fringe", 0, 5, 0.001 ).onChange( matChanger );
  238. gui.add( effectController, "focalLength", 16, 80, 0.001 ).onChange( matChanger );
  239. gui.add( effectController, "noise" ).onChange( matChanger );
  240. gui.add( effectController, "dithering", 0, 0.001, 0.0001 ).onChange( matChanger );
  241. gui.add( effectController, "pentagon" ).onChange( matChanger );
  242. gui.add( shaderSettings, "rings", 1, 8).step(1).onChange( shaderUpdate );
  243. gui.add( shaderSettings, "samples", 1, 13).step(1).onChange( shaderUpdate );
  244. matChanger();
  245. window.addEventListener( 'resize', onWindowResize, false );
  246. }
  247. function onWindowResize() {
  248. camera.aspect = window.innerWidth / window.innerHeight;
  249. camera.updateProjectionMatrix();
  250. renderer.setSize( window.innerWidth, window.innerHeight );
  251. }
  252. function onDocumentMouseMove( event ) {
  253. mouse.x = ( event.clientX - windowHalfX ) / windowHalfX;
  254. mouse.y = - ( event.clientY - windowHalfY ) / windowHalfY;
  255. postprocessing.bokeh_uniforms[ 'focusCoords' ].value.set(event.clientX / window.innerWidth, 1-(event.clientY / window.innerHeight));
  256. }
  257. function onDocumentTouchStart( event ) {
  258. if ( event.touches.length == 1 ) {
  259. event.preventDefault();
  260. mouse.x = ( event.touches[ 0 ].pageX - windowHalfX ) / windowHalfX;
  261. mouse.y = - ( event.touches[ 0 ].pageY - windowHalfY ) / windowHalfY;
  262. }
  263. }
  264. function onDocumentTouchMove( event ) {
  265. if ( event.touches.length == 1 ) {
  266. event.preventDefault();
  267. mouse.x = ( event.touches[ 0 ].pageX - windowHalfX ) / windowHalfX;
  268. mouse.y = - ( event.touches[ 0 ].pageY - windowHalfY ) / windowHalfY;
  269. }
  270. }
  271. function initPostprocessing() {
  272. postprocessing.scene = new THREE.Scene();
  273. postprocessing.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, -10000, 10000 );
  274. postprocessing.camera.position.z = 100;
  275. postprocessing.scene.add( postprocessing.camera );
  276. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };
  277. postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, height, pars );
  278. postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, height, pars );
  279. var bokeh_shader = THREE.BokehShader;
  280. postprocessing.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );
  281. postprocessing.bokeh_uniforms[ "tColor" ].value = postprocessing.rtTextureColor.texture;
  282. postprocessing.bokeh_uniforms[ "tDepth" ].value = postprocessing.rtTextureDepth.texture;
  283. postprocessing.bokeh_uniforms[ "textureWidth" ].value = window.innerWidth;
  284. postprocessing.bokeh_uniforms[ "textureHeight" ].value = height;
  285. postprocessing.materialBokeh = new THREE.ShaderMaterial( {
  286. uniforms: postprocessing.bokeh_uniforms,
  287. vertexShader: bokeh_shader.vertexShader,
  288. fragmentShader: bokeh_shader.fragmentShader,
  289. defines: {
  290. RINGS: shaderSettings.rings,
  291. SAMPLES: shaderSettings.samples,
  292. DEPTH_PACKING: 1 // RGBADepth
  293. }
  294. } );
  295. postprocessing.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( window.innerWidth, window.innerHeight ), postprocessing.materialBokeh );
  296. postprocessing.quad.position.z = - 500;
  297. postprocessing.scene.add( postprocessing.quad );
  298. }
  299. function shaderUpdate() {
  300. postprocessing.materialBokeh.defines.RINGS = shaderSettings.rings;
  301. postprocessing.materialBokeh.defines.SAMPLES = shaderSettings.samples;
  302. postprocessing.materialBokeh.needsUpdate = true;
  303. }
  304. function animate() {
  305. requestAnimationFrame( animate, renderer.domElement );
  306. render();
  307. stats.update();
  308. }
  309. function linearize(depth) {
  310. var zfar = camera.far;
  311. var znear = camera.near;
  312. return -zfar * znear / (depth * (zfar - znear) - zfar);
  313. }
  314. function smoothstep(near, far, depth) {
  315. var x = saturate( (depth - near) / (far - near));
  316. return x * x * (3- 2*x);
  317. }
  318. function saturate(x) {
  319. return Math.max(0, Math.min(1, x));
  320. }
  321. function render() {
  322. var time = Date.now() * 0.00015;
  323. camera.position.x = Math.cos(time) * 400;
  324. camera.position.z = Math.sin(time) * 500;
  325. camera.position.y = Math.sin(time / 1.4) * 100;
  326. camera.lookAt( target );
  327. camera.updateMatrixWorld();
  328. if ( effectController.jsDepthCalculation ) {
  329. raycaster.setFromCamera( mouse, camera );
  330. var intersects = raycaster.intersectObjects( scene.children, true );
  331. if ( intersects.length > 0 ) {
  332. var targetDistance = intersects[ 0 ].distance;
  333. distance += (targetDistance - distance) * 0.03;
  334. var sdistance = smoothstep(camera.near, camera.far, distance);
  335. var ldistance = linearize(1 - sdistance);
  336. // (Math.random() < 0.1) && console.log('moo', targetDistance, distance, ldistance);
  337. postprocessing.bokeh_uniforms[ 'focalDepth' ].value = ldistance;
  338. effectController['focalDepth'] = ldistance;
  339. }
  340. }
  341. for (var i=0;i<leaves;i++) {
  342. var plane = planes[i];
  343. plane.rotation.x += plane.rotation.dx;
  344. plane.rotation.y += plane.rotation.dy;
  345. plane.rotation.z += plane.rotation.dz;
  346. plane.position.y -= 2;
  347. plane.position.x += plane.position.dx;
  348. plane.position.z += plane.position.dz;
  349. if (plane.position.y < 0) plane.position.y += 300;
  350. }
  351. if ( postprocessing.enabled ) {
  352. renderer.clear();
  353. // Render scene into texture
  354. renderer.render( scene, camera, postprocessing.rtTextureColor, true );
  355. // Render depth into texture
  356. scene.overrideMaterial = material_depth;
  357. renderer.render( scene, camera, postprocessing.rtTextureDepth, true );
  358. scene.overrideMaterial = null;
  359. // Render bokeh composite
  360. renderer.render( postprocessing.scene, postprocessing.camera );
  361. } else {
  362. scene.overrideMaterial = null;
  363. renderer.clear();
  364. renderer.render( scene, camera );
  365. }
  366. }
  367. </script>
  368. </body>
  369. </html>