webgl_lightprobes_sponza.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - light probe volume (Sponza)</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. <meta property="og:title" content="three.js webgl - light probe volume (Sponza)">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_lightprobes_sponza.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_lightprobes_sponza.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - light probe volume (Sponza)<br/>
  16. WASD to move, mouse to look
  17. </div>
  18. <progress id="progressBar" value="0" max="100" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)"></progress>
  19. <script type="importmap">
  20. {
  21. "imports": {
  22. "three": "../build/three.module.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three';
  29. import { FirstPersonControls } from 'three/addons/controls/FirstPersonControls.js';
  30. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  31. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  32. import { Sky } from 'three/addons/objects/Sky.js';
  33. import { LightProbeGrid } from 'three/addons/lighting/LightProbeGrid.js';
  34. import { LightProbeGridHelper } from 'three/addons/helpers/LightProbeGridHelper.js';
  35. const MODEL_INDEX_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/model-index.json';
  36. const SAMPLE_ASSETS_BASE_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/';
  37. let camera, scene, renderer, controls, timer;
  38. let probes = null, probesHelper = null;
  39. let modelSize = null;
  40. let dirLight = null, sky = null;
  41. const sun = new THREE.Vector3();
  42. const _box = new THREE.Box3();
  43. const _size = new THREE.Vector3();
  44. const _center = new THREE.Vector3();
  45. init();
  46. async function init() {
  47. timer = new THREE.Timer();
  48. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 1000 );
  49. camera.position.set( - 10.25, 4.99, 0.40 );
  50. camera.rotation.set( 1.6505, - 1.5008, 1.6507 );
  51. scene = new THREE.Scene();
  52. sky = new Sky();
  53. sky.scale.setScalar( 450000 );
  54. scene.add( sky );
  55. const skyUniforms = sky.material.uniforms;
  56. skyUniforms[ 'turbidity' ].value = 10;
  57. skyUniforms[ 'rayleigh' ].value = 2;
  58. skyUniforms[ 'mieCoefficient' ].value = 0.005;
  59. skyUniforms[ 'mieDirectionalG' ].value = 0.8;
  60. renderer = new THREE.WebGLRenderer( { antialias: true } );
  61. renderer.setPixelRatio( Math.min( window.devicePixelRatio, 1.5 ) );
  62. renderer.setSize( window.innerWidth, window.innerHeight );
  63. renderer.setAnimationLoop( animate );
  64. renderer.shadowMap.enabled = true;
  65. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  66. renderer.toneMappingExposure = 1.0;
  67. document.body.appendChild( renderer.domElement );
  68. controls = new FirstPersonControls( camera, renderer.domElement );
  69. controls.movementSpeed = 2.0;
  70. controls.lookSpeed = 0.16;
  71. const progressBar = document.getElementById( 'progressBar' );
  72. const manager = new THREE.LoadingManager();
  73. manager.onProgress = function ( url, loaded, total ) {
  74. progressBar.value = loaded / total * 100;
  75. };
  76. manager.onLoad = function () {
  77. progressBar.remove();
  78. };
  79. const loader = new GLTFLoader( manager );
  80. const modelURL = await getSponzaModelURL();
  81. const gltf = await loader.loadAsync( modelURL );
  82. const model = gltf.scene;
  83. const embeddedLights = [];
  84. model.traverse( ( child ) => {
  85. if ( child.isMesh ) {
  86. child.castShadow = true;
  87. child.receiveShadow = true;
  88. } else if ( child.isLight ) {
  89. embeddedLights.push( child );
  90. }
  91. } );
  92. for ( const light of embeddedLights ) {
  93. if ( light.parent ) light.parent.remove( light );
  94. }
  95. scene.add( model );
  96. _box.setFromObject( model );
  97. modelSize = _box.getSize( _size ).clone();
  98. const modelCenter = _box.getCenter( _center ).clone();
  99. const targetY = modelCenter.y + modelSize.y * 0.2;
  100. const lightBaseDistance = Math.max( modelSize.x, modelSize.z );
  101. const probeFar = Math.max( modelSize.x, modelSize.y, modelSize.z ) * 2.0;
  102. let rebakeTimer = null;
  103. let isBaking = false;
  104. let bakeQueued = false;
  105. dirLight = new THREE.DirectionalLight( 0xfff2dc, 100.0 );
  106. dirLight.target.position.set( modelCenter.x, targetY, modelCenter.z );
  107. scene.add( dirLight.target );
  108. dirLight.castShadow = true;
  109. dirLight.shadow.mapSize.setScalar( 2048 );
  110. const shadowExtent = Math.max( modelSize.x, modelSize.z ) * 0.7;
  111. dirLight.shadow.camera.left = - shadowExtent;
  112. dirLight.shadow.camera.right = shadowExtent;
  113. dirLight.shadow.camera.top = shadowExtent;
  114. dirLight.shadow.camera.bottom = - shadowExtent;
  115. dirLight.shadow.camera.near = 0.1;
  116. dirLight.shadow.camera.far = modelSize.y * 4.0;
  117. scene.add( dirLight );
  118. const params = {
  119. enabled: true,
  120. showProbes: false,
  121. probeSize: 0.2,
  122. boundsX: - 0.5,
  123. boundsY: 6,
  124. boundsZ: - 0.3,
  125. sizeX: 21,
  126. sizeY: 11,
  127. sizeZ: 9,
  128. countX: 10,
  129. countY: 7,
  130. countZ: 7,
  131. bounces: 1,
  132. lightAzimuth: - 45,
  133. lightElevation: 55,
  134. lightIntensity: 100.0,
  135. shadows: true
  136. };
  137. function updateLightPosition() {
  138. const azimuth = THREE.MathUtils.degToRad( params.lightAzimuth );
  139. const elevation = THREE.MathUtils.degToRad( params.lightElevation );
  140. const radius = lightBaseDistance;
  141. const horizontal = Math.cos( elevation ) * radius;
  142. const vertical = Math.sin( elevation ) * radius;
  143. dirLight.position.set(
  144. modelCenter.x + Math.cos( azimuth ) * horizontal,
  145. targetY + vertical,
  146. modelCenter.z + Math.sin( azimuth ) * horizontal
  147. );
  148. dirLight.target.position.set( modelCenter.x, targetY, modelCenter.z );
  149. dirLight.target.updateMatrixWorld();
  150. const phi = THREE.MathUtils.degToRad( 90 - params.lightElevation );
  151. const theta = THREE.MathUtils.degToRad( params.lightAzimuth );
  152. sun.setFromSphericalCoords( 1, phi, theta );
  153. sky.material.uniforms[ 'sunPosition' ].value.copy( sun );
  154. }
  155. function scheduleRebake() {
  156. if ( rebakeTimer !== null ) clearTimeout( rebakeTimer );
  157. rebakeTimer = setTimeout( () => {
  158. rebakeTimer = null;
  159. bakeWithSettings();
  160. }, 250 );
  161. }
  162. async function bakeWithSettings() {
  163. if ( isBaking ) {
  164. bakeQueued = true;
  165. return;
  166. }
  167. isBaking = true;
  168. do {
  169. bakeQueued = false;
  170. if ( probes ) {
  171. scene.remove( probes );
  172. probes.dispose();
  173. }
  174. probes = new LightProbeGrid(
  175. params.sizeX, params.sizeY, params.sizeZ,
  176. params.countX, params.countY, params.countZ
  177. );
  178. probes.position.set( params.boundsX, params.boundsY, params.boundsZ );
  179. // Add to the scene before baking so bounce passes can sample the prior pass's atlas.
  180. scene.add( probes );
  181. // Hide the helper spheres so they don't appear in the cubemap captures.
  182. if ( probesHelper ) probesHelper.visible = false;
  183. probes.bake( renderer, scene, {
  184. cubemapSize: 32,
  185. near: 0.05,
  186. far: probeFar,
  187. bounces: params.bounces
  188. } );
  189. probes.visible = params.enabled;
  190. if ( ! probesHelper ) {
  191. probesHelper = new LightProbeGridHelper( probes, params.probeSize );
  192. probesHelper.visible = params.showProbes;
  193. scene.add( probesHelper );
  194. } else {
  195. probesHelper.probes = probes;
  196. probesHelper.update();
  197. probesHelper.visible = params.showProbes;
  198. }
  199. } while ( bakeQueued );
  200. isBaking = false;
  201. }
  202. updateLightPosition();
  203. const gui = new GUI();
  204. gui.add( params, 'enabled' ).name( 'GI' ).onChange( ( value ) => {
  205. if ( probes ) probes.visible = value;
  206. } );
  207. gui.add( params, 'lightAzimuth', - 180, 180, 1 ).name( 'Light Azimuth' ).onChange( () => {
  208. updateLightPosition();
  209. scheduleRebake();
  210. } );
  211. gui.add( params, 'lightElevation', 5, 85, 1 ).name( 'Light Elevation' ).onChange( () => {
  212. updateLightPosition();
  213. scheduleRebake();
  214. } );
  215. gui.add( params, 'lightIntensity', 0, 100, 0.1 ).name( 'Light Intensity' ).onChange( ( value ) => {
  216. dirLight.intensity = value;
  217. scheduleRebake();
  218. } );
  219. gui.add( params, 'shadows' ).name( 'Shadows' ).onChange( ( value ) => {
  220. setShadowsEnabled( value );
  221. scheduleRebake();
  222. } );
  223. gui.add( params, 'countX', 2, 32, 1 ).name( 'Probes X' ).onChange( scheduleRebake );
  224. gui.add( params, 'countY', 2, 16, 1 ).name( 'Probes Y' ).onChange( scheduleRebake );
  225. gui.add( params, 'countZ', 2, 16, 1 ).name( 'Probes Z' ).onChange( scheduleRebake );
  226. gui.add( params, 'bounces', 0, 2, 1 ).name( 'Bounces' ).onChange( scheduleRebake );
  227. gui.add( params, 'showProbes' ).name( 'Show Probes' ).onChange( ( value ) => {
  228. if ( probesHelper ) probesHelper.visible = value;
  229. } );
  230. gui.add( params, 'probeSize', 0.05, 2.0, 0.05 ).name( 'Probe Size' ).onChange( ( value ) => {
  231. if ( probesHelper ) {
  232. scene.remove( probesHelper );
  233. probesHelper.dispose();
  234. probesHelper = new LightProbeGridHelper( probes, value );
  235. probesHelper.visible = params.showProbes;
  236. scene.add( probesHelper );
  237. }
  238. } );
  239. gui.add( { log: () => {
  240. console.log( 'position:', camera.position.x.toFixed( 2 ), camera.position.y.toFixed( 2 ), camera.position.z.toFixed( 2 ) );
  241. console.log( 'rotation:', camera.rotation.x.toFixed( 4 ), camera.rotation.y.toFixed( 4 ), camera.rotation.z.toFixed( 4 ) );
  242. } }, 'log' ).name( 'Log Camera' );
  243. setShadowsEnabled( params.shadows );
  244. await bakeWithSettings();
  245. window.addEventListener( 'resize', onWindowResize );
  246. }
  247. async function getSponzaModelURL() {
  248. const response = await fetch( MODEL_INDEX_URL );
  249. const models = await response.json();
  250. const sponzaInfo = models.find( ( model ) => model.name === 'Sponza' );
  251. if ( ! sponzaInfo ) {
  252. throw new Error( 'Sponza entry was not found in the glTF sample model index.' );
  253. }
  254. const variants = sponzaInfo.variants || {};
  255. const variantName = variants[ 'glTF-Binary' ] || variants[ 'glTF' ] || variants[ 'glTF-Embedded' ] || Object.values( variants )[ 0 ];
  256. if ( ! variantName ) {
  257. throw new Error( 'Sponza has no supported glTF variant in the model index.' );
  258. }
  259. const variantFolder = variantName.endsWith( '.glb' ) ? 'glTF-Binary' : 'glTF';
  260. return `${ SAMPLE_ASSETS_BASE_URL }${ sponzaInfo.name }/${ variantFolder }/${ variantName }`;
  261. }
  262. function setShadowsEnabled( enabled ) {
  263. if ( ! renderer || ! dirLight ) return;
  264. renderer.shadowMap.enabled = enabled;
  265. dirLight.castShadow = enabled;
  266. }
  267. function onWindowResize() {
  268. camera.aspect = window.innerWidth / window.innerHeight;
  269. camera.updateProjectionMatrix();
  270. renderer.setSize( window.innerWidth, window.innerHeight );
  271. }
  272. function animate( timestamp ) {
  273. timer.update( timestamp );
  274. controls.update( timer.getDelta() );
  275. renderer.render( scene, camera );
  276. }
  277. </script>
  278. </body>
  279. </html>
粤ICP备19079148号