CCDIKSolver.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 _q = 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. * CCD Algorithm
  28. * - https://sites.google.com/site/auraliusproject/ccd-algorithm
  29. *
  30. * // ik parameter example
  31. * //
  32. * // target, effector, index in links are bone index in skeleton.bones.
  33. * // the bones relation should be
  34. * // <-- parent child -->
  35. * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector
  36. * iks = [ {
  37. * target: 1,
  38. * effector: 2,
  39. * links: [ { index: 5, limitation: new Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ],
  40. * iteration: 10,
  41. * minAngle: 0.0,
  42. * maxAngle: 1.0,
  43. * } ];
  44. */
  45. class CCDIKSolver {
  46. /**
  47. * @param {THREE.SkinnedMesh} mesh
  48. * @param {Array<Object>} iks
  49. */
  50. constructor( mesh, iks = [] ) {
  51. this.mesh = mesh;
  52. this.iks = iks;
  53. this._valid();
  54. }
  55. /**
  56. * Update all IK bones.
  57. *
  58. * @return {CCDIKSolver}
  59. */
  60. update() {
  61. const iks = this.iks;
  62. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  63. this.updateOne( iks[ i ] );
  64. }
  65. return this;
  66. }
  67. /**
  68. * Update one IK bone
  69. *
  70. * @param {Object} ik parameter
  71. * @return {CCDIKSolver}
  72. */
  73. updateOne( ik ) {
  74. const bones = this.mesh.skeleton.bones;
  75. // for reference overhead reduction in loop
  76. const math = Math;
  77. const effector = bones[ ik.effector ];
  78. const target = bones[ ik.target ];
  79. // don't use getWorldPosition() here for the performance
  80. // because it calls updateMatrixWorld( true ) inside.
  81. _targetPos.setFromMatrixPosition( target.matrixWorld );
  82. const links = ik.links;
  83. const iteration = ik.iteration !== undefined ? ik.iteration : 1;
  84. for ( let i = 0; i < iteration; i ++ ) {
  85. let rotated = false;
  86. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  87. const link = bones[ links[ j ].index ];
  88. // skip this link and following links.
  89. // this skip is used for MMD performance optimization.
  90. if ( links[ j ].enabled === false ) break;
  91. const limitation = links[ j ].limitation;
  92. const rotationMin = links[ j ].rotationMin;
  93. const rotationMax = links[ j ].rotationMax;
  94. // don't use getWorldPosition/Quaternion() here for the performance
  95. // because they call updateMatrixWorld( true ) inside.
  96. link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale );
  97. _invLinkQ.invert();
  98. _effectorPos.setFromMatrixPosition( effector.matrixWorld );
  99. // work in link world
  100. _effectorVec.subVectors( _effectorPos, _linkPos );
  101. _effectorVec.applyQuaternion( _invLinkQ );
  102. _effectorVec.normalize();
  103. _targetVec.subVectors( _targetPos, _linkPos );
  104. _targetVec.applyQuaternion( _invLinkQ );
  105. _targetVec.normalize();
  106. let angle = _targetVec.dot( _effectorVec );
  107. if ( angle > 1.0 ) {
  108. angle = 1.0;
  109. } else if ( angle < - 1.0 ) {
  110. angle = - 1.0;
  111. }
  112. angle = math.acos( angle );
  113. // skip if changing angle is too small to prevent vibration of bone
  114. if ( angle < 1e-5 ) continue;
  115. if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
  116. angle = ik.minAngle;
  117. }
  118. if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
  119. angle = ik.maxAngle;
  120. }
  121. _axis.crossVectors( _effectorVec, _targetVec );
  122. _axis.normalize();
  123. _q.setFromAxisAngle( _axis, angle );
  124. link.quaternion.multiply( _q );
  125. // TODO: re-consider the limitation specification
  126. if ( limitation !== undefined ) {
  127. let c = link.quaternion.w;
  128. if ( c > 1.0 ) c = 1.0;
  129. const c2 = math.sqrt( 1 - c * c );
  130. link.quaternion.set( limitation.x * c2,
  131. limitation.y * c2,
  132. limitation.z * c2,
  133. c );
  134. }
  135. if ( rotationMin !== undefined ) {
  136. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).max( rotationMin ) );
  137. }
  138. if ( rotationMax !== undefined ) {
  139. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).min( rotationMax ) );
  140. }
  141. link.updateMatrixWorld( true );
  142. rotated = true;
  143. }
  144. if ( ! rotated ) break;
  145. }
  146. return this;
  147. }
  148. /**
  149. * Creates Helper
  150. *
  151. * @param {number} sphereSize
  152. * @return {CCDIKHelper}
  153. */
  154. createHelper( sphereSize ) {
  155. return new CCDIKHelper( this.mesh, this.iks, sphereSize );
  156. }
  157. // private methods
  158. _valid() {
  159. const iks = this.iks;
  160. const bones = this.mesh.skeleton.bones;
  161. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  162. const ik = iks[ i ];
  163. const effector = bones[ ik.effector ];
  164. const links = ik.links;
  165. let link0, link1;
  166. link0 = effector;
  167. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  168. link1 = bones[ links[ j ].index ];
  169. if ( link0.parent !== link1 ) {
  170. console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
  171. }
  172. link0 = link1;
  173. }
  174. }
  175. }
  176. }
  177. function getPosition( bone, matrixWorldInv ) {
  178. return _vector
  179. .setFromMatrixPosition( bone.matrixWorld )
  180. .applyMatrix4( matrixWorldInv );
  181. }
  182. function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
  183. const v = getPosition( bone, matrixWorldInv );
  184. array[ index * 3 + 0 ] = v.x;
  185. array[ index * 3 + 1 ] = v.y;
  186. array[ index * 3 + 2 ] = v.z;
  187. }
  188. /**
  189. * Visualize IK bones
  190. *
  191. * @param {SkinnedMesh} mesh
  192. * @param {Array<Object>} iks
  193. * @param {number} sphereSize
  194. */
  195. class CCDIKHelper extends Object3D {
  196. constructor( mesh, iks = [], sphereSize = 0.25 ) {
  197. super();
  198. this.root = mesh;
  199. this.iks = iks;
  200. this.matrix.copy( mesh.matrixWorld );
  201. this.matrixAutoUpdate = false;
  202. this.sphereGeometry = new SphereGeometry( sphereSize, 16, 8 );
  203. this.targetSphereMaterial = new MeshBasicMaterial( {
  204. color: new Color( 0xff8888 ),
  205. depthTest: false,
  206. depthWrite: false,
  207. transparent: true
  208. } );
  209. this.effectorSphereMaterial = new MeshBasicMaterial( {
  210. color: new Color( 0x88ff88 ),
  211. depthTest: false,
  212. depthWrite: false,
  213. transparent: true
  214. } );
  215. this.linkSphereMaterial = new MeshBasicMaterial( {
  216. color: new Color( 0x8888ff ),
  217. depthTest: false,
  218. depthWrite: false,
  219. transparent: true
  220. } );
  221. this.lineMaterial = new LineBasicMaterial( {
  222. color: new Color( 0xff0000 ),
  223. depthTest: false,
  224. depthWrite: false,
  225. transparent: true
  226. } );
  227. this._init();
  228. }
  229. /**
  230. * Updates IK bones visualization.
  231. */
  232. updateMatrixWorld( force ) {
  233. const mesh = this.root;
  234. if ( this.visible ) {
  235. let offset = 0;
  236. const iks = this.iks;
  237. const bones = mesh.skeleton.bones;
  238. _matrix.copy( mesh.matrixWorld ).invert();
  239. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  240. const ik = iks[ i ];
  241. const targetBone = bones[ ik.target ];
  242. const effectorBone = bones[ ik.effector ];
  243. const targetMesh = this.children[ offset ++ ];
  244. const effectorMesh = this.children[ offset ++ ];
  245. targetMesh.position.copy( getPosition( targetBone, _matrix ) );
  246. effectorMesh.position.copy( getPosition( effectorBone, _matrix ) );
  247. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  248. const link = ik.links[ j ];
  249. const linkBone = bones[ link.index ];
  250. const linkMesh = this.children[ offset ++ ];
  251. linkMesh.position.copy( getPosition( linkBone, _matrix ) );
  252. }
  253. const line = this.children[ offset ++ ];
  254. const array = line.geometry.attributes.position.array;
  255. setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix );
  256. setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix );
  257. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  258. const link = ik.links[ j ];
  259. const linkBone = bones[ link.index ];
  260. setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix );
  261. }
  262. line.geometry.attributes.position.needsUpdate = true;
  263. }
  264. }
  265. this.matrix.copy( mesh.matrixWorld );
  266. super.updateMatrixWorld( force );
  267. }
  268. /**
  269. * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.
  270. */
  271. dispose() {
  272. this.sphereGeometry.dispose();
  273. this.targetSphereMaterial.dispose();
  274. this.effectorSphereMaterial.dispose();
  275. this.linkSphereMaterial.dispose();
  276. this.lineMaterial.dispose();
  277. const children = this.children;
  278. for ( let i = 0; i < children.length; i ++ ) {
  279. const child = children[ i ];
  280. if ( child.isLine ) child.geometry.dispose();
  281. }
  282. }
  283. // private method
  284. _init() {
  285. const scope = this;
  286. const iks = this.iks;
  287. function createLineGeometry( ik ) {
  288. const geometry = new BufferGeometry();
  289. const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
  290. geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  291. return geometry;
  292. }
  293. function createTargetMesh() {
  294. return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial );
  295. }
  296. function createEffectorMesh() {
  297. return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial );
  298. }
  299. function createLinkMesh() {
  300. return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial );
  301. }
  302. function createLine( ik ) {
  303. return new Line( createLineGeometry( ik ), scope.lineMaterial );
  304. }
  305. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  306. const ik = iks[ i ];
  307. this.add( createTargetMesh() );
  308. this.add( createEffectorMesh() );
  309. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  310. this.add( createLinkMesh() );
  311. }
  312. this.add( createLine( ik ) );
  313. }
  314. }
  315. }
  316. export { CCDIKSolver, CCDIKHelper };