2
0

webgl_shaders_tonemapping.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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/lil-gui.module.min.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[ "normal_pars_fragment" ],
  128. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  129. "void main() {",
  130. "vec3 normal = normalize( -vNormal );",
  131. "vec3 viewPosition = normalize( vViewPosition );",
  132. "#if NUM_DIR_LIGHTS > 0",
  133. "vec3 dirDiffuse = vec3( 0.0 );",
  134. "for( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {",
  135. "vec4 lDirection = viewMatrix * vec4( directionalLights[i].direction, 0.0 );",
  136. "vec3 dirVector = normalize( lDirection.xyz );",
  137. "float dotProduct = dot( viewPosition, dirVector );",
  138. "dotProduct = 1.0 * max( dotProduct, 0.0 ) + (1.0 - max( -dot( normal, dirVector ), 0.0 ));",
  139. "dotProduct *= dotProduct;",
  140. "dirDiffuse += max( 0.5 * dotProduct, 0.0 ) * directionalLights[i].color;",
  141. "}",
  142. "#endif",
  143. //Fade out atmosphere at edge
  144. "float viewDot = abs(dot( normal, viewPosition ));",
  145. "viewDot = clamp( pow( viewDot + 0.6, 10.0 ), 0.0, 1.0);",
  146. "vec3 color = vec3( 0.05, 0.09, 0.13 ) * dirDiffuse;",
  147. "gl_FragColor = vec4( color, viewDot );",
  148. "}"
  149. ].join( "\n" )
  150. };
  151. const earthAtmoMat = new THREE.ShaderMaterial( atmoShader );
  152. const earthMat = new THREE.MeshPhongMaterial( {
  153. color: 0xffffff,
  154. shininess: 200
  155. } );
  156. const textureLoader = new THREE.TextureLoader();
  157. textureLoader.load( 'textures/planets/earth_atmos_4096.jpg', function ( tex ) {
  158. earthMat.map = tex;
  159. earthMat.map.encoding = THREE.sRGBEncoding;
  160. earthMat.needsUpdate = true;
  161. } );
  162. textureLoader.load( 'textures/planets/earth_specular_2048.jpg', function ( tex ) {
  163. earthMat.specularMap = tex;
  164. earthMat.specularMap.encoding = THREE.sRGBEncoding;
  165. earthMat.needsUpdate = true;
  166. } );
  167. // let earthNormal = textureLoader.load( 'textures/planets/earth-new-normal-2048.jpg', function( tex ) {
  168. // earthMat.normalMap = tex;
  169. // earthMat.needsUpdate = true;
  170. // } );
  171. const earthLights = textureLoader.load( 'textures/planets/earth_lights_2048.png' );
  172. earthLights.encoding = THREE.sRGBEncoding;
  173. const earthLightsMat = new THREE.MeshBasicMaterial( {
  174. color: 0xffffff,
  175. blending: THREE.AdditiveBlending,
  176. transparent: true,
  177. depthTest: false,
  178. map: earthLights,
  179. } );
  180. const clouds = textureLoader.load( 'textures/planets/earth_clouds_2048.png' );
  181. clouds.encoding = THREE.sRGBEncoding;
  182. const earthCloudsMat = new THREE.MeshLambertMaterial( {
  183. color: 0xffffff,
  184. blending: THREE.NormalBlending,
  185. transparent: true,
  186. depthTest: false,
  187. map: clouds
  188. } );
  189. const earthGeo = new THREE.SphereGeometry( 600, 24, 24 );
  190. const sphereMesh = new THREE.Mesh( earthGeo, earthMat );
  191. scene.add( sphereMesh );
  192. const sphereLightsMesh = new THREE.Mesh( earthGeo, earthLightsMat );
  193. scene.add( sphereLightsMesh );
  194. const sphereCloudsMesh = new THREE.Mesh( earthGeo, earthCloudsMat );
  195. scene.add( sphereCloudsMesh );
  196. const sphereAtmoMesh = new THREE.Mesh( earthGeo, earthAtmoMat );
  197. sphereAtmoMesh.scale.set( 1.05, 1.05, 1.05 );
  198. scene.add( sphereAtmoMesh );
  199. const vBGShader = [
  200. // "attribute vec2 uv;",
  201. "varying vec2 vUv;",
  202. "void main() {",
  203. "vUv = uv;",
  204. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  205. "}"
  206. ].join( "\n" );
  207. const pBGShader = [
  208. "uniform sampler2D map;",
  209. "varying vec2 vUv;",
  210. "void main() {",
  211. "vec2 sampleUV = vUv;",
  212. "vec4 color = texture2D( map, sampleUV, 0.0 );",
  213. "gl_FragColor = vec4( color.xyz, 1.0 );",
  214. "}"
  215. ].join( "\n" );
  216. // Skybox
  217. adaptiveLuminanceMat = new THREE.ShaderMaterial( {
  218. uniforms: {
  219. "map": { value: null }
  220. },
  221. vertexShader: vBGShader,
  222. fragmentShader: pBGShader,
  223. depthTest: false,
  224. // color: 0xffffff
  225. blending: THREE.NoBlending
  226. } );
  227. currentLuminanceMat = 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. let quadBG = new THREE.Mesh( new THREE.PlaneGeometry( 0.1, 0.1 ), currentLuminanceMat );
  238. quadBG.position.z = - 500;
  239. quadBG.position.x = - window.innerWidth * 0.5 + window.innerWidth * 0.05;
  240. quadBG.scale.set( window.innerWidth, window.innerHeight, 1 );
  241. debugScene.add( quadBG );
  242. quadBG = new THREE.Mesh( new THREE.PlaneGeometry( 0.1, 0.1 ), adaptiveLuminanceMat );
  243. quadBG.position.z = - 500;
  244. quadBG.position.x = - window.innerWidth * 0.5 + window.innerWidth * 0.15;
  245. quadBG.scale.set( window.innerWidth, window.innerHeight, 1 );
  246. debugScene.add( quadBG );
  247. const r = "textures/cube/MilkyWay/";
  248. const urls = [ r + "dark-s_px.jpg", r + "dark-s_nx.jpg",
  249. r + "dark-s_py.jpg", r + "dark-s_ny.jpg",
  250. r + "dark-s_pz.jpg", r + "dark-s_nz.jpg" ];
  251. const textureCube = new THREE.CubeTextureLoader().load( urls );
  252. textureCube.encoding = THREE.sRGBEncoding;
  253. sceneCube.background = textureCube;
  254. renderer = new THREE.WebGLRenderer();
  255. renderer.setPixelRatio( window.devicePixelRatio );
  256. renderer.setSize( window.innerWidth, window.innerHeight );
  257. renderer.autoClear = false;
  258. container.appendChild( renderer.domElement );
  259. // let width = window.innerWidth || 1;
  260. const height = window.innerHeight || 1;
  261. const parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  262. const regularRenderTarget = new THREE.WebGLRenderTarget( windowThirdX, height, parameters );
  263. ldrEffectComposer = new EffectComposer( renderer, regularRenderTarget );
  264. parameters.type = THREE.FloatType;
  265. if ( renderer.capabilities.isWebGL2 === false && renderer.extensions.has( 'OES_texture_half_float_linear' ) === false ) {
  266. parameters.type = undefined; // avoid usage of floating point textures
  267. }
  268. const hdrRenderTarget = new THREE.WebGLRenderTarget( windowThirdX, height, parameters );
  269. dynamicHdrEffectComposer = new EffectComposer( renderer, hdrRenderTarget );
  270. dynamicHdrEffectComposer.setSize( window.innerWidth, window.innerHeight );
  271. hdrEffectComposer = new EffectComposer( renderer, hdrRenderTarget );
  272. const debugPass = new RenderPass( debugScene, cameraBG );
  273. debugPass.clear = false;
  274. const scenePass = new RenderPass( scene, camera, undefined, undefined, undefined );
  275. const skyboxPass = new RenderPass( sceneCube, cameraCube );
  276. scenePass.clear = false;
  277. adaptToneMappingPass = new AdaptiveToneMappingPass( true, 256 );
  278. adaptToneMappingPass.needsSwap = true;
  279. ldrToneMappingPass = new AdaptiveToneMappingPass( false, 256 );
  280. hdrToneMappingPass = new AdaptiveToneMappingPass( false, 256 );
  281. bloomPass = new BloomPass();
  282. const gammaCorrectionPass = new ShaderPass( GammaCorrectionShader );
  283. dynamicHdrEffectComposer.addPass( skyboxPass );
  284. dynamicHdrEffectComposer.addPass( scenePass );
  285. dynamicHdrEffectComposer.addPass( adaptToneMappingPass );
  286. dynamicHdrEffectComposer.addPass( bloomPass );
  287. dynamicHdrEffectComposer.addPass( gammaCorrectionPass );
  288. hdrEffectComposer.addPass( skyboxPass );
  289. hdrEffectComposer.addPass( scenePass );
  290. hdrEffectComposer.addPass( hdrToneMappingPass );
  291. hdrEffectComposer.addPass( bloomPass );
  292. hdrEffectComposer.addPass( gammaCorrectionPass );
  293. ldrEffectComposer.addPass( skyboxPass );
  294. ldrEffectComposer.addPass( scenePass );
  295. ldrEffectComposer.addPass( ldrToneMappingPass );
  296. ldrEffectComposer.addPass( bloomPass );
  297. ldrEffectComposer.addPass( gammaCorrectionPass );
  298. const gui = new GUI();
  299. const sceneGui = gui.addFolder( 'Scenes' );
  300. const toneMappingGui = gui.addFolder( 'ToneMapping' );
  301. const staticToneMappingGui = gui.addFolder( 'StaticOnly' );
  302. const adaptiveToneMappingGui = gui.addFolder( 'AdaptiveOnly' );
  303. sceneGui.add( params, 'bloomAmount', 0.0, 10.0 );
  304. sceneGui.add( params, 'sunLight', 0.1, 12.0 );
  305. toneMappingGui.add( params, 'enabled' );
  306. toneMappingGui.add( params, 'middleGrey', 0, 12 );
  307. toneMappingGui.add( params, 'maxLuminance', 1, 30 );
  308. staticToneMappingGui.add( params, 'avgLuminance', 0.001, 2.0 );
  309. adaptiveToneMappingGui.add( params, 'adaptionRate', 0.0, 10.0 );
  310. gui.open();
  311. window.addEventListener( 'resize', onWindowResize );
  312. }
  313. function onWindowResize() {
  314. windowHalfX = window.innerWidth / 2;
  315. windowHalfY = window.innerHeight / 2;
  316. windowThirdX = window.innerWidth / 3;
  317. camera.aspect = windowThirdX / window.innerHeight;
  318. camera.updateProjectionMatrix();
  319. cameraCube.aspect = windowThirdX / window.innerHeight;
  320. cameraCube.updateProjectionMatrix();
  321. renderer.setSize( window.innerWidth, window.innerHeight );
  322. }
  323. function animate() {
  324. requestAnimationFrame( animate );
  325. if ( bloomPass ) {
  326. bloomPass.copyUniforms[ "opacity" ].value = params.bloomAmount;
  327. }
  328. if ( adaptToneMappingPass ) {
  329. adaptToneMappingPass.setAdaptionRate( params.adaptionRate );
  330. adaptiveLuminanceMat.uniforms[ "map" ].value = adaptToneMappingPass.luminanceRT;
  331. currentLuminanceMat.uniforms[ "map" ].value = adaptToneMappingPass.currentLuminanceRT;
  332. adaptToneMappingPass.enabled = params.enabled;
  333. adaptToneMappingPass.setMaxLuminance( params.maxLuminance );
  334. adaptToneMappingPass.setMiddleGrey( params.middleGrey );
  335. hdrToneMappingPass.enabled = params.enabled;
  336. hdrToneMappingPass.setMaxLuminance( params.maxLuminance );
  337. hdrToneMappingPass.setMiddleGrey( params.middleGrey );
  338. if ( hdrToneMappingPass.setAverageLuminance ) {
  339. hdrToneMappingPass.setAverageLuminance( params.avgLuminance );
  340. }
  341. ldrToneMappingPass.enabled = params.enabled;
  342. ldrToneMappingPass.setMaxLuminance( params.maxLuminance );
  343. ldrToneMappingPass.setMiddleGrey( params.middleGrey );
  344. if ( ldrToneMappingPass.setAverageLuminance ) {
  345. ldrToneMappingPass.setAverageLuminance( params.avgLuminance );
  346. }
  347. }
  348. directionalLight.intensity = params.sunLight;
  349. orbitControls.update();
  350. render();
  351. }
  352. function render() {
  353. camera.lookAt( scene.position );
  354. cameraCube.rotation.copy( camera.rotation );
  355. renderer.setViewport( 0, 0, windowThirdX, window.innerHeight );
  356. ldrEffectComposer.render( 0.017 );
  357. renderer.setViewport( windowThirdX, 0, windowThirdX, window.innerHeight );
  358. hdrEffectComposer.render( 0.017 );
  359. renderer.setViewport( windowThirdX * 2, 0, windowThirdX, window.innerHeight );
  360. dynamicHdrEffectComposer.render( 0.017 );
  361. }
  362. </script>
  363. </body>
  364. </html>