SkeletonUtils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. import {
  2. AnimationClip,
  3. AnimationMixer,
  4. Euler,
  5. Matrix4,
  6. Quaternion,
  7. QuaternionKeyframeTrack,
  8. SkeletonHelper,
  9. Vector2,
  10. Vector3,
  11. VectorKeyframeTrack
  12. } from 'three';
  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[ 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 + 1 ),
  149. values: new Float32Array( ( numFrames + 1 ) * 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. // `numFrames + 1` accomodate final keyframe
  163. boneData.quat = {
  164. times: new Float32Array( numFrames + 1 ),
  165. values: new Float32Array( ( numFrames + 1 ) * 4 )
  166. };
  167. }
  168. boneData.quat.times[ i ] = time;
  169. bone.quaternion.toArray( boneData.quat.values, i * 4 );
  170. }
  171. }
  172. // check for final keyframe
  173. if ( i === numFrames - 1 ) {
  174. mixer.update( Math.max( clip.duration - mixer.time, 0 ) );
  175. } else {
  176. mixer.update( delta );
  177. }
  178. source.updateMatrixWorld();
  179. }
  180. retarget( target, source, options );
  181. // add boneData at final keyframe
  182. for ( let j = 0; j < boneDatas.length; ++ j ) {
  183. boneData = boneDatas[ j ];
  184. if ( boneData ) {
  185. if ( boneData.pos ) {
  186. boneData.pos.times[ numFrames ] = clip.duration;
  187. bone.position.toArray( boneData.pos.values, numFrames * 3 );
  188. }
  189. if ( boneData.quat ) {
  190. boneData.quat.times[ numFrames ] = clip.duration;
  191. bone.position.toArray( boneData.quat.values, numFrames * 4 );
  192. }
  193. }
  194. }
  195. for ( let i = 0; i < boneDatas.length; ++ i ) {
  196. boneData = boneDatas[ i ];
  197. if ( boneData ) {
  198. if ( boneData.pos ) {
  199. convertedTracks.push( new VectorKeyframeTrack(
  200. '.bones[' + boneData.bone.name + '].position',
  201. boneData.pos.times,
  202. boneData.pos.values
  203. ) );
  204. }
  205. convertedTracks.push( new QuaternionKeyframeTrack(
  206. '.bones[' + boneData.bone.name + '].quaternion',
  207. boneData.quat.times,
  208. boneData.quat.values
  209. ) );
  210. }
  211. }
  212. mixer.uncacheAction( clip );
  213. return new AnimationClip( clip.name, - 1, convertedTracks );
  214. }
  215. function getHelperFromSkeleton( skeleton ) {
  216. const source = new SkeletonHelper( skeleton.bones[ 0 ] );
  217. source.skeleton = skeleton;
  218. return source;
  219. }
  220. function getSkeletonOffsets( target, source, options = {} ) {
  221. const targetParentPos = new Vector3(),
  222. targetPos = new Vector3(),
  223. sourceParentPos = new Vector3(),
  224. sourcePos = new Vector3(),
  225. targetDir = new Vector2(),
  226. sourceDir = new Vector2();
  227. options.hip = options.hip !== undefined ? options.hip : 'hip';
  228. options.names = options.names || {};
  229. if ( ! source.isObject3D ) {
  230. source = getHelperFromSkeleton( source );
  231. }
  232. const nameKeys = Object.keys( options.names ),
  233. nameValues = Object.values( options.names ),
  234. sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
  235. bones = target.isObject3D ? target.skeleton.bones : getBones( target ),
  236. offsets = [];
  237. let bone, boneTo,
  238. name, i;
  239. target.skeleton.pose();
  240. for ( i = 0; i < bones.length; ++ i ) {
  241. bone = bones[ i ];
  242. name = options.names[ bone.name ] || bone.name;
  243. boneTo = getBoneByName( name, sourceBones );
  244. if ( boneTo && name !== options.hip ) {
  245. const boneParent = getNearestBone( bone.parent, nameKeys ),
  246. boneToParent = getNearestBone( boneTo.parent, nameValues );
  247. boneParent.updateMatrixWorld();
  248. boneToParent.updateMatrixWorld();
  249. targetParentPos.setFromMatrixPosition( boneParent.matrixWorld );
  250. targetPos.setFromMatrixPosition( bone.matrixWorld );
  251. sourceParentPos.setFromMatrixPosition( boneToParent.matrixWorld );
  252. sourcePos.setFromMatrixPosition( boneTo.matrixWorld );
  253. targetDir.subVectors(
  254. new Vector2( targetPos.x, targetPos.y ),
  255. new Vector2( targetParentPos.x, targetParentPos.y )
  256. ).normalize();
  257. sourceDir.subVectors(
  258. new Vector2( sourcePos.x, sourcePos.y ),
  259. new Vector2( sourceParentPos.x, sourceParentPos.y )
  260. ).normalize();
  261. const laterialAngle = targetDir.angle() - sourceDir.angle();
  262. const offset = new Matrix4().makeRotationFromEuler(
  263. new Euler(
  264. 0,
  265. 0,
  266. laterialAngle
  267. )
  268. );
  269. bone.matrix.multiply( offset );
  270. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  271. bone.updateMatrixWorld();
  272. offsets[ name ] = offset;
  273. }
  274. }
  275. return offsets;
  276. }
  277. function renameBones( skeleton, names ) {
  278. const bones = getBones( skeleton );
  279. for ( let i = 0; i < bones.length; ++ i ) {
  280. const bone = bones[ i ];
  281. if ( names[ bone.name ] ) {
  282. bone.name = names[ bone.name ];
  283. }
  284. }
  285. return this;
  286. }
  287. function getBones( skeleton ) {
  288. return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
  289. }
  290. function getBoneByName( name, skeleton ) {
  291. for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
  292. if ( name === bones[ i ].name )
  293. return bones[ i ];
  294. }
  295. }
  296. function getNearestBone( bone, names ) {
  297. while ( bone.isBone ) {
  298. if ( names.indexOf( bone.name ) !== - 1 ) {
  299. return bone;
  300. }
  301. bone = bone.parent;
  302. }
  303. }
  304. function findBoneTrackData( name, tracks ) {
  305. const regexp = /\[(.*)\]\.(.*)/,
  306. result = { name: name };
  307. for ( let i = 0; i < tracks.length; ++ i ) {
  308. // 1 is track name
  309. // 2 is track type
  310. const trackData = regexp.exec( tracks[ i ].name );
  311. if ( trackData && name === trackData[ 1 ] ) {
  312. result[ trackData[ 2 ] ] = i;
  313. }
  314. }
  315. return result;
  316. }
  317. function getEqualsBonesNames( skeleton, targetSkeleton ) {
  318. const sourceBones = getBones( skeleton ),
  319. targetBones = getBones( targetSkeleton ),
  320. bones = [];
  321. search : for ( let i = 0; i < sourceBones.length; i ++ ) {
  322. const boneName = sourceBones[ i ].name;
  323. for ( let j = 0; j < targetBones.length; j ++ ) {
  324. if ( boneName === targetBones[ j ].name ) {
  325. bones.push( boneName );
  326. continue search;
  327. }
  328. }
  329. }
  330. return bones;
  331. }
  332. function clone( source ) {
  333. const sourceLookup = new Map();
  334. const cloneLookup = new Map();
  335. const clone = source.clone();
  336. parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
  337. sourceLookup.set( clonedNode, sourceNode );
  338. cloneLookup.set( sourceNode, clonedNode );
  339. } );
  340. clone.traverse( function ( node ) {
  341. if ( ! node.isSkinnedMesh ) return;
  342. const clonedMesh = node;
  343. const sourceMesh = sourceLookup.get( node );
  344. const sourceBones = sourceMesh.skeleton.bones;
  345. clonedMesh.skeleton = sourceMesh.skeleton.clone();
  346. clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
  347. clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
  348. return cloneLookup.get( bone );
  349. } );
  350. clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
  351. } );
  352. return clone;
  353. }
  354. function parallelTraverse( a, b, callback ) {
  355. callback( a, b );
  356. for ( let i = 0; i < a.children.length; i ++ ) {
  357. parallelTraverse( a.children[ i ], b.children[ i ], callback );
  358. }
  359. }
  360. export {
  361. retarget,
  362. retargetClip,
  363. getHelperFromSkeleton,
  364. getSkeletonOffsets,
  365. renameBones,
  366. getBones,
  367. getBoneByName,
  368. getNearestBone,
  369. findBoneTrackData,
  370. getEqualsBonesNames,
  371. clone,
  372. };