SkeletonUtils.js 12 KB

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