webgl_animation_multiple.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Multiple animated objects</title>
  5. <meta charset="utf-8">
  6. <meta content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" name="viewport">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="container"></div>
  11. <div id="info">
  12. This demo shows how to clone a skinned 3d model using <strong>SkeletonUtils.clone()</strong><br/>
  13. Soldier model from <a href="https://www.mixamo.com" target="_blank" rel="noopener">https://www.mixamo.com</a>.
  14. </div>
  15. <script type="module">
  16. import * as THREE from '../build/three.module.js';
  17. import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
  18. import * as SkeletonUtils from './jsm/utils/SkeletonUtils.js';
  19. //////////////////////////////
  20. // Global objects
  21. //////////////////////////////
  22. let worldScene = null; // THREE.Scene where it all will be rendered
  23. let renderer = null;
  24. let camera = null;
  25. let clock = null;
  26. const mixers = []; // All the THREE.AnimationMixer objects for all the animations in the scene
  27. //////////////////////////////
  28. //////////////////////////////
  29. // Information about our 3D models and units
  30. //////////////////////////////
  31. // The names of the 3D models to load. One-per file.
  32. // A model may have multiple SkinnedMesh objects as well as several rigs (armatures). Units will define which
  33. // meshes, armatures and animations to use. We will load the whole scene for each object and clone it for each unit.
  34. // Models are from https://www.mixamo.com/
  35. const MODELS = [
  36. { name: "Soldier" },
  37. { name: "Parrot" },
  38. ];
  39. // Here we define instances of the models that we want to place in the scene, their position, scale and the animations
  40. // that must be played.
  41. const UNITS = [
  42. {
  43. modelName: "Soldier", // Will use the 3D model from file models/gltf/Soldier.glb
  44. meshName: "vanguard_Mesh", // Name of the main mesh to animate
  45. position: { x: 0, y: 0, z: 0 }, // Where to put the unit in the scene
  46. scale: 1, // Scaling of the unit. 1.0 means: use original size, 0.1 means "10 times smaller", etc.
  47. animationName: "Idle" // Name of animation to run
  48. },
  49. {
  50. modelName: "Soldier",
  51. meshName: "vanguard_Mesh",
  52. position: { x: 3, y: 0, z: 0 },
  53. scale: 2,
  54. animationName: "Walk"
  55. },
  56. {
  57. modelName: "Soldier",
  58. meshName: "vanguard_Mesh",
  59. position: { x: 1, y: 0, z: 0 },
  60. scale: 1,
  61. animationName: "Run"
  62. },
  63. {
  64. modelName: "Parrot",
  65. meshName: "mesh_0",
  66. position: { x: - 4, y: 0, z: 0 },
  67. rotation: { x: 0, y: Math.PI, z: 0 },
  68. scale: 0.01,
  69. animationName: "parrot_A_"
  70. },
  71. {
  72. modelName: "Parrot",
  73. meshName: "mesh_0",
  74. position: { x: - 2, y: 0, z: 0 },
  75. rotation: { x: 0, y: Math.PI / 2, z: 0 },
  76. scale: 0.02,
  77. animationName: null
  78. },
  79. ];
  80. //////////////////////////////
  81. // The main setup happens here
  82. //////////////////////////////
  83. let numLoadedModels = 0;
  84. initScene();
  85. initRenderer();
  86. loadModels();
  87. animate();
  88. //////////////////////////////
  89. //////////////////////////////
  90. // Function implementations
  91. //////////////////////////////
  92. /**
  93. * Function that starts loading process for the next model in the queue. The loading process is
  94. * asynchronous: it happens "in the background". Therefore we don't load all the models at once. We load one,
  95. * wait until it is done, then load the next one. When all models are loaded, we call loadUnits().
  96. */
  97. function loadModels() {
  98. for ( let i = 0; i < MODELS.length; ++ i ) {
  99. const m = MODELS[ i ];
  100. loadGltfModel( m, function () {
  101. ++ numLoadedModels;
  102. if ( numLoadedModels === MODELS.length ) {
  103. console.log( "All models loaded, time to instantiate units..." );
  104. instantiateUnits();
  105. }
  106. } );
  107. }
  108. }
  109. /**
  110. * Look at UNITS configuration, clone necessary 3D model scenes, place the armatures and meshes in the scene and
  111. * launch necessary animations
  112. */
  113. function instantiateUnits() {
  114. let numSuccess = 0;
  115. for ( let i = 0; i < UNITS.length; ++ i ) {
  116. const u = UNITS[ i ];
  117. const model = getModelByName( u.modelName );
  118. if ( model ) {
  119. const clonedScene = SkeletonUtils.clone( model.scene );
  120. if ( clonedScene ) {
  121. // THREE.Scene is cloned properly, let's find one mesh and launch animation for it
  122. const clonedMesh = clonedScene.getObjectByName( u.meshName );
  123. if ( clonedMesh ) {
  124. const mixer = startAnimation( clonedMesh, model.animations, u.animationName );
  125. // Save the animation mixer in the list, will need it in the animation loop
  126. mixers.push( mixer );
  127. numSuccess ++;
  128. }
  129. // Different models can have different configurations of armatures and meshes. Therefore,
  130. // We can't set position, scale or rotation to individual mesh objects. Instead we set
  131. // it to the whole cloned scene and then add the whole scene to the game world
  132. // Note: this may have weird effects if you have lights or other items in the GLTF file's scene!
  133. worldScene.add( clonedScene );
  134. if ( u.position ) {
  135. clonedScene.position.set( u.position.x, u.position.y, u.position.z );
  136. }
  137. if ( u.scale ) {
  138. clonedScene.scale.set( u.scale, u.scale, u.scale );
  139. }
  140. if ( u.rotation ) {
  141. clonedScene.rotation.x = u.rotation.x;
  142. clonedScene.rotation.y = u.rotation.y;
  143. clonedScene.rotation.z = u.rotation.z;
  144. }
  145. }
  146. } else {
  147. console.error( "Can not find model", u.modelName );
  148. }
  149. }
  150. console.log( `Successfully instantiated ${numSuccess} units` );
  151. }
  152. /**
  153. * Start animation for a specific mesh object. Find the animation by name in the 3D model's animation array
  154. * @param skinnedMesh {THREE.SkinnedMesh} The mesh to animate
  155. * @param animations {Array} Array containing all the animations for this model
  156. * @param animationName {string} Name of the animation to launch
  157. * @return {THREE.AnimationMixer} Mixer to be used in the render loop
  158. */
  159. function startAnimation( skinnedMesh, animations, animationName ) {
  160. const mixer = new THREE.AnimationMixer( skinnedMesh );
  161. const clip = THREE.AnimationClip.findByName( animations, animationName );
  162. if ( clip ) {
  163. const action = mixer.clipAction( clip );
  164. action.play();
  165. }
  166. return mixer;
  167. }
  168. /**
  169. * Find a model object by name
  170. * @param name
  171. * @returns {object|null}
  172. */
  173. function getModelByName( name ) {
  174. for ( let i = 0; i < MODELS.length; ++ i ) {
  175. if ( MODELS[ i ].name === name ) {
  176. return MODELS[ i ];
  177. }
  178. }
  179. return null;
  180. }
  181. /**
  182. * Load a 3D model from a GLTF file. Use the GLTFLoader.
  183. * @param model {object} Model config, one item from the MODELS array. It will be updated inside the function!
  184. * @param onLoaded {function} A callback function that will be called when the model is loaded
  185. */
  186. function loadGltfModel( model, onLoaded ) {
  187. const loader = new GLTFLoader();
  188. const modelName = "models/gltf/" + model.name + ".glb";
  189. loader.load( modelName, function ( gltf ) {
  190. const scene = gltf.scene;
  191. model.animations = gltf.animations;
  192. model.scene = scene;
  193. // Enable Shadows
  194. gltf.scene.traverse( function ( object ) {
  195. if ( object.isMesh ) {
  196. object.castShadow = true;
  197. }
  198. } );
  199. console.log( "Done loading model", model.name );
  200. onLoaded();
  201. } );
  202. }
  203. /**
  204. * Render loop. Renders the next frame of all animations
  205. */
  206. function animate() {
  207. requestAnimationFrame( animate );
  208. // Get the time elapsed since the last frame
  209. const mixerUpdateDelta = clock.getDelta();
  210. // Update all the animation frames
  211. for ( let i = 0; i < mixers.length; ++ i ) {
  212. mixers[ i ].update( mixerUpdateDelta );
  213. }
  214. renderer.render( worldScene, camera );
  215. }
  216. //////////////////////////////
  217. // General Three.JS stuff
  218. //////////////////////////////
  219. // This part is not anyhow related to the cloning of models, it's just setting up the scene.
  220. /**
  221. * Initialize ThreeJS scene renderer
  222. */
  223. function initRenderer() {
  224. const container = document.getElementById( 'container' );
  225. renderer = new THREE.WebGLRenderer( { antialias: true } );
  226. renderer.setPixelRatio( window.devicePixelRatio );
  227. renderer.setSize( window.innerWidth, window.innerHeight );
  228. renderer.outputEncoding = THREE.sRGBEncoding;
  229. renderer.shadowMap.enabled = true;
  230. renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  231. container.appendChild( renderer.domElement );
  232. }
  233. /**
  234. * Initialize ThreeJS THREE.Scene
  235. */
  236. function initScene() {
  237. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
  238. camera.position.set( 3, 6, - 10 );
  239. camera.lookAt( 0, 1, 0 );
  240. clock = new THREE.Clock();
  241. worldScene = new THREE.Scene();
  242. worldScene.background = new THREE.Color( 0xa0a0a0 );
  243. worldScene.fog = new THREE.Fog( 0xa0a0a0, 10, 22 );
  244. const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
  245. hemiLight.position.set( 0, 20, 0 );
  246. worldScene.add( hemiLight );
  247. const dirLight = new THREE.DirectionalLight( 0xffffff );
  248. dirLight.position.set( - 3, 10, - 10 );
  249. dirLight.castShadow = true;
  250. dirLight.shadow.camera.top = 10;
  251. dirLight.shadow.camera.bottom = - 10;
  252. dirLight.shadow.camera.left = - 10;
  253. dirLight.shadow.camera.right = 10;
  254. dirLight.shadow.camera.near = 0.1;
  255. dirLight.shadow.camera.far = 40;
  256. worldScene.add( dirLight );
  257. // ground
  258. const groundMesh = new THREE.Mesh(
  259. new THREE.PlaneGeometry( 40, 40 ),
  260. new THREE.MeshPhongMaterial( {
  261. color: 0x999999,
  262. depthWrite: false
  263. } )
  264. );
  265. groundMesh.rotation.x = - Math.PI / 2;
  266. groundMesh.receiveShadow = true;
  267. worldScene.add( groundMesh );
  268. window.addEventListener( 'resize', onWindowResize );
  269. }
  270. /**
  271. * A callback that will be called whenever the browser window is resized.
  272. */
  273. function onWindowResize() {
  274. camera.aspect = window.innerWidth / window.innerHeight;
  275. camera.updateProjectionMatrix();
  276. renderer.setSize( window.innerWidth, window.innerHeight );
  277. }
  278. </script>
  279. </body>
  280. </html>