webgl_animation_multiple.html 10 KB

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