SkeletonUtils.js 11 KB

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