0
0

SkeletonUtils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. ( function () {
  2. function retarget( target, source, options = {} ) {
  3. const pos = new THREE.Vector3(),
  4. quat = new THREE.Quaternion(),
  5. scale = new THREE.Vector3(),
  6. bindBoneMatrix = new THREE.Matrix4(),
  7. relativeMatrix = new THREE.Matrix4(),
  8. globalMatrix = new THREE.Matrix4();
  9. options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true;
  10. options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true;
  11. options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false;
  12. options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
  13. options.hip = options.hip !== undefined ? options.hip : 'hip';
  14. options.names = options.names || {};
  15. const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  16. bones = target.isObject3D ? target.skeleton.bones : getBones( target );
  17. let bindBones, bone, name, boneTo, bonesPosition; // reset bones
  18. if ( target.isObject3D ) {
  19. target.skeleton.pose();
  20. } else {
  21. options.useTargetMatrix = true;
  22. options.preserveMatrix = false;
  23. }
  24. if ( options.preservePosition ) {
  25. bonesPosition = [];
  26. for ( let i = 0; i < bones.length; i ++ ) {
  27. bonesPosition.push( bones[ i ].position.clone() );
  28. }
  29. }
  30. if ( options.preserveMatrix ) {
  31. // reset matrix
  32. target.updateMatrixWorld();
  33. target.matrixWorld.identity(); // reset children matrix
  34. for ( let i = 0; i < target.children.length; ++ i ) {
  35. target.children[ i ].updateMatrixWorld( true );
  36. }
  37. }
  38. if ( options.offsets ) {
  39. bindBones = [];
  40. for ( let i = 0; i < bones.length; ++ i ) {
  41. bone = bones[ i ];
  42. name = options.names[ bone.name ] || bone.name;
  43. if ( options.offsets && options.offsets[ name ] ) {
  44. bone.matrix.multiply( options.offsets[ name ] );
  45. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  46. bone.updateMatrixWorld();
  47. }
  48. bindBones.push( bone.matrixWorld.clone() );
  49. }
  50. }
  51. for ( let i = 0; i < bones.length; ++ i ) {
  52. bone = bones[ i ];
  53. name = options.names[ bone.name ] || bone.name;
  54. boneTo = getBoneByName( name, sourceBones );
  55. globalMatrix.copy( bone.matrixWorld );
  56. if ( boneTo ) {
  57. boneTo.updateMatrixWorld();
  58. if ( options.useTargetMatrix ) {
  59. relativeMatrix.copy( boneTo.matrixWorld );
  60. } else {
  61. relativeMatrix.copy( target.matrixWorld ).invert();
  62. relativeMatrix.multiply( boneTo.matrixWorld );
  63. } // ignore scale to extract rotation
  64. scale.setFromMatrixScale( relativeMatrix );
  65. relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) ); // apply to global matrix
  66. globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
  67. if ( target.isObject3D ) {
  68. const boneIndex = bones.indexOf( bone ),
  69. wBindMatrix = bindBones ? bindBones[ boneIndex ] : bindBoneMatrix.copy( target.skeleton.boneInverses[ boneIndex ] ).invert();
  70. globalMatrix.multiply( wBindMatrix );
  71. }
  72. globalMatrix.copyPosition( relativeMatrix );
  73. }
  74. if ( bone.parent && bone.parent.isBone ) {
  75. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  76. bone.matrix.multiply( globalMatrix );
  77. } else {
  78. bone.matrix.copy( globalMatrix );
  79. }
  80. if ( options.preserveHipPosition && name === options.hip ) {
  81. bone.matrix.setPosition( pos.set( 0, bone.position.y, 0 ) );
  82. }
  83. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  84. bone.updateMatrixWorld();
  85. }
  86. if ( options.preservePosition ) {
  87. for ( let i = 0; i < bones.length; ++ i ) {
  88. bone = bones[ i ];
  89. name = options.names[ bone.name ] || bone.name;
  90. if ( name !== options.hip ) {
  91. bone.position.copy( bonesPosition[ i ] );
  92. }
  93. }
  94. }
  95. if ( options.preserveMatrix ) {
  96. // restore matrix
  97. target.updateMatrixWorld( true );
  98. }
  99. }
  100. function retargetClip( target, source, clip, options = {} ) {
  101. options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
  102. options.fps = options.fps !== undefined ? options.fps : 30;
  103. options.names = options.names || [];
  104. if ( ! source.isObject3D ) {
  105. source = getHelperFromSkeleton( source );
  106. }
  107. const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
  108. delta = 1 / options.fps,
  109. convertedTracks = [],
  110. mixer = new THREE.AnimationMixer( source ),
  111. bones = getBones( target.skeleton ),
  112. boneDatas = [];
  113. let positionOffset, bone, boneTo, boneData, name;
  114. mixer.clipAction( clip ).play();
  115. mixer.update( 0 );
  116. source.updateMatrixWorld();
  117. for ( let i = 0; i < numFrames; ++ i ) {
  118. const time = i * delta;
  119. retarget( target, source, options );
  120. for ( let j = 0; j < bones.length; ++ j ) {
  121. name = options.names[ bones[ j ].name ] || bones[ j ].name;
  122. boneTo = getBoneByName( name, source.skeleton );
  123. if ( boneTo ) {
  124. bone = bones[ j ];
  125. boneData = boneDatas[ j ] = boneDatas[ j ] || {
  126. bone: bone
  127. };
  128. if ( options.hip === name ) {
  129. if ( ! boneData.pos ) {
  130. boneData.pos = {
  131. times: new Float32Array( numFrames ),
  132. values: new Float32Array( numFrames * 3 )
  133. };
  134. }
  135. if ( options.useFirstFramePosition ) {
  136. if ( i === 0 ) {
  137. positionOffset = bone.position.clone();
  138. }
  139. bone.position.sub( positionOffset );
  140. }
  141. boneData.pos.times[ i ] = time;
  142. bone.position.toArray( boneData.pos.values, i * 3 );
  143. }
  144. if ( ! boneData.quat ) {
  145. boneData.quat = {
  146. times: new Float32Array( numFrames ),
  147. values: new Float32Array( numFrames * 4 )
  148. };
  149. }
  150. boneData.quat.times[ i ] = time;
  151. bone.quaternion.toArray( boneData.quat.values, i * 4 );
  152. }
  153. }
  154. mixer.update( delta );
  155. source.updateMatrixWorld();
  156. }
  157. for ( let i = 0; i < boneDatas.length; ++ i ) {
  158. boneData = boneDatas[ i ];
  159. if ( boneData ) {
  160. if ( boneData.pos ) {
  161. convertedTracks.push( new THREE.VectorKeyframeTrack( '.bones[' + boneData.bone.name + '].position', boneData.pos.times, boneData.pos.values ) );
  162. }
  163. convertedTracks.push( new THREE.QuaternionKeyframeTrack( '.bones[' + boneData.bone.name + '].quaternion', boneData.quat.times, boneData.quat.values ) );
  164. }
  165. }
  166. mixer.uncacheAction( clip );
  167. return new THREE.AnimationClip( clip.name, - 1, convertedTracks );
  168. }
  169. function getHelperFromSkeleton( skeleton ) {
  170. const source = new THREE.SkeletonHelper( skeleton.bones[ 0 ] );
  171. source.skeleton = skeleton;
  172. return source;
  173. }
  174. function getSkeletonOffsets( target, source, options = {} ) {
  175. const targetParentPos = new THREE.Vector3(),
  176. targetPos = new THREE.Vector3(),
  177. sourceParentPos = new THREE.Vector3(),
  178. sourcePos = new THREE.Vector3(),
  179. targetDir = new THREE.Vector2(),
  180. sourceDir = new THREE.Vector2();
  181. options.hip = options.hip !== undefined ? options.hip : 'hip';
  182. options.names = options.names || {};
  183. if ( ! source.isObject3D ) {
  184. source = getHelperFromSkeleton( source );
  185. }
  186. const nameKeys = Object.keys( options.names ),
  187. nameValues = Object.values( options.names ),
  188. sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  189. bones = target.isObject3D ? target.skeleton.bones : getBones( target ),
  190. offsets = [];
  191. let bone, boneTo, name, i;
  192. target.skeleton.pose();
  193. for ( i = 0; i < bones.length; ++ i ) {
  194. bone = bones[ i ];
  195. name = options.names[ bone.name ] || bone.name;
  196. boneTo = getBoneByName( name, sourceBones );
  197. if ( boneTo && name !== options.hip ) {
  198. const boneParent = getNearestBone( bone.parent, nameKeys ),
  199. boneToParent = getNearestBone( boneTo.parent, nameValues );
  200. boneParent.updateMatrixWorld();
  201. boneToParent.updateMatrixWorld();
  202. targetParentPos.setFromMatrixPosition( boneParent.matrixWorld );
  203. targetPos.setFromMatrixPosition( bone.matrixWorld );
  204. sourceParentPos.setFromMatrixPosition( boneToParent.matrixWorld );
  205. sourcePos.setFromMatrixPosition( boneTo.matrixWorld );
  206. targetDir.subVectors( new THREE.Vector2( targetPos.x, targetPos.y ), new THREE.Vector2( targetParentPos.x, targetParentPos.y ) ).normalize();
  207. sourceDir.subVectors( new THREE.Vector2( sourcePos.x, sourcePos.y ), new THREE.Vector2( sourceParentPos.x, sourceParentPos.y ) ).normalize();
  208. const laterialAngle = targetDir.angle() - sourceDir.angle();
  209. const offset = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler( 0, 0, laterialAngle ) );
  210. bone.matrix.multiply( offset );
  211. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  212. bone.updateMatrixWorld();
  213. offsets[ name ] = offset;
  214. }
  215. }
  216. return offsets;
  217. }
  218. function renameBones( skeleton, names ) {
  219. const bones = getBones( skeleton );
  220. for ( let i = 0; i < bones.length; ++ i ) {
  221. const bone = bones[ i ];
  222. if ( names[ bone.name ] ) {
  223. bone.name = names[ bone.name ];
  224. }
  225. }
  226. return this;
  227. }
  228. function getBones( skeleton ) {
  229. return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
  230. }
  231. function getBoneByName( name, skeleton ) {
  232. for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
  233. if ( name === bones[ i ].name ) return bones[ i ];
  234. }
  235. }
  236. function getNearestBone( bone, names ) {
  237. while ( bone.isBone ) {
  238. if ( names.indexOf( bone.name ) !== - 1 ) {
  239. return bone;
  240. }
  241. bone = bone.parent;
  242. }
  243. }
  244. function findBoneTrackData( name, tracks ) {
  245. const regexp = /\[(.*)\]\.(.*)/,
  246. result = {
  247. name: name
  248. };
  249. for ( let i = 0; i < tracks.length; ++ i ) {
  250. // 1 is track name
  251. // 2 is track type
  252. const trackData = regexp.exec( tracks[ i ].name );
  253. if ( trackData && name === trackData[ 1 ] ) {
  254. result[ trackData[ 2 ] ] = i;
  255. }
  256. }
  257. return result;
  258. }
  259. function getEqualsBonesNames( skeleton, targetSkeleton ) {
  260. const sourceBones = getBones( skeleton ),
  261. targetBones = getBones( targetSkeleton ),
  262. bones = [];
  263. search: for ( let i = 0; i < sourceBones.length; i ++ ) {
  264. const boneName = sourceBones[ i ].name;
  265. for ( let j = 0; j < targetBones.length; j ++ ) {
  266. if ( boneName === targetBones[ j ].name ) {
  267. bones.push( boneName );
  268. continue search;
  269. }
  270. }
  271. }
  272. return bones;
  273. }
  274. function clone( source ) {
  275. const sourceLookup = new Map();
  276. const cloneLookup = new Map();
  277. const clone = source.clone();
  278. parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
  279. sourceLookup.set( clonedNode, sourceNode );
  280. cloneLookup.set( sourceNode, clonedNode );
  281. } );
  282. clone.traverse( function ( node ) {
  283. if ( ! node.isSkinnedMesh ) return;
  284. const clonedMesh = node;
  285. const sourceMesh = sourceLookup.get( node );
  286. const sourceBones = sourceMesh.skeleton.bones;
  287. clonedMesh.skeleton = sourceMesh.skeleton.clone();
  288. clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
  289. clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
  290. return cloneLookup.get( bone );
  291. } );
  292. clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
  293. } );
  294. return clone;
  295. }
  296. function parallelTraverse( a, b, callback ) {
  297. callback( a, b );
  298. for ( let i = 0; i < a.children.length; i ++ ) {
  299. parallelTraverse( a.children[ i ], b.children[ i ], callback );
  300. }
  301. }
  302. THREE.SkeletonUtils = {};
  303. THREE.SkeletonUtils.clone = clone;
  304. THREE.SkeletonUtils.findBoneTrackData = findBoneTrackData;
  305. THREE.SkeletonUtils.getBoneByName = getBoneByName;
  306. THREE.SkeletonUtils.getBones = getBones;
  307. THREE.SkeletonUtils.getEqualsBonesNames = getEqualsBonesNames;
  308. THREE.SkeletonUtils.getHelperFromSkeleton = getHelperFromSkeleton;
  309. THREE.SkeletonUtils.getNearestBone = getNearestBone;
  310. THREE.SkeletonUtils.getSkeletonOffsets = getSkeletonOffsets;
  311. THREE.SkeletonUtils.renameBones = renameBones;
  312. THREE.SkeletonUtils.retarget = retarget;
  313. THREE.SkeletonUtils.retargetClip = retargetClip;
  314. } )();