threejs-load-gltf-shadows.html 12 KB

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