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