load-gltf.html 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. Title: Three.js Loading a .GLTF File
  2. Description: Loading a .GLTF File
  3. TOC: Load a .GLTF file
  4. In a previous lesson we [loaded an .OBJ file](threejs-load-obj.html). If
  5. you haven't read it you might want to check it out first.
  6. As pointed out over there the .OBJ file format is very old and fairly
  7. simple. It provides no scene graph so everything loaded is one large
  8. mesh. It was designed mostly as a simple way to pass data between
  9. 3D editors.
  10. [The gLTF format](https://github.com/KhronosGroup/glTF) is actually
  11. a format designed from the ground up for be used for displaying
  12. graphics. 3D formats can be divided into 3 or 4 basic types.
  13. * 3D Editor Formats
  14. This are formats specific to a single app. .blend (Blender), .max (3d Studio Max),
  15. .mb and .ma (Maya), etc...
  16. * Exchange formats
  17. These are formats like .OBJ, .DAE (Collada), .FBX. They are designed to help exchange
  18. information between 3D editors. As such they are usually much larger than needed with
  19. extra info used only inside 3d editors
  20. * App formats
  21. These are usually specific to certain apps, usually games.
  22. * Transmission formats
  23. gLTF might be the first true transmission format. I suppose VRML might be considered
  24. one but VRML was actually a pretty poor format.
  25. gLTF is designed to do some things well that all those other formats don't do
  26. 1. Be small for transmission
  27. For example this means much of their large data, like vertices, is stored in
  28. binary. When you download a .gLTF file that data can be uploaded to the GPU
  29. with zero processing. It's ready as is. This is in contrast to say VRML, .OBJ,
  30. or .DAE where vertices are stored as text and have to be parsed. Text vertex
  31. positions can easily be 3x to 5x larger than binary.
  32. 2. Be ready to render
  33. This again is different from other formats except maybe App formats. The data
  34. in a glTF file is mean to be rendered, not edited. Data that's not important to
  35. rendering has generally been removed. Polygons have been converted to triangles.
  36. Materials have known values that are supposed to work everywhere.
  37. gLTF was specifically designed so you should be able to download a glTF file and
  38. display it with a minimum of trouble. Let's cross our fingers that's truly the case
  39. as none of the other formats have been able to do this.
  40. I wasn't really sure what I should show. At some level loading and displaying a gLTF file
  41. is simpler than an .OBJ file. Unlike a .OBJ file materials are directly part of the format.
  42. That said I thought I should at least load one up and I think going over the issues I ran
  43. into might provide some good info.
  44. Searching the net I found [this low-poly city](https://sketchfab.com/models/edd1c604e1e045a0a2a552ddd9a293e6)
  45. by [antonmoek](https://sketchfab.com/antonmoek) which seemed like if we're lucky
  46. might make a good example.
  47. <div class="threejs_center"><img src="resources/images/cartoon_lowpoly_small_city_free_pack.jpg"></div>
  48. Starting with [an example from the .OBJ article](threejs-load-obj.html) I removed the code
  49. for loading .OBJ and replaced it with code for loading .GLTF
  50. The old .OBJ code was
  51. ```js
  52. const mtlLoader = new MTLLoader();
  53. mtlLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', (mtl) => {
  54. mtl.preload();
  55. mtl.materials.Material.side = THREE.DoubleSide;
  56. objLoader.setMaterials(mtl);
  57. objLoader.load('resources/models/windmill/windmill.obj', (event) => {
  58. const root = event.detail.loaderRootNode;
  59. scene.add(root);
  60. ...
  61. });
  62. });
  63. ```
  64. The new .GLTF code is
  65. ```js
  66. {
  67. const gltfLoader = new GLTFLoader();
  68. const url = 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf';
  69. gltfLoader.load(url, (gltf) => {
  70. const root = gltf.scene;
  71. scene.add(root);
  72. ...
  73. });
  74. ```
  75. I kept the auto framing code as before
  76. We also need to include the `GLTFLoader` and we can get rid of the `OBJLoader`.
  77. ```html
  78. -import {LoaderSupport} from './resources/threejs/r132/examples/jsm/loaders/LoaderSupport.js';
  79. -import {OBJLoader} from './resources/threejs/r132/examples/jsm/loaders/OBJLoader.js';
  80. -import {MTLLoader} from './resources/threejs/r132/examples/jsm/loaders/MTLLoader.js';
  81. +import {GLTFLoader} from './resources/threejs/r132/examples/jsm/loaders/GLTFLoader.js';
  82. ```
  83. And running that we get
  84. {{{example url="../threejs-load-gltf.html" }}}
  85. Magic! It just works, textures and all.
  86. Next I wanted to see if I could animate the cars driving around so
  87. I needed to check if the scene had the cars as separate entities
  88. and if they were setup in a way I could use them.
  89. I wrote some code to dump put the scenegraph to the [JavaScript
  90. console](threejs-debugging-javascript.html).
  91. Here's the code to print out the scenegraph.
  92. ```js
  93. function dumpObject(obj, lines = [], isLast = true, prefix = '') {
  94. const localPrefix = isLast ? '└─' : '├─';
  95. lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  96. const newPrefix = prefix + (isLast ? ' ' : '│ ');
  97. const lastNdx = obj.children.length - 1;
  98. obj.children.forEach((child, ndx) => {
  99. const isLast = ndx === lastNdx;
  100. dumpObject(child, lines, isLast, newPrefix);
  101. });
  102. return lines;
  103. }
  104. ```
  105. And I just called it right after loading the scene.
  106. ```js
  107. const gltfLoader = new GLTFLoader();
  108. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
  109. const root = gltf.scene;
  110. scene.add(root);
  111. console.log(dumpObject(root).join('\n'));
  112. ```
  113. [Running that](../threejs-load-gltf-dump-scenegraph.html) I got this listing
  114. ```text
  115. OSG_Scene [Scene]
  116. └─RootNode_(gltf_orientation_matrix) [Object3D]
  117. └─RootNode_(model_correction_matrix) [Object3D]
  118. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  119. └─RootNode [Object3D]
  120. │ ...
  121. ├─Cars [Object3D]
  122. │ ├─CAR_03_1 [Object3D]
  123. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  124. │ ├─CAR_03 [Object3D]
  125. │ │ └─CAR_03_World_ap_0 [Mesh]
  126. │ ├─Car_04 [Object3D]
  127. │ │ └─Car_04_World_ap_0 [Mesh]
  128. │ ├─CAR_03_2 [Object3D]
  129. │ │ └─CAR_03_2_World_ap_0 [Mesh]
  130. │ ├─Car_04_1 [Object3D]
  131. │ │ └─Car_04_1_World_ap_0 [Mesh]
  132. │ ├─Car_04_2 [Object3D]
  133. │ │ └─Car_04_2_World_ap_0 [Mesh]
  134. │ ├─Car_04_3 [Object3D]
  135. │ │ └─Car_04_3_World_ap_0 [Mesh]
  136. │ ├─Car_04_4 [Object3D]
  137. │ │ └─Car_04_4_World_ap_0 [Mesh]
  138. │ ├─Car_08_4 [Object3D]
  139. │ │ └─Car_08_4_World_ap8_0 [Mesh]
  140. │ ├─Car_08_3 [Object3D]
  141. │ │ └─Car_08_3_World_ap9_0 [Mesh]
  142. │ ├─Car_04_1_2 [Object3D]
  143. │ │ └─Car_04_1_2_World_ap_0 [Mesh]
  144. │ ├─Car_08_2 [Object3D]
  145. │ │ └─Car_08_2_World_ap11_0 [Mesh]
  146. │ ├─CAR_03_1_2 [Object3D]
  147. │ │ └─CAR_03_1_2_World_ap_0 [Mesh]
  148. │ ├─CAR_03_2_2 [Object3D]
  149. │ │ └─CAR_03_2_2_World_ap_0 [Mesh]
  150. │ ├─Car_04_2_2 [Object3D]
  151. │ │ └─Car_04_2_2_World_ap_0 [Mesh]
  152. ...
  153. ```
  154. From that we can see all the cars happen to be under a parent
  155. called `"Cars"`
  156. ```text
  157. * ├─Cars [Object3D]
  158. │ ├─CAR_03_1 [Object3D]
  159. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  160. │ ├─CAR_03 [Object3D]
  161. │ │ └─CAR_03_World_ap_0 [Mesh]
  162. │ ├─Car_04 [Object3D]
  163. │ │ └─Car_04_World_ap_0 [Mesh]
  164. ```
  165. So as a simple test I thought I would just try rotating
  166. all the children of the "Cars" node around their Y axis.
  167. I looked up the "Cars" node after loading the scene
  168. and saved the result.
  169. ```js
  170. +let cars;
  171. {
  172. const gltfLoader = new GLTFLoader();
  173. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
  174. const root = gltf.scene;
  175. scene.add(root);
  176. + cars = root.getObjectByName('Cars');
  177. ```
  178. Then in the `render` function we can just set the rotation
  179. of each child of `cars`.
  180. ```js
  181. +function render(time) {
  182. + time *= 0.001; // convert to seconds
  183. if (resizeRendererToDisplaySize(renderer)) {
  184. const canvas = renderer.domElement;
  185. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  186. camera.updateProjectionMatrix();
  187. }
  188. + if (cars) {
  189. + for (const car of cars.children) {
  190. + car.rotation.y = time;
  191. + }
  192. + }
  193. renderer.render(scene, camera);
  194. requestAnimationFrame(render);
  195. }
  196. ```
  197. And we get
  198. {{{example url="../threejs-load-gltf-rotate-cars.html" }}}
  199. Hmmm, it looks like unfortunately this scene wasn't designed to
  200. animate the cars as their origins are not setup for that purpose.
  201. The trucks are rotating in the wrong direction.
  202. This brings up an important point which is if you're going to
  203. do something in 3D you need to plan ahead and design your assets
  204. so they have their origins in the correct places, so they are
  205. the correct scale, etc.
  206. Since I'm not an artist and I don't know blender that well I
  207. will hack this example. We'll take each car and parent it to
  208. another `Object3D`. We will then move those `Object3D` objects
  209. to move the cars but separately we can set the car's original
  210. `Object3D` to re-orient it so it's about where we really need it.
  211. Looking back at the scene graph listing it looks like there
  212. are really only 3 types of cars, "Car_08", "CAR_03", and "Car_04".
  213. Hopefully each type of car will work with the same adjustments.
  214. I wrote this code to go through each car, parent it to a new
  215. `Object3D`, parent that new `Object3D` to the scene, and apply
  216. some per car *type* settings to fix its orientation, and add
  217. the new `Object3D` a `cars` array.
  218. ```js
  219. -let cars;
  220. +const cars = [];
  221. {
  222. const gltfLoader = new GLTFLoader();
  223. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
  224. const root = gltf.scene;
  225. scene.add(root);
  226. - cars = root.getObjectByName('Cars');
  227. + const loadedCars = root.getObjectByName('Cars');
  228. + const fixes = [
  229. + { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI +* .5], },
  230. + { prefix: 'CAR_03', rot: [0, Math.PI, 0], },
  231. + { prefix: 'Car_04', rot: [0, Math.PI, 0], },
  232. + ];
  233. +
  234. + root.updateMatrixWorld();
  235. + for (const car of loadedCars.children.slice()) {
  236. + const fix = fixes.find(fix => car.name.startsWith(fix.prefix));
  237. + const obj = new THREE.Object3D();
  238. + car.getWorldPosition(obj.position);
  239. + car.position.set(0, 0, 0);
  240. + car.rotation.set(...fix.rot);
  241. + obj.add(car);
  242. + scene.add(obj);
  243. + cars.push(obj);
  244. + }
  245. ...
  246. ```
  247. This fixes the orientation of the cars.
  248. {{{example url="../threejs-load-gltf-rotate-cars-fixed.html" }}}
  249. Now let's drive them around.
  250. Making even a simple driving system is too much for this post but
  251. it seems instead we could just make one convoluted path that
  252. drives down all the roads and then put the cars on the path.
  253. Here's a picture from Blender about half way through building
  254. the path.
  255. <div class="threejs_center"><img src="resources/images/making-path-for-cars.jpg" style="width: 1094px"></div>
  256. I needed a way to get the data for that path out of Blender.
  257. Fortunately I was able to select just my path and export .OBJ checking "write nurbs".
  258. <div class="threejs_center"><img src="resources/images/blender-export-obj-write-nurbs.jpg" style="width: 498px"></div>
  259. Opening the .OBJ file I was able to get a list of points
  260. which I formatted into this
  261. ```js
  262. const controlPoints = [
  263. [1.118281, 5.115846, -3.681386],
  264. [3.948875, 5.115846, -3.641834],
  265. [3.960072, 5.115846, -0.240352],
  266. [3.985447, 5.115846, 4.585005],
  267. [-3.793631, 5.115846, 4.585006],
  268. [-3.826839, 5.115846, -14.736200],
  269. [-14.542292, 5.115846, -14.765865],
  270. [-14.520929, 5.115846, -3.627002],
  271. [-5.452815, 5.115846, -3.634418],
  272. [-5.467251, 5.115846, 4.549161],
  273. [-13.266233, 5.115846, 4.567083],
  274. [-13.250067, 5.115846, -13.499271],
  275. [4.081842, 5.115846, -13.435463],
  276. [4.125436, 5.115846, -5.334928],
  277. [-14.521364, 5.115846, -5.239871],
  278. [-14.510466, 5.115846, 5.486727],
  279. [5.745666, 5.115846, 5.510492],
  280. [5.787942, 5.115846, -14.728308],
  281. [-5.423720, 5.115846, -14.761919],
  282. [-5.373599, 5.115846, -3.704133],
  283. [1.004861, 5.115846, -3.641834],
  284. ];
  285. ```
  286. THREE.js has some curve classes. The `CatmullRomCurve3` seemed
  287. like it might work. The thing about that kind of curve is
  288. it tries to make a smooth curve going through the points.
  289. In fact putting those points in directly will generate
  290. a curve like this
  291. <div class="threejs_center"><img src="resources/images/car-curves-before.png" style="width: 400px"></div>
  292. but we want a sharper corners. It seemed like if we computed
  293. some extra points we could get what we want. For each pair
  294. of points we'll compute a point 10% of the way between
  295. the 2 points and another 90% of the way between the 2 points
  296. and pass the result to `CatmullRomCurve3`.
  297. This will give us a curve like this
  298. <div class="threejs_center"><img src="resources/images/car-curves-after.png" style="width: 400px"></div>
  299. Here's the code to make the curve
  300. ```js
  301. let curve;
  302. let curveObject;
  303. {
  304. const controlPoints = [
  305. [1.118281, 5.115846, -3.681386],
  306. [3.948875, 5.115846, -3.641834],
  307. [3.960072, 5.115846, -0.240352],
  308. [3.985447, 5.115846, 4.585005],
  309. [-3.793631, 5.115846, 4.585006],
  310. [-3.826839, 5.115846, -14.736200],
  311. [-14.542292, 5.115846, -14.765865],
  312. [-14.520929, 5.115846, -3.627002],
  313. [-5.452815, 5.115846, -3.634418],
  314. [-5.467251, 5.115846, 4.549161],
  315. [-13.266233, 5.115846, 4.567083],
  316. [-13.250067, 5.115846, -13.499271],
  317. [4.081842, 5.115846, -13.435463],
  318. [4.125436, 5.115846, -5.334928],
  319. [-14.521364, 5.115846, -5.239871],
  320. [-14.510466, 5.115846, 5.486727],
  321. [5.745666, 5.115846, 5.510492],
  322. [5.787942, 5.115846, -14.728308],
  323. [-5.423720, 5.115846, -14.761919],
  324. [-5.373599, 5.115846, -3.704133],
  325. [1.004861, 5.115846, -3.641834],
  326. ];
  327. const p0 = new THREE.Vector3();
  328. const p1 = new THREE.Vector3();
  329. curve = new THREE.CatmullRomCurve3(
  330. controlPoints.map((p, ndx) => {
  331. p0.set(...p);
  332. p1.set(...controlPoints[(ndx + 1) % controlPoints.length]);
  333. return [
  334. (new THREE.Vector3()).copy(p0),
  335. (new THREE.Vector3()).lerpVectors(p0, p1, 0.1),
  336. (new THREE.Vector3()).lerpVectors(p0, p1, 0.9),
  337. ];
  338. }).flat(),
  339. true,
  340. );
  341. {
  342. const points = curve.getPoints(250);
  343. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  344. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  345. curveObject = new THREE.Line(geometry, material);
  346. scene.add(curveObject);
  347. }
  348. }
  349. ```
  350. The first part of that code makes a curve.
  351. The second part of that code generates 250 points
  352. from the curve and then creates an object to display
  353. the lines made by connecting those 250 points.
  354. Running [the example](../threejs-load-gltf-car-path.html) I didn't see
  355. the curve. To make it visible I made it ignore the depth test and
  356. render last
  357. ```js
  358. curveObject = new THREE.Line(geometry, material);
  359. + material.depthTest = false;
  360. + curveObject.renderOrder = 1;
  361. ```
  362. And that's when I discovered it was way too small.
  363. <div class="threejs_center"><img src="resources/images/car-curves-too-small.png" style="width: 498px"></div>
  364. Checking the hierarchy in Blender I found out that the artist had
  365. scaled the node all the cars are parented to.
  366. <div class="threejs_center"><img src="resources/images/cars-scale-0.01.png" style="width: 342px;"></div>
  367. Scaling is bad for real time 3D apps. It causes all kinds of
  368. issues and ends up being no end of frustration when doing
  369. real time 3D. Artists often don't know this because it's so
  370. easy to scale an entire scene in a 3D editing program but
  371. if you decide to make a real time 3D app I suggest you request your
  372. artists to never scale anything. If they change the scale
  373. they should find a way to apply that scale to the vertices
  374. so that when it ends up making it to your app you can ignore
  375. scale.
  376. And, not just scale, in this case the cars are rotated and offset
  377. by their parent, the `Cars` node. This will make it hard at runtime
  378. to move the cars around in world space. To be clear, in this case
  379. we want cars to drive around in world space which is why these
  380. issues are coming up. If something that is meant to be manipulated
  381. in a local space, like the moon revolving around the earth this
  382. is less of an issue.
  383. Going back to the function we wrote above to dump the scene graph,
  384. let's dump the position, rotation, and scale of each node.
  385. ```js
  386. +function dumpVec3(v3, precision = 3) {
  387. + return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`;
  388. +}
  389. function dumpObject(obj, lines, isLast = true, prefix = '') {
  390. const localPrefix = isLast ? '└─' : '├─';
  391. lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  392. + const dataPrefix = obj.children.length
  393. + ? (isLast ? ' │ ' : '│ │ ')
  394. + : (isLast ? ' ' : '│ ');
  395. + lines.push(`${prefix}${dataPrefix} pos: ${dumpVec3(obj.position)}`);
  396. + lines.push(`${prefix}${dataPrefix} rot: ${dumpVec3(obj.rotation)}`);
  397. + lines.push(`${prefix}${dataPrefix} scl: ${dumpVec3(obj.scale)}`);
  398. const newPrefix = prefix + (isLast ? ' ' : '│ ');
  399. const lastNdx = obj.children.length - 1;
  400. obj.children.forEach((child, ndx) => {
  401. const isLast = ndx === lastNdx;
  402. dumpObject(child, lines, isLast, newPrefix);
  403. });
  404. return lines;
  405. }
  406. ```
  407. And the result from [running it](../threejs-load-gltf-dump-scenegraph-extra.html)
  408. ```text
  409. OSG_Scene [Scene]
  410. │ pos: 0.000, 0.000, 0.000
  411. │ rot: 0.000, 0.000, 0.000
  412. │ scl: 1.000, 1.000, 1.000
  413. └─RootNode_(gltf_orientation_matrix) [Object3D]
  414. │ pos: 0.000, 0.000, 0.000
  415. │ rot: -1.571, 0.000, 0.000
  416. │ scl: 1.000, 1.000, 1.000
  417. └─RootNode_(model_correction_matrix) [Object3D]
  418. │ pos: 0.000, 0.000, 0.000
  419. │ rot: 0.000, 0.000, 0.000
  420. │ scl: 1.000, 1.000, 1.000
  421. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  422. │ pos: 0.000, 0.000, 0.000
  423. │ rot: 1.571, 0.000, 0.000
  424. │ scl: 1.000, 1.000, 1.000
  425. └─RootNode [Object3D]
  426. │ pos: 0.000, 0.000, 0.000
  427. │ rot: 0.000, 0.000, 0.000
  428. │ scl: 1.000, 1.000, 1.000
  429. ├─Cars [Object3D]
  430. * │ │ pos: -369.069, -90.704, -920.159
  431. * │ │ rot: 0.000, 0.000, 0.000
  432. * │ │ scl: 1.000, 1.000, 1.000
  433. │ ├─CAR_03_1 [Object3D]
  434. │ │ │ pos: 22.131, 14.663, -475.071
  435. │ │ │ rot: -3.142, 0.732, 3.142
  436. │ │ │ scl: 1.500, 1.500, 1.500
  437. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  438. │ │ pos: 0.000, 0.000, 0.000
  439. │ │ rot: 0.000, 0.000, 0.000
  440. │ │ scl: 1.000, 1.000, 1.000
  441. ```
  442. This shows us that `Cars` in the original scene has had its rotation and scale
  443. removed and applied to its children. That suggests either whatever exporter was
  444. used to create the .GLTF file did some special work here or more likely the
  445. artist exported a different version of the file than the corresponding .blend
  446. file, which is why things don't match.
  447. The moral of that is I should have probably downloaded the .blend
  448. file and exported myself. Before exporting I should have inspected
  449. all the major nodes and removed any transformations.
  450. All these nodes at the top
  451. ```text
  452. OSG_Scene [Scene]
  453. │ pos: 0.000, 0.000, 0.000
  454. │ rot: 0.000, 0.000, 0.000
  455. │ scl: 1.000, 1.000, 1.000
  456. └─RootNode_(gltf_orientation_matrix) [Object3D]
  457. │ pos: 0.000, 0.000, 0.000
  458. │ rot: -1.571, 0.000, 0.000
  459. │ scl: 1.000, 1.000, 1.000
  460. └─RootNode_(model_correction_matrix) [Object3D]
  461. │ pos: 0.000, 0.000, 0.000
  462. │ rot: 0.000, 0.000, 0.000
  463. │ scl: 1.000, 1.000, 1.000
  464. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  465. │ pos: 0.000, 0.000, 0.000
  466. │ rot: 1.571, 0.000, 0.000
  467. │ scl: 1.000, 1.000, 1.000
  468. ```
  469. are also a waste.
  470. Ideally the scene would consist of a single "root" node with no position,
  471. rotation, or scale. At runtime I could then pull all the children out of that
  472. root and parent them to the scene itself. There might be children of the root
  473. like "Cars" which would help me find all the cars but ideally it would also have
  474. no translation, rotation, or scale so I could re-parent the cars to the scene
  475. with the minimal amount of work.
  476. In any case the quickest though maybe not the best fix is to just
  477. adjust the object we're using to view the curve.
  478. Here's what I ended up with.
  479. First I adjusted the position of the curve and found values
  480. that seemed to work. I then hid it.
  481. ```js
  482. {
  483. const points = curve.getPoints(250);
  484. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  485. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  486. curveObject = new THREE.Line(geometry, material);
  487. + curveObject.scale.set(100, 100, 100);
  488. + curveObject.position.y = -621;
  489. + curveObject.visible = false;
  490. material.depthTest = false;
  491. curveObject.renderOrder = 1;
  492. scene.add(curveObject);
  493. }
  494. ```
  495. Then I wrote code to move the cars along the curve. For each car we pick a
  496. position from 0 to 1 along the curve and compute a point in world space using
  497. the `curveObject` to transform the point. We then pick another point slightly
  498. further down the curve. We set the car's orientation using `lookAt` and put the
  499. car at the mid point between the 2 points.
  500. ```js
  501. // create 2 Vector3s we can use for path calculations
  502. const carPosition = new THREE.Vector3();
  503. const carTarget = new THREE.Vector3();
  504. function render(time) {
  505. ...
  506. - for (const car of cars) {
  507. - car.rotation.y = time;
  508. - }
  509. + {
  510. + const pathTime = time * .01;
  511. + const targetOffset = 0.01;
  512. + cars.forEach((car, ndx) => {
  513. + // a number between 0 and 1 to evenly space the cars
  514. + const u = pathTime + ndx / cars.length;
  515. +
  516. + // get the first point
  517. + curve.getPointAt(u % 1, carPosition);
  518. + carPosition.applyMatrix4(curveObject.matrixWorld);
  519. +
  520. + // get a second point slightly further down the curve
  521. + curve.getPointAt((u + targetOffset) % 1, carTarget);
  522. + carTarget.applyMatrix4(curveObject.matrixWorld);
  523. +
  524. + // put the car at the first point (temporarily)
  525. + car.position.copy(carPosition);
  526. + // point the car the second point
  527. + car.lookAt(carTarget);
  528. +
  529. + // put the car between the 2 points
  530. + car.position.lerpVectors(carPosition, carTarget, 0.5);
  531. + });
  532. + }
  533. ```
  534. and when I ran it I found out for each type of car, their height above their origins
  535. are not consistently set and so I needed to offset each one
  536. a little.
  537. ```js
  538. const loadedCars = root.getObjectByName('Cars');
  539. const fixes = [
  540. - { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], },
  541. - { prefix: 'CAR_03', rot: [0, Math.PI, 0], },
  542. - { prefix: 'Car_04', rot: [0, Math.PI, 0], },
  543. + { prefix: 'Car_08', y: 0, rot: [Math.PI * .5, 0, Math.PI * .5], },
  544. + { prefix: 'CAR_03', y: 33, rot: [0, Math.PI, 0], },
  545. + { prefix: 'Car_04', y: 40, rot: [0, Math.PI, 0], },
  546. ];
  547. root.updateMatrixWorld();
  548. for (const car of loadedCars.children.slice()) {
  549. const fix = fixes.find(fix => car.name.startsWith(fix.prefix));
  550. const obj = new THREE.Object3D();
  551. car.getWorldPosition(obj.position);
  552. - car.position.set(0, 0, 0);
  553. + car.position.set(0, fix.y, 0);
  554. car.rotation.set(...fix.rot);
  555. obj.add(car);
  556. scene.add(obj);
  557. cars.push(obj);
  558. }
  559. ```
  560. And the result.
  561. {{{example url="../threejs-load-gltf-animated-cars.html" }}}
  562. Not bad for a few minutes work.
  563. The last thing I wanted to do is turn on shadows.
  564. To do this I grabbed all the GUI code from the `DirectionalLight` shadows
  565. example in [the article on shadows](threejs-shadows.html) and pasted it
  566. into our latest code.
  567. Then, after loading, we need to turn on shadows on all the objects.
  568. ```js
  569. {
  570. const gltfLoader = new GLTFLoader();
  571. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
  572. const root = gltf.scene;
  573. scene.add(root);
  574. + root.traverse((obj) => {
  575. + if (obj.castShadow !== undefined) {
  576. + obj.castShadow = true;
  577. + obj.receiveShadow = true;
  578. + }
  579. + });
  580. ```
  581. I then spent nearly 4 hours trying to figure out why the shadow helpers
  582. were not working. It was because I forgot to enable shadows with
  583. ```js
  584. renderer.shadowMap.enabled = true;
  585. ```
  586. 😭
  587. I then adjusted the values until our `DirectionLight`'s shadow camera
  588. had a frustum that covered the entire scene. These are the settings
  589. I ended up with.
  590. ```js
  591. {
  592. const color = 0xFFFFFF;
  593. const intensity = 1;
  594. const light = new THREE.DirectionalLight(color, intensity);
  595. + light.castShadow = true;
  596. * light.position.set(-250, 800, -850);
  597. * light.target.position.set(-550, 40, -450);
  598. + light.shadow.bias = -0.004;
  599. + light.shadow.mapSize.width = 2048;
  600. + light.shadow.mapSize.height = 2048;
  601. scene.add(light);
  602. scene.add(light.target);
  603. + const cam = light.shadow.camera;
  604. + cam.near = 1;
  605. + cam.far = 2000;
  606. + cam.left = -1500;
  607. + cam.right = 1500;
  608. + cam.top = 1500;
  609. + cam.bottom = -1500;
  610. ...
  611. ```
  612. and I set the background color to light blue.
  613. ```js
  614. const scene = new THREE.Scene();
  615. -scene.background = new THREE.Color('black');
  616. +scene.background = new THREE.Color('#DEFEFF');
  617. ```
  618. And ... shadows
  619. {{{example url="../threejs-load-gltf-shadows.html" }}}
  620. I hope walking through this project was useful and showed some
  621. good examples of working though some of the issues of loading
  622. a file with a scenegraph.
  623. One interesting thing is that comparing the .blend file to the .gltf
  624. file, the .blend file has several lights but they are not lights
  625. after being loaded into the scene. A .GLTF file is just a JSON
  626. file so you can easily look inside. It consists of several
  627. arrays of things and each item in an array is referenced by index
  628. else where. While there are extensions in the works they point
  629. to a problem with almost all 3d formats. **They can never cover every
  630. case**.
  631. There is always a need for more data. For example we manually exported
  632. a path for the cars to follow. Ideally that info could have been in
  633. the .GLTF file but to do that we'd need to write our own exporter
  634. and some how mark nodes for how we want them exported or use a
  635. naming scheme or something along those lines to get data from
  636. whatever tool we're using to create the data into our app.
  637. All of that is left as an exercise to the reader.