load-gltf-shadows.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Load .GLTF - Shadows</title>
  8. <style>
  9. html, body {
  10. margin: 0;
  11. height: 100%;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../../build/three.module.js"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import {OrbitControls} from '../../examples/jsm/controls/OrbitControls.js';
  36. import {GLTFLoader} from '../../examples/jsm/loaders/GLTFLoader.js';
  37. import {GUI} from '../../examples/jsm/libs/lil-gui.module.min.js';
  38. function main() {
  39. const canvas = document.querySelector('#c');
  40. const renderer = new THREE.WebGLRenderer({canvas});
  41. renderer.outputEncoding = THREE.sRGBEncoding;
  42. renderer.shadowMap.enabled = true;
  43. const fov = 45;
  44. const aspect = 2; // the canvas default
  45. const near = 0.1;
  46. const far = 100;
  47. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  48. camera.position.set(0, 10, 20);
  49. const controls = new OrbitControls(camera, canvas);
  50. controls.target.set(0, 5, 0);
  51. controls.update();
  52. const scene = new THREE.Scene();
  53. scene.background = new THREE.Color('#DEFEFF');
  54. {
  55. const planeSize = 40;
  56. const loader = new THREE.TextureLoader();
  57. const texture = loader.load('resources/images/checker.png');
  58. texture.wrapS = THREE.RepeatWrapping;
  59. texture.wrapT = THREE.RepeatWrapping;
  60. texture.magFilter = THREE.NearestFilter;
  61. const repeats = planeSize / 2;
  62. texture.repeat.set(repeats, repeats);
  63. const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
  64. const planeMat = new THREE.MeshPhongMaterial({
  65. map: texture,
  66. side: THREE.DoubleSide,
  67. });
  68. const mesh = new THREE.Mesh(planeGeo, planeMat);
  69. mesh.rotation.x = Math.PI * -.5;
  70. scene.add(mesh);
  71. }
  72. {
  73. const skyColor = 0xB1E1FF; // light blue
  74. const groundColor = 0xB97A20; // brownish orange
  75. const intensity = 0.6;
  76. const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
  77. scene.add(light);
  78. }
  79. {
  80. const color = 0xFFFFFF;
  81. const intensity = 0.8;
  82. const light = new THREE.DirectionalLight(color, intensity);
  83. light.castShadow = true;
  84. light.position.set(-250, 800, -850);
  85. light.target.position.set(-550, 40, -450);
  86. light.shadow.bias = -0.004;
  87. light.shadow.mapSize.width = 2048;
  88. light.shadow.mapSize.height = 2048;
  89. scene.add(light);
  90. scene.add(light.target);
  91. const cam = light.shadow.camera;
  92. cam.near = 1;
  93. cam.far = 2000;
  94. cam.left = -1500;
  95. cam.right = 1500;
  96. cam.top = 1500;
  97. cam.bottom = -1500;
  98. const cameraHelper = new THREE.CameraHelper(cam);
  99. scene.add(cameraHelper);
  100. cameraHelper.visible = false;
  101. const helper = new THREE.DirectionalLightHelper(light, 100);
  102. scene.add(helper);
  103. helper.visible = false;
  104. function makeXYZGUI(gui, vector3, name, onChangeFn) {
  105. const folder = gui.addFolder(name);
  106. folder.add(vector3, 'x', vector3.x - 500, vector3.x + 500).onChange(onChangeFn);
  107. folder.add(vector3, 'y', vector3.y - 500, vector3.y + 500).onChange(onChangeFn);
  108. folder.add(vector3, 'z', vector3.z - 500, vector3.z + 500).onChange(onChangeFn);
  109. folder.open();
  110. }
  111. function updateCamera() {
  112. // update the light target's matrixWorld because it's needed by the helper
  113. light.updateMatrixWorld();
  114. light.target.updateMatrixWorld();
  115. helper.update();
  116. // update the light's shadow camera's projection matrix
  117. light.shadow.camera.updateProjectionMatrix();
  118. // and now update the camera helper we're using to show the light's shadow camera
  119. cameraHelper.update();
  120. }
  121. updateCamera();
  122. class DimensionGUIHelper {
  123. constructor(obj, minProp, maxProp) {
  124. this.obj = obj;
  125. this.minProp = minProp;
  126. this.maxProp = maxProp;
  127. }
  128. get value() {
  129. return this.obj[this.maxProp] * 2;
  130. }
  131. set value(v) {
  132. this.obj[this.maxProp] = v / 2;
  133. this.obj[this.minProp] = v / -2;
  134. }
  135. }
  136. class MinMaxGUIHelper {
  137. constructor(obj, minProp, maxProp, minDif) {
  138. this.obj = obj;
  139. this.minProp = minProp;
  140. this.maxProp = maxProp;
  141. this.minDif = minDif;
  142. }
  143. get min() {
  144. return this.obj[this.minProp];
  145. }
  146. set min(v) {
  147. this.obj[this.minProp] = v;
  148. this.obj[this.maxProp] = Math.max(this.obj[this.maxProp], v + this.minDif);
  149. }
  150. get max() {
  151. return this.obj[this.maxProp];
  152. }
  153. set max(v) {
  154. this.obj[this.maxProp] = v;
  155. this.min = this.min; // this will call the min setter
  156. }
  157. }
  158. class VisibleGUIHelper {
  159. constructor(...objects) {
  160. this.objects = [...objects];
  161. }
  162. get value() {
  163. return this.objects[0].visible;
  164. }
  165. set value(v) {
  166. this.objects.forEach((obj) => {
  167. obj.visible = v;
  168. });
  169. }
  170. }
  171. const gui = new GUI();
  172. gui.close();
  173. gui.add(new VisibleGUIHelper(helper, cameraHelper), 'value').name('show helpers');
  174. gui.add(light.shadow, 'bias', -0.1, 0.1, 0.001);
  175. {
  176. const folder = gui.addFolder('Shadow Camera');
  177. folder.open();
  178. folder.add(new DimensionGUIHelper(light.shadow.camera, 'left', 'right'), 'value', 1, 4000)
  179. .name('width')
  180. .onChange(updateCamera);
  181. folder.add(new DimensionGUIHelper(light.shadow.camera, 'bottom', 'top'), 'value', 1, 4000 )
  182. .name('height')
  183. .onChange(updateCamera);
  184. const minMaxGUIHelper = new MinMaxGUIHelper(light.shadow.camera, 'near', 'far', 0.1);
  185. folder.add(minMaxGUIHelper, 'min', 1, 1000, 1).name('near').onChange(updateCamera);
  186. folder.add(minMaxGUIHelper, 'max', 1, 4000, 1).name('far').onChange(updateCamera);
  187. folder.add(light.shadow.camera, 'zoom', 0.01, 1.5, 0.01).onChange(updateCamera);
  188. }
  189. makeXYZGUI(gui, light.position, 'position', updateCamera);
  190. makeXYZGUI(gui, light.target.position, 'target', updateCamera);
  191. }
  192. function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
  193. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  194. const halfFovY = THREE.MathUtils.degToRad(camera.fov * .5);
  195. const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
  196. // compute a unit vector that points in the direction the camera is now
  197. // in the xz plane from the center of the box
  198. const direction = (new THREE.Vector3())
  199. .subVectors(camera.position, boxCenter)
  200. .multiply(new THREE.Vector3(1, 0, 1))
  201. .normalize();
  202. // move the camera to a position distance units way from the center
  203. // in whatever direction the camera was from the center already
  204. camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));
  205. // pick some near and far values for the frustum that
  206. // will contain the box.
  207. camera.near = boxSize / 100;
  208. camera.far = boxSize * 100;
  209. camera.updateProjectionMatrix();
  210. // point the camera to look at the center of the box
  211. camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
  212. }
  213. let curve;
  214. let curveObject;
  215. {
  216. const controlPoints = [
  217. [1.118281, 5.115846, -3.681386],
  218. [3.948875, 5.115846, -3.641834],
  219. [3.960072, 5.115846, -0.240352],
  220. [3.985447, 5.115846, 4.585005],
  221. [-3.793631, 5.115846, 4.585006],
  222. [-3.826839, 5.115846, -14.736200],
  223. [-14.542292, 5.115846, -14.765865],
  224. [-14.520929, 5.115846, -3.627002],
  225. [-5.452815, 5.115846, -3.634418],
  226. [-5.467251, 5.115846, 4.549161],
  227. [-13.266233, 5.115846, 4.567083],
  228. [-13.250067, 5.115846, -13.499271],
  229. [4.081842, 5.115846, -13.435463],
  230. [4.125436, 5.115846, -5.334928],
  231. [-14.521364, 5.115846, -5.239871],
  232. [-14.510466, 5.115846, 5.486727],
  233. [5.745666, 5.115846, 5.510492],
  234. [5.787942, 5.115846, -14.728308],
  235. [-5.423720, 5.115846, -14.761919],
  236. [-5.373599, 5.115846, -3.704133],
  237. [1.004861, 5.115846, -3.641834],
  238. ];
  239. const p0 = new THREE.Vector3();
  240. const p1 = new THREE.Vector3();
  241. curve = new THREE.CatmullRomCurve3(
  242. controlPoints.map((p, ndx) => {
  243. p0.set(...p);
  244. p1.set(...controlPoints[(ndx + 1) % controlPoints.length]);
  245. return [
  246. (new THREE.Vector3()).copy(p0),
  247. (new THREE.Vector3()).lerpVectors(p0, p1, 0.1),
  248. (new THREE.Vector3()).lerpVectors(p0, p1, 0.9),
  249. ];
  250. }).flat(),
  251. true,
  252. );
  253. {
  254. const points = curve.getPoints(250);
  255. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  256. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  257. curveObject = new THREE.Line(geometry, material);
  258. curveObject.scale.set(100, 100, 100);
  259. curveObject.position.y = -621;
  260. curveObject.visible = false;
  261. scene.add(curveObject);
  262. }
  263. }
  264. const cars = [];
  265. {
  266. const gltfLoader = new GLTFLoader();
  267. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
  268. const root = gltf.scene;
  269. scene.add(root);
  270. root.traverse((obj) => {
  271. if (obj.castShadow !== undefined) {
  272. obj.castShadow = true;
  273. obj.receiveShadow = true;
  274. }
  275. });
  276. const loadedCars = root.getObjectByName('Cars');
  277. const fixes = [
  278. { prefix: 'Car_08', y: 0, rot: [Math.PI * .5, 0, Math.PI * .5], },
  279. { prefix: 'CAR_03', y: 33, rot: [0, Math.PI, 0], },
  280. { prefix: 'Car_04', y: 40, rot: [0, Math.PI, 0], },
  281. ];
  282. root.updateMatrixWorld();
  283. for (const car of loadedCars.children.slice()) {
  284. const fix = fixes.find(fix => car.name.startsWith(fix.prefix));
  285. const obj = new THREE.Object3D();
  286. car.position.set(0, fix.y, 0);
  287. car.rotation.set(...fix.rot);
  288. obj.add(car);
  289. scene.add(obj);
  290. cars.push(obj);
  291. }
  292. // compute the box that contains all the stuff
  293. // from root and below
  294. const box = new THREE.Box3().setFromObject(root);
  295. const boxSize = box.getSize(new THREE.Vector3()).length();
  296. const boxCenter = box.getCenter(new THREE.Vector3());
  297. // set the camera to frame the box
  298. frameArea(boxSize * 0.5, boxSize, boxCenter, camera);
  299. // update the Trackball controls to handle the new size
  300. controls.maxDistance = boxSize * 10;
  301. controls.target.copy(boxCenter);
  302. controls.update();
  303. });
  304. }
  305. function resizeRendererToDisplaySize(renderer) {
  306. const canvas = renderer.domElement;
  307. const width = canvas.clientWidth;
  308. const height = canvas.clientHeight;
  309. const needResize = canvas.width !== width || canvas.height !== height;
  310. if (needResize) {
  311. renderer.setSize(width, height, false);
  312. }
  313. return needResize;
  314. }
  315. // create 2 Vector3s we can use for path calculations
  316. const carPosition = new THREE.Vector3();
  317. const carTarget = new THREE.Vector3();
  318. function render(time) {
  319. time *= 0.001; // convert to seconds
  320. if (resizeRendererToDisplaySize(renderer)) {
  321. const canvas = renderer.domElement;
  322. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  323. camera.updateProjectionMatrix();
  324. }
  325. {
  326. const pathTime = time * .01;
  327. const targetOffset = 0.01;
  328. cars.forEach((car, ndx) => {
  329. // a number between 0 and 1 to evenly space the cars
  330. const u = pathTime + ndx / cars.length;
  331. // get the first point
  332. curve.getPointAt(u % 1, carPosition);
  333. carPosition.applyMatrix4(curveObject.matrixWorld);
  334. // get a second point slightly further down the curve
  335. curve.getPointAt((u + targetOffset) % 1, carTarget);
  336. carTarget.applyMatrix4(curveObject.matrixWorld);
  337. // put the car at the first point (temporarily)
  338. car.position.copy(carPosition);
  339. // point the car the second point
  340. car.lookAt(carTarget);
  341. // put the car between the 2 points
  342. car.position.lerpVectors(carPosition, carTarget, 0.5);
  343. });
  344. }
  345. renderer.render(scene, camera);
  346. requestAnimationFrame(render);
  347. }
  348. requestAnimationFrame(render);
  349. }
  350. main();
  351. </script>
  352. </html>