SkeletonUtils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import {
  2. AnimationClip,
  3. AnimationMixer,
  4. Matrix4,
  5. Quaternion,
  6. QuaternionKeyframeTrack,
  7. SkeletonHelper,
  8. Vector3,
  9. VectorKeyframeTrack
  10. } from 'three';
  11. /** @module SkeletonUtils */
  12. function getBoneName( bone, options ) {
  13. if ( options.getBoneName !== undefined ) {
  14. return options.getBoneName( bone );
  15. }
  16. return options.names[ bone.name ];
  17. }
  18. /**
  19. * Retargets the skeleton from the given source 3D object to the
  20. * target 3D object.
  21. *
  22. * @param {Object3D} target - The target 3D object.
  23. * @param {Object3D} source - The source 3D object.
  24. * @param {module:SkeletonUtils~RetargetOptions} options - The options.
  25. */
  26. function retarget( target, source, options = {} ) {
  27. const quat = new Quaternion(),
  28. scale = new Vector3(),
  29. relativeMatrix = new Matrix4(),
  30. globalMatrix = new Matrix4();
  31. options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true;
  32. options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true;
  33. options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
  34. options.hip = options.hip !== undefined ? options.hip : 'hip';
  35. options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3( 1, 1, 1 );
  36. options.scale = options.scale !== undefined ? options.scale : 1;
  37. options.names = options.names || {};
  38. const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  39. bones = target.isObject3D ? target.skeleton.bones : getBones( target );
  40. let bone, name, boneTo,
  41. bonesPosition;
  42. // reset bones
  43. if ( target.isObject3D ) {
  44. target.skeleton.pose();
  45. } else {
  46. options.useTargetMatrix = true;
  47. options.preserveBoneMatrix = false;
  48. }
  49. if ( options.preserveBonePositions ) {
  50. bonesPosition = [];
  51. for ( let i = 0; i < bones.length; i ++ ) {
  52. bonesPosition.push( bones[ i ].position.clone() );
  53. }
  54. }
  55. if ( options.preserveBoneMatrix ) {
  56. // reset matrix
  57. target.updateMatrixWorld();
  58. target.matrixWorld.identity();
  59. // reset children matrix
  60. for ( let i = 0; i < target.children.length; ++ i ) {
  61. target.children[ i ].updateMatrixWorld( true );
  62. }
  63. }
  64. for ( let i = 0; i < bones.length; ++ i ) {
  65. bone = bones[ i ];
  66. name = getBoneName( bone, options );
  67. boneTo = getBoneByName( name, sourceBones );
  68. globalMatrix.copy( bone.matrixWorld );
  69. if ( boneTo ) {
  70. boneTo.updateMatrixWorld();
  71. if ( options.useTargetMatrix ) {
  72. relativeMatrix.copy( boneTo.matrixWorld );
  73. } else {
  74. relativeMatrix.copy( target.matrixWorld ).invert();
  75. relativeMatrix.multiply( boneTo.matrixWorld );
  76. }
  77. // ignore scale to extract rotation
  78. scale.setFromMatrixScale( relativeMatrix );
  79. relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
  80. // apply to global matrix
  81. globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
  82. if ( target.isObject3D ) {
  83. if ( options.localOffsets ) {
  84. if ( options.localOffsets[ bone.name ] ) {
  85. globalMatrix.multiply( options.localOffsets[ bone.name ] );
  86. }
  87. }
  88. }
  89. globalMatrix.copyPosition( relativeMatrix );
  90. }
  91. if ( name === options.hip ) {
  92. globalMatrix.elements[ 12 ] *= options.scale * options.hipInfluence.x;
  93. globalMatrix.elements[ 13 ] *= options.scale * options.hipInfluence.y;
  94. globalMatrix.elements[ 14 ] *= options.scale * options.hipInfluence.z;
  95. if ( options.hipPosition !== undefined ) {
  96. globalMatrix.elements[ 12 ] += options.hipPosition.x * options.scale;
  97. globalMatrix.elements[ 13 ] += options.hipPosition.y * options.scale;
  98. globalMatrix.elements[ 14 ] += options.hipPosition.z * options.scale;
  99. }
  100. }
  101. if ( bone.parent ) {
  102. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  103. bone.matrix.multiply( globalMatrix );
  104. } else {
  105. bone.matrix.copy( globalMatrix );
  106. }
  107. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  108. bone.updateMatrixWorld();
  109. }
  110. if ( options.preserveBonePositions ) {
  111. for ( let i = 0; i < bones.length; ++ i ) {
  112. bone = bones[ i ];
  113. name = getBoneName( bone, options ) || bone.name;
  114. if ( name !== options.hip ) {
  115. bone.position.copy( bonesPosition[ i ] );
  116. }
  117. }
  118. }
  119. if ( options.preserveBoneMatrix ) {
  120. // restore matrix
  121. target.updateMatrixWorld( true );
  122. }
  123. }
  124. /**
  125. * Retargets the animation clip of the source object to the
  126. * target 3D object.
  127. *
  128. * @param {Object3D} target - The target 3D object.
  129. * @param {Object3D} source - The source 3D object.
  130. * @param {AnimationClip} clip - The animation clip.
  131. * @param {module:SkeletonUtils~RetargetOptions} options - The options.
  132. * @return {AnimationClip} The retargeted animation clip.
  133. */
  134. function retargetClip( target, source, clip, options = {} ) {
  135. options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
  136. // Calculate the fps from the source clip based on the track with the most frames, unless fps is already provided.
  137. options.fps = options.fps !== undefined ? options.fps : ( Math.max( ...clip.tracks.map( track => track.times.length ) ) / clip.duration );
  138. options.names = options.names || [];
  139. if ( ! source.isObject3D ) {
  140. source = getHelperFromSkeleton( source );
  141. }
  142. const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
  143. delta = clip.duration / ( numFrames - 1 ),
  144. convertedTracks = [],
  145. mixer = new AnimationMixer( source ),
  146. bones = getBones( target.skeleton ),
  147. boneDatas = [];
  148. let positionOffset,
  149. bone, boneTo, boneData,
  150. name;
  151. mixer.clipAction( clip ).play();
  152. // trim
  153. let start = 0, end = numFrames;
  154. if ( options.trim !== undefined ) {
  155. start = Math.round( options.trim[ 0 ] * options.fps );
  156. end = Math.min( Math.round( options.trim[ 1 ] * options.fps ), numFrames ) - start;
  157. mixer.update( options.trim[ 0 ] );
  158. } else {
  159. mixer.update( 0 );
  160. }
  161. source.updateMatrixWorld();
  162. //
  163. for ( let frame = 0; frame < end; ++ frame ) {
  164. const time = frame * delta;
  165. retarget( target, source, options );
  166. for ( let j = 0; j < bones.length; ++ j ) {
  167. bone = bones[ j ];
  168. name = getBoneName( bone, options ) || bone.name;
  169. boneTo = getBoneByName( name, source.skeleton );
  170. if ( boneTo ) {
  171. boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };
  172. if ( options.hip === name ) {
  173. if ( ! boneData.pos ) {
  174. boneData.pos = {
  175. times: new Float32Array( end ),
  176. values: new Float32Array( end * 3 )
  177. };
  178. }
  179. if ( options.useFirstFramePosition ) {
  180. if ( frame === 0 ) {
  181. positionOffset = bone.position.clone();
  182. }
  183. bone.position.sub( positionOffset );
  184. }
  185. boneData.pos.times[ frame ] = time;
  186. bone.position.toArray( boneData.pos.values, frame * 3 );
  187. }
  188. if ( ! boneData.quat ) {
  189. boneData.quat = {
  190. times: new Float32Array( end ),
  191. values: new Float32Array( end * 4 )
  192. };
  193. }
  194. boneData.quat.times[ frame ] = time;
  195. bone.quaternion.toArray( boneData.quat.values, frame * 4 );
  196. }
  197. }
  198. if ( frame === end - 2 ) {
  199. // last mixer update before final loop iteration
  200. // make sure we do not go over or equal to clip duration
  201. mixer.update( delta - 0.0000001 );
  202. } else {
  203. mixer.update( delta );
  204. }
  205. source.updateMatrixWorld();
  206. }
  207. for ( let i = 0; i < boneDatas.length; ++ i ) {
  208. boneData = boneDatas[ i ];
  209. if ( boneData ) {
  210. if ( boneData.pos ) {
  211. convertedTracks.push( new VectorKeyframeTrack(
  212. '.bones[' + boneData.bone.name + '].position',
  213. boneData.pos.times,
  214. boneData.pos.values
  215. ) );
  216. }
  217. convertedTracks.push( new QuaternionKeyframeTrack(
  218. '.bones[' + boneData.bone.name + '].quaternion',
  219. boneData.quat.times,
  220. boneData.quat.values
  221. ) );
  222. }
  223. }
  224. mixer.uncacheAction( clip );
  225. return new AnimationClip( clip.name, - 1, convertedTracks );
  226. }
  227. /**
  228. * Clones the given 3D object and its descendants, ensuring that any `SkinnedMesh` instances are
  229. * correctly associated with their bones. Bones are also cloned, and must be descendants of the
  230. * object passed to this method. Other data, like geometries and materials, are reused by reference.
  231. *
  232. * @param {Object3D} source - The 3D object to clone.
  233. * @return {Object3D} The cloned 3D object.
  234. */
  235. function clone( source ) {
  236. const sourceLookup = new Map();
  237. const cloneLookup = new Map();
  238. const clone = source.clone();
  239. parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
  240. sourceLookup.set( clonedNode, sourceNode );
  241. cloneLookup.set( sourceNode, clonedNode );
  242. } );
  243. clone.traverse( function ( node ) {
  244. if ( ! node.isSkinnedMesh ) return;
  245. const clonedMesh = node;
  246. const sourceMesh = sourceLookup.get( node );
  247. const sourceBones = sourceMesh.skeleton.bones;
  248. clonedMesh.skeleton = sourceMesh.skeleton.clone();
  249. clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
  250. clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
  251. return cloneLookup.get( bone );
  252. } );
  253. clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
  254. } );
  255. return clone;
  256. }
  257. // internal helper
  258. function getBoneByName( name, skeleton ) {
  259. for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
  260. if ( name === bones[ i ].name )
  261. return bones[ i ];
  262. }
  263. }
  264. function getBones( skeleton ) {
  265. return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
  266. }
  267. function getHelperFromSkeleton( skeleton ) {
  268. const source = new SkeletonHelper( skeleton.bones[ 0 ] );
  269. source.skeleton = skeleton;
  270. return source;
  271. }
  272. function parallelTraverse( a, b, callback ) {
  273. callback( a, b );
  274. for ( let i = 0; i < a.children.length; i ++ ) {
  275. parallelTraverse( a.children[ i ], b.children[ i ], callback );
  276. }
  277. }
  278. /**
  279. * Retarget options of `SkeletonUtils`.
  280. *
  281. * @typedef {Object} module:SkeletonUtils~RetargetOptions
  282. * @property {boolean} [useFirstFramePosition=false] - Whether to use the position of the first frame or not.
  283. * @property {number} [fps] - The FPS of the clip.
  284. * @property {Object<string,string>} [names] - A dictionary for mapping target to source bone names.
  285. * @property {function(string):string} [getBoneName] - A function for mapping bone names. Alternative to `names`.
  286. * @property {Array<number>} [trim] - Whether to trim the clip or not. If set the array should hold two values for the start and end.
  287. * @property {boolean} [preserveBoneMatrix=true] - Whether to preserve bone matrices or not.
  288. * @property {boolean} [preserveBonePositions=true] - Whether to preserve bone positions or not.
  289. * @property {boolean} [useTargetMatrix=false] - Whether to use the target matrix or not.
  290. * @property {string} [hip='hip'] - The name of the source's hip bone.
  291. * @property {Vector3} [hipInfluence=(1,1,1)] - The hip influence.
  292. * @property {number} [scale=1] - The scale.
  293. **/
  294. export {
  295. retarget,
  296. retargetClip,
  297. clone,
  298. };
粤ICP备19079148号