webgl_postprocessing_godrays.html 14 KB

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