webgl_postprocessing_godrays.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - postprocessing - godrays</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 god-rays example - tree by <a href="http://www.turbosquid.com/3d-models/free-tree-3d-model/592617" target="_blank" rel="noopener">stanloshka</a>
  12. </div>
  13. <script type="module">
  14. import * as THREE from '../build/three.module.js';
  15. import Stats from './jsm/libs/stats.module.js';
  16. import { OBJLoader } from './jsm/loaders/OBJLoader.js';
  17. import { GodRaysFakeSunShader, GodRaysDepthMaskShader, GodRaysCombineShader, GodRaysGenerateShader } from './jsm/shaders/GodRaysShader.js';
  18. var container, stats;
  19. var camera, scene, renderer, materialDepth;
  20. var sphereMesh;
  21. var sunPosition = new THREE.Vector3( 0, 1000, - 1000 );
  22. var screenSpacePosition = new THREE.Vector3();
  23. var mouseX = 0, mouseY = 0;
  24. var postprocessing = { enabled: true };
  25. var orbitRadius = 200;
  26. var bgColor = 0x000511;
  27. var sunColor = 0xffee00;
  28. // Use a smaller size for some of the god-ray render targets for better performance.
  29. var godrayRenderTargetResolutionMultiplier = 1.0 / 4.0;
  30. init();
  31. animate();
  32. function init() {
  33. container = document.createElement( 'div' );
  34. document.body.appendChild( container );
  35. //
  36. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 3000 );
  37. camera.position.z = 200;
  38. scene = new THREE.Scene();
  39. //
  40. materialDepth = new THREE.MeshDepthMaterial();
  41. var materialScene = new THREE.MeshBasicMaterial( { color: 0x000000 } );
  42. // tree
  43. var loader = new OBJLoader();
  44. loader.load( 'models/obj/tree.obj', function ( object ) {
  45. object.material = materialScene;
  46. object.position.set( 0, - 150, - 150 );
  47. object.scale.multiplyScalar( 400 );
  48. scene.add( object );
  49. } );
  50. // sphere
  51. var geo = new THREE.SphereBufferGeometry( 1, 20, 10 );
  52. sphereMesh = new THREE.Mesh( geo, materialScene );
  53. sphereMesh.scale.multiplyScalar( 20 );
  54. scene.add( sphereMesh );
  55. //
  56. renderer = new THREE.WebGLRenderer();
  57. renderer.setClearColor( 0xffffff );
  58. renderer.setPixelRatio( window.devicePixelRatio );
  59. renderer.setSize( window.innerWidth, window.innerHeight );
  60. container.appendChild( renderer.domElement );
  61. renderer.autoClear = false;
  62. //
  63. stats = new Stats();
  64. container.appendChild( stats.dom );
  65. //
  66. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  67. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  68. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  69. window.addEventListener( 'resize', onWindowResize, false );
  70. //
  71. initPostprocessing( window.innerWidth, window.innerHeight );
  72. }
  73. //
  74. function onDocumentMouseMove( event ) {
  75. mouseX = event.clientX - window.innerWidth / 2;
  76. mouseY = event.clientY - window.innerHeight / 2;
  77. }
  78. function onDocumentTouchStart( event ) {
  79. if ( event.touches.length === 1 ) {
  80. event.preventDefault();
  81. mouseX = event.touches[ 0 ].pageX - window.innerWidth / 2;
  82. mouseY = event.touches[ 0 ].pageY - window.innerHeight / 2;
  83. }
  84. }
  85. function onDocumentTouchMove( event ) {
  86. if ( event.touches.length === 1 ) {
  87. event.preventDefault();
  88. mouseX = event.touches[ 0 ].pageX - window.innerWidth / 2;
  89. mouseY = event.touches[ 0 ].pageY - window.innerHeight / 2;
  90. }
  91. }
  92. //
  93. function onWindowResize() {
  94. var renderTargetWidth = window.innerWidth;
  95. var renderTargetHeight = window.innerHeight;
  96. camera.aspect = renderTargetWidth / renderTargetHeight;
  97. camera.updateProjectionMatrix();
  98. renderer.setSize( renderTargetWidth, renderTargetHeight );
  99. postprocessing.rtTextureColors.setSize( renderTargetWidth, renderTargetHeight );
  100. postprocessing.rtTextureDepth.setSize( renderTargetWidth, renderTargetHeight );
  101. postprocessing.rtTextureDepthMask.setSize( renderTargetWidth, renderTargetHeight );
  102. var adjustedWidth = renderTargetWidth * godrayRenderTargetResolutionMultiplier;
  103. var adjustedHeight = renderTargetHeight * godrayRenderTargetResolutionMultiplier;
  104. postprocessing.rtTextureGodRays1.setSize( adjustedWidth, adjustedHeight );
  105. postprocessing.rtTextureGodRays2.setSize( adjustedWidth, adjustedHeight );
  106. }
  107. function initPostprocessing( renderTargetWidth, renderTargetHeight ) {
  108. postprocessing.scene = new THREE.Scene();
  109. postprocessing.camera = new THREE.OrthographicCamera( - 0.5, 0.5, 0.5, - 0.5, - 10000, 10000 );
  110. postprocessing.camera.position.z = 100;
  111. postprocessing.scene.add( postprocessing.camera );
  112. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };
  113. postprocessing.rtTextureColors = new THREE.WebGLRenderTarget( renderTargetWidth, renderTargetHeight, pars );
  114. // Switching the depth formats to luminance from rgb doesn't seem to work. I didn't
  115. // investigate further for now.
  116. // pars.format = LuminanceFormat;
  117. // I would have this quarter size and use it as one of the ping-pong render
  118. // targets but the aliasing causes some temporal flickering
  119. postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( renderTargetWidth, renderTargetHeight, pars );
  120. postprocessing.rtTextureDepthMask = new THREE.WebGLRenderTarget( renderTargetWidth, renderTargetHeight, pars );
  121. // The ping-pong render targets can use an adjusted resolution to minimize cost
  122. var adjustedWidth = renderTargetWidth * godrayRenderTargetResolutionMultiplier;
  123. var adjustedHeight = renderTargetHeight * godrayRenderTargetResolutionMultiplier;
  124. postprocessing.rtTextureGodRays1 = new THREE.WebGLRenderTarget( adjustedWidth, adjustedHeight, pars );
  125. postprocessing.rtTextureGodRays2 = new THREE.WebGLRenderTarget( adjustedWidth, adjustedHeight, pars );
  126. // god-ray shaders
  127. var godraysMaskShader = GodRaysDepthMaskShader;
  128. postprocessing.godrayMaskUniforms = THREE.UniformsUtils.clone( godraysMaskShader.uniforms );
  129. postprocessing.materialGodraysDepthMask = new THREE.ShaderMaterial( {
  130. uniforms: postprocessing.godrayMaskUniforms,
  131. vertexShader: godraysMaskShader.vertexShader,
  132. fragmentShader: godraysMaskShader.fragmentShader
  133. } );
  134. var godraysGenShader = GodRaysGenerateShader;
  135. postprocessing.godrayGenUniforms = THREE.UniformsUtils.clone( godraysGenShader.uniforms );
  136. postprocessing.materialGodraysGenerate = new THREE.ShaderMaterial( {
  137. uniforms: postprocessing.godrayGenUniforms,
  138. vertexShader: godraysGenShader.vertexShader,
  139. fragmentShader: godraysGenShader.fragmentShader
  140. } );
  141. var godraysCombineShader = GodRaysCombineShader;
  142. postprocessing.godrayCombineUniforms = THREE.UniformsUtils.clone( godraysCombineShader.uniforms );
  143. postprocessing.materialGodraysCombine = new THREE.ShaderMaterial( {
  144. uniforms: postprocessing.godrayCombineUniforms,
  145. vertexShader: godraysCombineShader.vertexShader,
  146. fragmentShader: godraysCombineShader.fragmentShader
  147. } );
  148. var godraysFakeSunShader = GodRaysFakeSunShader;
  149. postprocessing.godraysFakeSunUniforms = THREE.UniformsUtils.clone( godraysFakeSunShader.uniforms );
  150. postprocessing.materialGodraysFakeSun = new THREE.ShaderMaterial( {
  151. uniforms: postprocessing.godraysFakeSunUniforms,
  152. vertexShader: godraysFakeSunShader.vertexShader,
  153. fragmentShader: godraysFakeSunShader.fragmentShader
  154. } );
  155. postprocessing.godraysFakeSunUniforms.bgColor.value.setHex( bgColor );
  156. postprocessing.godraysFakeSunUniforms.sunColor.value.setHex( sunColor );
  157. postprocessing.godrayCombineUniforms.fGodRayIntensity.value = 0.75;
  158. postprocessing.quad = new THREE.Mesh(
  159. new THREE.PlaneBufferGeometry( 1.0, 1.0 ),
  160. postprocessing.materialGodraysGenerate
  161. );
  162. postprocessing.quad.position.z = - 9900;
  163. postprocessing.scene.add( postprocessing.quad );
  164. }
  165. function animate() {
  166. requestAnimationFrame( animate, renderer.domElement );
  167. stats.begin();
  168. render();
  169. stats.end();
  170. }
  171. function getStepSize( filterLen, tapsPerPass, pass ) {
  172. return filterLen * Math.pow( tapsPerPass, - pass );
  173. }
  174. function filterGodRays( inputTex, renderTarget, stepSize ) {
  175. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysGenerate;
  176. postprocessing.godrayGenUniforms[ "fStepSize" ].value = stepSize;
  177. postprocessing.godrayGenUniforms[ "tInput" ].value = inputTex;
  178. renderer.setRenderTarget( renderTarget );
  179. renderer.render( postprocessing.scene, postprocessing.camera );
  180. postprocessing.scene.overrideMaterial = null;
  181. }
  182. function render() {
  183. var time = Date.now() / 4000;
  184. sphereMesh.position.x = orbitRadius * Math.cos( time );
  185. sphereMesh.position.z = orbitRadius * Math.sin( time ) - 100;
  186. camera.position.x += ( mouseX - camera.position.x ) * 0.036;
  187. camera.position.y += ( - ( mouseY ) - camera.position.y ) * 0.036;
  188. camera.lookAt( scene.position );
  189. if ( postprocessing.enabled ) {
  190. // Find the screenspace position of the sun
  191. screenSpacePosition.copy( sunPosition ).project( camera );
  192. screenSpacePosition.x = ( screenSpacePosition.x + 1 ) / 2;
  193. screenSpacePosition.y = ( screenSpacePosition.y + 1 ) / 2;
  194. // Give it to the god-ray and sun shaders
  195. postprocessing.godrayGenUniforms[ "vSunPositionScreenSpace" ].value.x = screenSpacePosition.x;
  196. postprocessing.godrayGenUniforms[ "vSunPositionScreenSpace" ].value.y = screenSpacePosition.y;
  197. postprocessing.godraysFakeSunUniforms[ "vSunPositionScreenSpace" ].value.x = screenSpacePosition.x;
  198. postprocessing.godraysFakeSunUniforms[ "vSunPositionScreenSpace" ].value.y = screenSpacePosition.y;
  199. // -- Draw sky and sun --
  200. // Clear colors and depths, will clear to sky color
  201. renderer.setRenderTarget( postprocessing.rtTextureColors );
  202. renderer.clear( true, true, false );
  203. // Sun render. Runs a shader that gives a brightness based on the screen
  204. // space distance to the sun. Not very efficient, so i make a scissor
  205. // rectangle around the suns position to avoid rendering surrounding pixels.
  206. var sunsqH = 0.74 * window.innerHeight; // 0.74 depends on extent of sun from shader
  207. var sunsqW = 0.74 * window.innerHeight; // both depend on height because sun is aspect-corrected
  208. screenSpacePosition.x *= window.innerWidth;
  209. screenSpacePosition.y *= window.innerHeight;
  210. renderer.setScissor( screenSpacePosition.x - sunsqW / 2, screenSpacePosition.y - sunsqH / 2, sunsqW, sunsqH );
  211. renderer.setScissorTest( true );
  212. postprocessing.godraysFakeSunUniforms[ "fAspect" ].value = window.innerWidth / window.innerHeight;
  213. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysFakeSun;
  214. renderer.setRenderTarget( postprocessing.rtTextureColors );
  215. renderer.render( postprocessing.scene, postprocessing.camera );
  216. renderer.setScissorTest( false );
  217. // -- Draw scene objects --
  218. // Colors
  219. scene.overrideMaterial = null;
  220. renderer.setRenderTarget( postprocessing.rtTextureColors );
  221. renderer.render( scene, camera );
  222. // Depth
  223. scene.overrideMaterial = materialDepth;
  224. renderer.setRenderTarget( postprocessing.rtTextureDepth );
  225. renderer.clear();
  226. renderer.render( scene, camera );
  227. //
  228. postprocessing.godrayMaskUniforms[ "tInput" ].value = postprocessing.rtTextureDepth.texture;
  229. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysDepthMask;
  230. renderer.setRenderTarget( postprocessing.rtTextureDepthMask );
  231. renderer.render( postprocessing.scene, postprocessing.camera );
  232. // -- Render god-rays --
  233. // Maximum length of god-rays (in texture space [0,1]X[0,1])
  234. var filterLen = 1.0;
  235. // Samples taken by filter
  236. var TAPS_PER_PASS = 6.0;
  237. // Pass order could equivalently be 3,2,1 (instead of 1,2,3), which
  238. // would start with a small filter support and grow to large. however
  239. // the large-to-small order produces less objectionable aliasing artifacts that
  240. // appear as a glimmer along the length of the beams
  241. // pass 1 - render into first ping-pong target
  242. filterGodRays( postprocessing.rtTextureDepthMask.texture, postprocessing.rtTextureGodRays2, getStepSize( filterLen, TAPS_PER_PASS, 1.0 ) );
  243. // pass 2 - render into second ping-pong target
  244. filterGodRays( postprocessing.rtTextureGodRays2.texture, postprocessing.rtTextureGodRays1, getStepSize( filterLen, TAPS_PER_PASS, 2.0 ) );
  245. // pass 3 - 1st RT
  246. filterGodRays( postprocessing.rtTextureGodRays1.texture, postprocessing.rtTextureGodRays2, getStepSize( filterLen, TAPS_PER_PASS, 3.0 ) );
  247. // final pass - composite god-rays onto colors
  248. postprocessing.godrayCombineUniforms[ "tColors" ].value = postprocessing.rtTextureColors.texture;
  249. postprocessing.godrayCombineUniforms[ "tGodRays" ].value = postprocessing.rtTextureGodRays2.texture;
  250. postprocessing.scene.overrideMaterial = postprocessing.materialGodraysCombine;
  251. renderer.setRenderTarget( null );
  252. renderer.render( postprocessing.scene, postprocessing.camera );
  253. postprocessing.scene.overrideMaterial = null;
  254. } else {
  255. renderer.setRenderTarget( null );
  256. renderer.clear();
  257. renderer.render( scene, camera );
  258. }
  259. }
  260. </script>
  261. </body>
  262. </html>