webgl_shaders_tonemapping.html 15 KB

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