CCDIKSolver.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. Line,
  6. LineBasicMaterial,
  7. Matrix4,
  8. Mesh,
  9. MeshBasicMaterial,
  10. Object3D,
  11. Quaternion,
  12. SphereGeometry,
  13. Vector3
  14. } from 'three';
  15. const _quaternion = new Quaternion();
  16. const _targetPos = new Vector3();
  17. const _targetVec = new Vector3();
  18. const _effectorPos = new Vector3();
  19. const _effectorVec = new Vector3();
  20. const _linkPos = new Vector3();
  21. const _invLinkQ = new Quaternion();
  22. const _linkScale = new Vector3();
  23. const _axis = new Vector3();
  24. const _vector = new Vector3();
  25. const _matrix = new Matrix4();
  26. /**
  27. * This class solves the Inverse Kinematics Problem with a [CCD Algorithm](https://web.archive.org/web/20221206080850/https://sites.google.com/site/auraliusproject/ccd-algorithm).
  28. *
  29. * `CCDIKSolver` is designed to work with instances of {@link SkinnedMesh}.
  30. *
  31. * @three_import import { CCDIKSolver } from 'three/addons/animation/CCDIKSolver.js';
  32. */
  33. class CCDIKSolver {
  34. /**
  35. * @param {SkinnedMesh} mesh - The skinned mesh.
  36. * @param {Array<CCDIKSolver~IK>} [iks=[]] - The IK objects.
  37. */
  38. constructor( mesh, iks = [] ) {
  39. /**
  40. * The skinned mesh.
  41. *
  42. * @type {SkinnedMesh}
  43. */
  44. this.mesh = mesh;
  45. /**
  46. * The IK objects.
  47. *
  48. * @type {Array<CCDIKSolver~IK>}
  49. */
  50. this.iks = iks;
  51. this._initialQuaternions = [];
  52. this._workingQuaternion = new Quaternion();
  53. for ( const ik of iks ) {
  54. const chainQuats = [];
  55. for ( let i = 0; i < ik.links.length; i ++ ) {
  56. chainQuats.push( new Quaternion() );
  57. }
  58. this._initialQuaternions.push( chainQuats );
  59. }
  60. this._valid();
  61. }
  62. /**
  63. * Updates all IK bones by solving the CCD algorithm.
  64. *
  65. * @param {number} [globalBlendFactor=1.0] - Blend factor applied if an IK chain doesn't have its own .blendFactor.
  66. * @return {CCDIKSolver} A reference to this instance.
  67. */
  68. update( globalBlendFactor = 1.0 ) {
  69. const iks = this.iks;
  70. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  71. this.updateOne( iks[ i ], globalBlendFactor );
  72. }
  73. return this;
  74. }
  75. /**
  76. * Updates one IK bone solving the CCD algorithm.
  77. *
  78. * @param {CCDIKSolver~IK} ik - The IK to update.
  79. * @param {number} [overrideBlend=1.0] - If the IK object does not define `blendFactor`, this value is used.
  80. * @return {CCDIKSolver} A reference to this instance.
  81. */
  82. updateOne( ik, overrideBlend = 1.0 ) {
  83. const chainBlend = ik.blendFactor !== undefined ? ik.blendFactor : overrideBlend;
  84. const bones = this.mesh.skeleton.bones;
  85. const chainIndex = this.iks.indexOf( ik );
  86. const initialQuaternions = this._initialQuaternions[ chainIndex ];
  87. // for reference overhead reduction in loop
  88. const math = Math;
  89. const effector = bones[ ik.effector ];
  90. const target = bones[ ik.target ];
  91. // don't use getWorldPosition() here for the performance
  92. // because it calls updateMatrixWorld( true ) inside.
  93. _targetPos.setFromMatrixPosition( target.matrixWorld );
  94. const links = ik.links;
  95. const iteration = ik.iteration !== undefined ? ik.iteration : 1;
  96. if ( chainBlend < 1.0 ) {
  97. for ( let j = 0; j < links.length; j ++ ) {
  98. const linkIndex = links[ j ].index;
  99. initialQuaternions[ j ].copy( bones[ linkIndex ].quaternion );
  100. }
  101. }
  102. for ( let i = 0; i < iteration; i ++ ) {
  103. let rotated = false;
  104. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  105. const link = bones[ links[ j ].index ];
  106. // skip this link and following links
  107. if ( links[ j ].enabled === false ) break;
  108. const limitation = links[ j ].limitation;
  109. const rotationMin = links[ j ].rotationMin;
  110. const rotationMax = links[ j ].rotationMax;
  111. // don't use getWorldPosition/Quaternion() here for the performance
  112. // because they call updateMatrixWorld( true ) inside.
  113. link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale );
  114. _invLinkQ.invert();
  115. _effectorPos.setFromMatrixPosition( effector.matrixWorld );
  116. // work in link world
  117. _effectorVec.subVectors( _effectorPos, _linkPos );
  118. _effectorVec.applyQuaternion( _invLinkQ );
  119. _effectorVec.normalize();
  120. _targetVec.subVectors( _targetPos, _linkPos );
  121. _targetVec.applyQuaternion( _invLinkQ );
  122. _targetVec.normalize();
  123. let angle = _targetVec.dot( _effectorVec );
  124. if ( angle > 1.0 ) {
  125. angle = 1.0;
  126. } else if ( angle < - 1.0 ) {
  127. angle = - 1.0;
  128. }
  129. angle = math.acos( angle );
  130. // skip if changing angle is too small to prevent vibration of bone
  131. if ( angle < 1e-5 ) continue;
  132. if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
  133. angle = ik.minAngle;
  134. }
  135. if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
  136. angle = ik.maxAngle;
  137. }
  138. _axis.crossVectors( _effectorVec, _targetVec );
  139. _axis.normalize();
  140. _quaternion.setFromAxisAngle( _axis, angle );
  141. link.quaternion.multiply( _quaternion );
  142. // TODO: re-consider the limitation specification
  143. if ( limitation !== undefined ) {
  144. let c = link.quaternion.w;
  145. if ( c > 1.0 ) c = 1.0;
  146. // preserve sign of the rotation along the limitation axis,
  147. // otherwise negative rotations get mirrored to positive
  148. const dot = link.quaternion.x * limitation.x + link.quaternion.y * limitation.y + link.quaternion.z * limitation.z;
  149. const sign = dot < 0 ? - 1 : 1;
  150. const c2 = sign * math.sqrt( 1 - c * c );
  151. link.quaternion.set( limitation.x * c2,
  152. limitation.y * c2,
  153. limitation.z * c2,
  154. c );
  155. }
  156. if ( rotationMin !== undefined ) {
  157. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).max( rotationMin ) );
  158. }
  159. if ( rotationMax !== undefined ) {
  160. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).min( rotationMax ) );
  161. }
  162. link.updateMatrixWorld( true );
  163. rotated = true;
  164. }
  165. if ( ! rotated ) break;
  166. }
  167. if ( chainBlend < 1.0 ) {
  168. for ( let j = 0; j < links.length; j ++ ) {
  169. const linkIndex = links[ j ].index;
  170. const link = bones[ linkIndex ];
  171. this._workingQuaternion.copy( initialQuaternions[ j ] ).slerp( link.quaternion, chainBlend );
  172. link.quaternion.copy( this._workingQuaternion );
  173. link.updateMatrixWorld( true );
  174. }
  175. }
  176. return this;
  177. }
  178. /**
  179. * Creates a helper for visualizing the CCDIK.
  180. *
  181. * @param {number} sphereSize - The sphere size.
  182. * @return {CCDIKHelper} The created helper.
  183. */
  184. createHelper( sphereSize ) {
  185. return new CCDIKHelper( this.mesh, this.iks, sphereSize );
  186. }
  187. // private methods
  188. _valid() {
  189. const iks = this.iks;
  190. const bones = this.mesh.skeleton.bones;
  191. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  192. const ik = iks[ i ];
  193. const effector = bones[ ik.effector ];
  194. const links = ik.links;
  195. let link0, link1;
  196. link0 = effector;
  197. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  198. link1 = bones[ links[ j ].index ];
  199. if ( link0.parent !== link1 ) {
  200. console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
  201. }
  202. link0 = link1;
  203. }
  204. }
  205. }
  206. }
  207. function getPosition( bone, matrixWorldInv ) {
  208. return _vector
  209. .setFromMatrixPosition( bone.matrixWorld )
  210. .applyMatrix4( matrixWorldInv );
  211. }
  212. function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
  213. const v = getPosition( bone, matrixWorldInv );
  214. array[ index * 3 + 0 ] = v.x;
  215. array[ index * 3 + 1 ] = v.y;
  216. array[ index * 3 + 2 ] = v.z;
  217. }
  218. /**
  219. * Helper for visualizing IK bones.
  220. *
  221. * @augments Object3D
  222. * @three_import import { CCDIKHelper } from 'three/addons/animation/CCDIKSolver.js';
  223. */
  224. class CCDIKHelper extends Object3D {
  225. /**
  226. * @param {SkinnedMesh} mesh - The skinned mesh.
  227. * @param {Array<CCDIKSolver~IK>} [iks=[]] - The IK objects.
  228. * @param {number} [sphereSize=0.25] - The sphere size.
  229. */
  230. constructor( mesh, iks = [], sphereSize = 0.25 ) {
  231. super();
  232. /**
  233. * The skinned mesh this helper refers to.
  234. *
  235. * @type {SkinnedMesh}
  236. */
  237. this.root = mesh;
  238. /**
  239. * The IK objects.
  240. *
  241. * @type {Array<CCDIKSolver~IK>}
  242. */
  243. this.iks = iks;
  244. this.matrix.copy( mesh.matrixWorld );
  245. this.matrixAutoUpdate = false;
  246. /**
  247. * The helpers sphere geometry.
  248. *
  249. * @type {SphereGeometry}
  250. */
  251. this.sphereGeometry = new SphereGeometry( sphereSize, 16, 8 );
  252. /**
  253. * The material for the target spheres.
  254. *
  255. * @type {MeshBasicMaterial}
  256. */
  257. this.targetSphereMaterial = new MeshBasicMaterial( {
  258. color: new Color( 0xff8888 ),
  259. depthTest: false,
  260. depthWrite: false,
  261. transparent: true
  262. } );
  263. /**
  264. * The material for the effector spheres.
  265. *
  266. * @type {MeshBasicMaterial}
  267. */
  268. this.effectorSphereMaterial = new MeshBasicMaterial( {
  269. color: new Color( 0x88ff88 ),
  270. depthTest: false,
  271. depthWrite: false,
  272. transparent: true
  273. } );
  274. /**
  275. * The material for the link spheres.
  276. *
  277. * @type {MeshBasicMaterial}
  278. */
  279. this.linkSphereMaterial = new MeshBasicMaterial( {
  280. color: new Color( 0x8888ff ),
  281. depthTest: false,
  282. depthWrite: false,
  283. transparent: true
  284. } );
  285. /**
  286. * A global line material.
  287. *
  288. * @type {LineBasicMaterial}
  289. */
  290. this.lineMaterial = new LineBasicMaterial( {
  291. color: new Color( 0xff0000 ),
  292. depthTest: false,
  293. depthWrite: false,
  294. transparent: true
  295. } );
  296. this._init();
  297. }
  298. updateMatrixWorld( force ) {
  299. const mesh = this.root;
  300. if ( this.visible ) {
  301. let offset = 0;
  302. const iks = this.iks;
  303. const bones = mesh.skeleton.bones;
  304. _matrix.copy( mesh.matrixWorld ).invert();
  305. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  306. const ik = iks[ i ];
  307. const targetBone = bones[ ik.target ];
  308. const effectorBone = bones[ ik.effector ];
  309. const targetMesh = this.children[ offset ++ ];
  310. const effectorMesh = this.children[ offset ++ ];
  311. targetMesh.position.copy( getPosition( targetBone, _matrix ) );
  312. effectorMesh.position.copy( getPosition( effectorBone, _matrix ) );
  313. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  314. const link = ik.links[ j ];
  315. const linkBone = bones[ link.index ];
  316. const linkMesh = this.children[ offset ++ ];
  317. linkMesh.position.copy( getPosition( linkBone, _matrix ) );
  318. }
  319. const line = this.children[ offset ++ ];
  320. const array = line.geometry.attributes.position.array;
  321. setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix );
  322. setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix );
  323. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  324. const link = ik.links[ j ];
  325. const linkBone = bones[ link.index ];
  326. setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix );
  327. }
  328. line.geometry.attributes.position.needsUpdate = true;
  329. }
  330. }
  331. this.matrix.copy( mesh.matrixWorld );
  332. super.updateMatrixWorld( force );
  333. }
  334. /**
  335. * Frees the GPU-related resources allocated by this instance.
  336. * Call this method whenever this instance is no longer used in your app.
  337. */
  338. dispose() {
  339. this.sphereGeometry.dispose();
  340. this.targetSphereMaterial.dispose();
  341. this.effectorSphereMaterial.dispose();
  342. this.linkSphereMaterial.dispose();
  343. this.lineMaterial.dispose();
  344. const children = this.children;
  345. for ( let i = 0; i < children.length; i ++ ) {
  346. const child = children[ i ];
  347. if ( child.isLine ) child.geometry.dispose();
  348. }
  349. }
  350. // private method
  351. _init() {
  352. const scope = this;
  353. const iks = this.iks;
  354. function createLineGeometry( ik ) {
  355. const geometry = new BufferGeometry();
  356. const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
  357. geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  358. return geometry;
  359. }
  360. function createTargetMesh() {
  361. return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial );
  362. }
  363. function createEffectorMesh() {
  364. return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial );
  365. }
  366. function createLinkMesh() {
  367. return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial );
  368. }
  369. function createLine( ik ) {
  370. return new Line( createLineGeometry( ik ), scope.lineMaterial );
  371. }
  372. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  373. const ik = iks[ i ];
  374. this.add( createTargetMesh() );
  375. this.add( createEffectorMesh() );
  376. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  377. this.add( createLinkMesh() );
  378. }
  379. this.add( createLine( ik ) );
  380. }
  381. }
  382. }
  383. /**
  384. * This type represents IK configuration objects.
  385. *
  386. * @typedef {Object} CCDIKSolver~IK
  387. * @property {number} target - The target bone index which refers to a bone in the `Skeleton.bones` array.
  388. * @property {number} effector - The effector bone index which refers to a bone in the `Skeleton.bones` array.
  389. * @property {Array<CCDIKSolver~BoneLink>} links - An array of bone links.
  390. * @property {number} [iteration=1] - Iteration number of calculation. Smaller is faster but less precise.
  391. * @property {number} [minAngle] - Minimum rotation angle in a step in radians.
  392. * @property {number} [maxAngle] - Minimum rotation angle in a step in radians.
  393. * @property {number} [blendFactor] - The blend factor.
  394. **/
  395. /**
  396. * This type represents bone links.
  397. *
  398. * @typedef {Object} CCDIKSolver~BoneLink
  399. * @property {number} index - The index of a linked bone which refers to a bone in the `Skeleton.bones` array.
  400. * @property {number} [limitation] - Rotation axis.
  401. * @property {number} [rotationMin] - Rotation minimum limit.
  402. * @property {number} [rotationMax] - Rotation maximum limit.
  403. * @property {boolean} [enabled=true] - Whether the link is enabled or not.
  404. **/
  405. export { CCDIKSolver, CCDIKHelper };
粤ICP备19079148号