webgl_shaders_tonemapping.html 15 KB

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