webgl_shaders_tonemapping.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - adaptive tone-mapping</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. <style>
  9. #labels {
  10. position: absolute;
  11. display: grid;
  12. grid-template-columns: 1fr 1fr 1fr;
  13. justify-items: center;
  14. align-items: end;
  15. height: 100%;
  16. width: 100%;
  17. }
  18. #labels > div {
  19. background-color: black;
  20. padding: 6px;
  21. margin-bottom: 20%;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <div id="d">
  27. <div id="info">
  28. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl demo :
  29. Earth diffuse and city lights by <a href="http://seanward.org" target="_blank" rel="noopener">Sean Ward</a>
  30. </div>
  31. <div id="labels">
  32. <div>
  33. Low Dynamic Range<br/>
  34. Static Tone Mapping
  35. </div>
  36. <div>
  37. High Dynamic Range<br/>
  38. Static Tone Mapping
  39. </div>
  40. <div>
  41. High Dynamic Range<br/>
  42. Adaptive Tone Mapping
  43. </div>
  44. </div>
  45. </div>
  46. <script type="module">
  47. import * as THREE from '../build/three.module.js';
  48. import { GUI } from './jsm/libs/dat.gui.module.js';
  49. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  50. import { EffectComposer } from './jsm/postprocessing/EffectComposer.js';
  51. import { RenderPass } from './jsm/postprocessing/RenderPass.js';
  52. import { ShaderPass } from './jsm/postprocessing/ShaderPass.js';
  53. import { AdaptiveToneMappingPass } from './jsm/postprocessing/AdaptiveToneMappingPass.js';
  54. import { BloomPass } from './jsm/postprocessing/BloomPass.js';
  55. import { GammaCorrectionShader } from './jsm/shaders/GammaCorrectionShader.js';
  56. let bloomPass, adaptToneMappingPass, ldrToneMappingPass, hdrToneMappingPass;
  57. let params;
  58. let camera, scene, renderer, dynamicHdrEffectComposer, hdrEffectComposer, ldrEffectComposer;
  59. let cameraCube, sceneCube;
  60. let cameraBG, debugScene;
  61. let adaptiveLuminanceMat, currentLuminanceMat;
  62. let directionalLight;
  63. let orbitControls;
  64. let windowHalfX = window.innerWidth / 2;
  65. let windowHalfY = window.innerHeight / 2;
  66. let windowThirdX = window.innerWidth / 3;
  67. init();
  68. animate();
  69. function init() {
  70. params = {
  71. bloomAmount: 1.0,
  72. sunLight: 4.0,
  73. enabled: true,
  74. avgLuminance: 0.7,
  75. middleGrey: 0.04,
  76. maxLuminance: 16,
  77. adaptionRate: 2.0
  78. };
  79. const container = document.createElement( 'div' );
  80. document.body.appendChild( container );
  81. // CAMERAS
  82. camera = new THREE.PerspectiveCamera( 70, windowThirdX / window.innerHeight, 0.1, 100000 );
  83. camera.position.x = 700;
  84. camera.position.y = 400;
  85. camera.position.z = 800;
  86. cameraCube = new THREE.PerspectiveCamera( 70, windowThirdX / window.innerHeight, 1, 100000 );
  87. cameraBG = new THREE.OrthographicCamera( - windowHalfX, windowHalfX, windowHalfY, - windowHalfY, - 10000, 10000 );
  88. cameraBG.position.z = 100;
  89. orbitControls = new OrbitControls( camera, container );
  90. orbitControls.autoRotate = true;
  91. orbitControls.autoRotateSpeed = 1;
  92. // SCENE
  93. scene = new THREE.Scene();
  94. sceneCube = new THREE.Scene();
  95. debugScene = new THREE.Scene();
  96. // LIGHTS
  97. const ambient = new THREE.AmbientLight( 0x050505 );
  98. scene.add( ambient );
  99. directionalLight = new THREE.DirectionalLight( 0xffffff, params.sunLight );
  100. directionalLight.position.set( 2, 0, 10 ).normalize();
  101. scene.add( directionalLight );
  102. const atmoShader = {
  103. side: THREE.BackSide,
  104. // blending: THREE.AdditiveBlending,
  105. transparent: true,
  106. lights: true,
  107. uniforms: THREE.UniformsUtils.merge( [
  108. THREE.UniformsLib[ "common" ],
  109. THREE.UniformsLib[ "lights" ]
  110. ] ),
  111. vertexShader: [
  112. "varying vec3 vViewPosition;",
  113. "varying vec3 vNormal;",
  114. "void main() {",
  115. THREE.ShaderChunk[ "beginnormal_vertex" ],
  116. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  117. " vNormal = normalize( transformedNormal );",
  118. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  119. "vViewPosition = -mvPosition.xyz;",
  120. "gl_Position = projectionMatrix * mvPosition;",
  121. "}"
  122. ].join( "\n" ),
  123. fragmentShader: [
  124. THREE.ShaderChunk[ "common" ],
  125. THREE.ShaderChunk[ "bsdfs" ],
  126. THREE.ShaderChunk[ "lights_pars_begin" ],
  127. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  128. "void main() {",
  129. "vec3 normal = normalize( -vNormal );",
  130. "vec3 viewPosition = normalize( vViewPosition );",
  131. "#if NUM_DIR_LIGHTS > 0",
  132. "vec3 dirDiffuse = vec3( 0.0 );",
  133. "for( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {",
  134. "vec4 lDirection = viewMatrix * vec4( directionalLights[i].direction, 0.0 );",
  135. "vec3 dirVector = normalize( lDirection.xyz );",
  136. "float dotProduct = dot( viewPosition, dirVector );",
  137. "dotProduct = 1.0 * max( dotProduct, 0.0 ) + (1.0 - max( -dot( normal, dirVector ), 0.0 ));",
  138. "dotProduct *= dotProduct;",
  139. "dirDiffuse += max( 0.5 * dotProduct, 0.0 ) * directionalLights[i].color;",
  140. "}",
  141. "#endif",
  142. //Fade out atmosphere at edge
  143. "float viewDot = abs(dot( normal, viewPosition ));",
  144. "viewDot = clamp( pow( viewDot + 0.6, 10.0 ), 0.0, 1.0);",
  145. "vec3 color = vec3( 0.05, 0.09, 0.13 ) * dirDiffuse;",
  146. "gl_FragColor = vec4( color, viewDot );",
  147. "}"
  148. ].join( "\n" )
  149. };
  150. const earthAtmoMat = new THREE.ShaderMaterial( atmoShader );
  151. const earthMat = new THREE.MeshPhongMaterial( {
  152. color: 0xffffff,
  153. shininess: 200
  154. } );
  155. const textureLoader = new THREE.TextureLoader();
  156. textureLoader.load( 'textures/planets/earth_atmos_4096.jpg', function ( tex ) {
  157. earthMat.map = tex;
  158. earthMat.map.encoding = THREE.sRGBEncoding;
  159. earthMat.needsUpdate = true;
  160. } );
  161. textureLoader.load( 'textures/planets/earth_specular_2048.jpg', function ( tex ) {
  162. earthMat.specularMap = tex;
  163. earthMat.specularMap.encoding = THREE.sRGBEncoding;
  164. earthMat.needsUpdate = true;
  165. } );
  166. // let earthNormal = textureLoader.load( 'textures/planets/earth-new-normal-2048.jpg', function( tex ) {
  167. // earthMat.normalMap = tex;
  168. // earthMat.needsUpdate = true;
  169. // } );
  170. const earthLights = textureLoader.load( 'textures/planets/earth_lights_2048.png' );
  171. earthLights.encoding = THREE.sRGBEncoding;
  172. const earthLightsMat = new THREE.MeshBasicMaterial( {
  173. color: 0xffffff,
  174. blending: THREE.AdditiveBlending,
  175. transparent: true,
  176. depthTest: false,
  177. map: earthLights,
  178. } );
  179. const clouds = textureLoader.load( 'textures/planets/earth_clouds_2048.png' );
  180. clouds.encoding = THREE.sRGBEncoding;
  181. const earthCloudsMat = new THREE.MeshLambertMaterial( {
  182. color: 0xffffff,
  183. blending: THREE.NormalBlending,
  184. transparent: true,
  185. depthTest: false,
  186. map: clouds
  187. } );
  188. const earthGeo = new THREE.SphereGeometry( 600, 24, 24 );
  189. const sphereMesh = new THREE.Mesh( earthGeo, earthMat );
  190. scene.add( sphereMesh );
  191. const sphereLightsMesh = new THREE.Mesh( earthGeo, earthLightsMat );
  192. scene.add( sphereLightsMesh );
  193. const sphereCloudsMesh = new THREE.Mesh( earthGeo, earthCloudsMat );
  194. scene.add( sphereCloudsMesh );
  195. const sphereAtmoMesh = new THREE.Mesh( earthGeo, earthAtmoMat );
  196. sphereAtmoMesh.scale.set( 1.05, 1.05, 1.05 );
  197. scene.add( sphereAtmoMesh );
  198. const vBGShader = [
  199. // "attribute vec2 uv;",
  200. "varying vec2 vUv;",
  201. "void main() {",
  202. "vUv = uv;",
  203. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  204. "}"
  205. ].join( "\n" );
  206. const pBGShader = [
  207. "uniform sampler2D map;",
  208. "varying vec2 vUv;",
  209. "void main() {",
  210. "vec2 sampleUV = vUv;",
  211. "vec4 color = texture2D( map, sampleUV, 0.0 );",
  212. "gl_FragColor = vec4( color.xyz, 1.0 );",
  213. "}"
  214. ].join( "\n" );
  215. // Skybox
  216. adaptiveLuminanceMat = new THREE.ShaderMaterial( {
  217. uniforms: {
  218. "map": { value: null }
  219. },
  220. vertexShader: vBGShader,
  221. fragmentShader: pBGShader,
  222. depthTest: false,
  223. // color: 0xffffff
  224. blending: THREE.NoBlending
  225. } );
  226. currentLuminanceMat = new THREE.ShaderMaterial( {
  227. uniforms: {
  228. "map": { value: null }
  229. },
  230. vertexShader: vBGShader,
  231. fragmentShader: pBGShader,
  232. depthTest: false
  233. // color: 0xffffff
  234. // blending: THREE.NoBlending
  235. } );
  236. let quadBG = new THREE.Mesh( new THREE.PlaneGeometry( 0.1, 0.1 ), currentLuminanceMat );
  237. quadBG.position.z = - 500;
  238. quadBG.position.x = - window.innerWidth * 0.5 + window.innerWidth * 0.05;
  239. quadBG.scale.set( window.innerWidth, window.innerHeight, 1 );
  240. debugScene.add( quadBG );
  241. quadBG = new THREE.Mesh( new THREE.PlaneGeometry( 0.1, 0.1 ), adaptiveLuminanceMat );
  242. quadBG.position.z = - 500;
  243. quadBG.position.x = - window.innerWidth * 0.5 + window.innerWidth * 0.15;
  244. quadBG.scale.set( window.innerWidth, window.innerHeight, 1 );
  245. debugScene.add( quadBG );
  246. const r = "textures/cube/MilkyWay/";
  247. const urls = [ r + "dark-s_px.jpg", r + "dark-s_nx.jpg",
  248. r + "dark-s_py.jpg", r + "dark-s_ny.jpg",
  249. r + "dark-s_pz.jpg", r + "dark-s_nz.jpg" ];
  250. const textureCube = new THREE.CubeTextureLoader().load( urls );
  251. textureCube.encoding = THREE.sRGBEncoding;
  252. sceneCube.background = textureCube;
  253. renderer = new THREE.WebGLRenderer();
  254. renderer.setPixelRatio( window.devicePixelRatio );
  255. renderer.setSize( window.innerWidth, window.innerHeight );
  256. renderer.autoClear = false;
  257. container.appendChild( renderer.domElement );
  258. // let width = window.innerWidth || 1;
  259. const height = window.innerHeight || 1;
  260. const parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  261. const regularRenderTarget = new THREE.WebGLRenderTarget( windowThirdX, height, parameters );
  262. ldrEffectComposer = new EffectComposer( renderer, regularRenderTarget );
  263. parameters.type = THREE.FloatType;
  264. if ( renderer.capabilities.isWebGL2 === false && renderer.extensions.has( 'OES_texture_half_float_linear' ) === false ) {
  265. parameters.type = undefined; // avoid usage of floating point textures
  266. }
  267. const hdrRenderTarget = new THREE.WebGLRenderTarget( windowThirdX, height, parameters );
  268. dynamicHdrEffectComposer = new EffectComposer( renderer, hdrRenderTarget );
  269. dynamicHdrEffectComposer.setSize( window.innerWidth, window.innerHeight );
  270. hdrEffectComposer = new EffectComposer( renderer, hdrRenderTarget );
  271. const debugPass = new RenderPass( debugScene, cameraBG );
  272. debugPass.clear = false;
  273. const scenePass = new RenderPass( scene, camera, undefined, undefined, undefined );
  274. const skyboxPass = new RenderPass( sceneCube, cameraCube );
  275. scenePass.clear = false;
  276. adaptToneMappingPass = new AdaptiveToneMappingPass( true, 256 );
  277. adaptToneMappingPass.needsSwap = true;
  278. ldrToneMappingPass = new AdaptiveToneMappingPass( false, 256 );
  279. hdrToneMappingPass = new AdaptiveToneMappingPass( false, 256 );
  280. bloomPass = new BloomPass();
  281. const gammaCorrectionPass = new ShaderPass( GammaCorrectionShader );
  282. dynamicHdrEffectComposer.addPass( skyboxPass );
  283. dynamicHdrEffectComposer.addPass( scenePass );
  284. dynamicHdrEffectComposer.addPass( adaptToneMappingPass );
  285. dynamicHdrEffectComposer.addPass( bloomPass );
  286. dynamicHdrEffectComposer.addPass( gammaCorrectionPass );
  287. hdrEffectComposer.addPass( skyboxPass );
  288. hdrEffectComposer.addPass( scenePass );
  289. hdrEffectComposer.addPass( hdrToneMappingPass );
  290. hdrEffectComposer.addPass( bloomPass );
  291. hdrEffectComposer.addPass( gammaCorrectionPass );
  292. ldrEffectComposer.addPass( skyboxPass );
  293. ldrEffectComposer.addPass( scenePass );
  294. ldrEffectComposer.addPass( ldrToneMappingPass );
  295. ldrEffectComposer.addPass( bloomPass );
  296. ldrEffectComposer.addPass( gammaCorrectionPass );
  297. const gui = new GUI();
  298. const sceneGui = gui.addFolder( 'Scenes' );
  299. const toneMappingGui = gui.addFolder( 'ToneMapping' );
  300. const staticToneMappingGui = gui.addFolder( 'StaticOnly' );
  301. const adaptiveToneMappingGui = gui.addFolder( 'AdaptiveOnly' );
  302. sceneGui.add( params, 'bloomAmount', 0.0, 10.0 );
  303. sceneGui.add( params, 'sunLight', 0.1, 12.0 );
  304. toneMappingGui.add( params, 'enabled' );
  305. toneMappingGui.add( params, 'middleGrey', 0, 12 );
  306. toneMappingGui.add( params, 'maxLuminance', 1, 30 );
  307. staticToneMappingGui.add( params, 'avgLuminance', 0.001, 2.0 );
  308. adaptiveToneMappingGui.add( params, 'adaptionRate', 0.0, 10.0 );
  309. gui.open();
  310. window.addEventListener( 'resize', onWindowResize );
  311. }
  312. function onWindowResize() {
  313. windowHalfX = window.innerWidth / 2;
  314. windowHalfY = window.innerHeight / 2;
  315. windowThirdX = window.innerWidth / 3;
  316. camera.aspect = windowThirdX / window.innerHeight;
  317. camera.updateProjectionMatrix();
  318. cameraCube.aspect = windowThirdX / window.innerHeight;
  319. cameraCube.updateProjectionMatrix();
  320. renderer.setSize( window.innerWidth, window.innerHeight );
  321. }
  322. function animate() {
  323. requestAnimationFrame( animate );
  324. if ( bloomPass ) {
  325. bloomPass.copyUniforms[ "opacity" ].value = params.bloomAmount;
  326. }
  327. if ( adaptToneMappingPass ) {
  328. adaptToneMappingPass.setAdaptionRate( params.adaptionRate );
  329. adaptiveLuminanceMat.uniforms[ "map" ].value = adaptToneMappingPass.luminanceRT;
  330. currentLuminanceMat.uniforms[ "map" ].value = adaptToneMappingPass.currentLuminanceRT;
  331. adaptToneMappingPass.enabled = params.enabled;
  332. adaptToneMappingPass.setMaxLuminance( params.maxLuminance );
  333. adaptToneMappingPass.setMiddleGrey( params.middleGrey );
  334. hdrToneMappingPass.enabled = params.enabled;
  335. hdrToneMappingPass.setMaxLuminance( params.maxLuminance );
  336. hdrToneMappingPass.setMiddleGrey( params.middleGrey );
  337. if ( hdrToneMappingPass.setAverageLuminance ) {
  338. hdrToneMappingPass.setAverageLuminance( params.avgLuminance );
  339. }
  340. ldrToneMappingPass.enabled = params.enabled;
  341. ldrToneMappingPass.setMaxLuminance( params.maxLuminance );
  342. ldrToneMappingPass.setMiddleGrey( params.middleGrey );
  343. if ( ldrToneMappingPass.setAverageLuminance ) {
  344. ldrToneMappingPass.setAverageLuminance( params.avgLuminance );
  345. }
  346. }
  347. directionalLight.intensity = params.sunLight;
  348. orbitControls.update();
  349. render();
  350. }
  351. function render() {
  352. camera.lookAt( scene.position );
  353. cameraCube.rotation.copy( camera.rotation );
  354. renderer.setViewport( 0, 0, windowThirdX, window.innerHeight );
  355. ldrEffectComposer.render( 0.017 );
  356. renderer.setViewport( windowThirdX, 0, windowThirdX, window.innerHeight );
  357. hdrEffectComposer.render( 0.017 );
  358. renderer.setViewport( windowThirdX * 2, 0, windowThirdX, window.innerHeight );
  359. dynamicHdrEffectComposer.render( 0.017 );
  360. }
  361. </script>
  362. </body>
  363. </html>