CCDIKSolver.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. * @return {CCDIKHelper}
  152. */
  153. createHelper() {
  154. return new CCDIKHelper( this.mesh, this.mesh.geometry.userData.MMD.iks );
  155. }
  156. // private methods
  157. _valid() {
  158. const iks = this.iks;
  159. const bones = this.mesh.skeleton.bones;
  160. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  161. const ik = iks[ i ];
  162. const effector = bones[ ik.effector ];
  163. const links = ik.links;
  164. let link0, link1;
  165. link0 = effector;
  166. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  167. link1 = bones[ links[ j ].index ];
  168. if ( link0.parent !== link1 ) {
  169. console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
  170. }
  171. link0 = link1;
  172. }
  173. }
  174. }
  175. }
  176. function getPosition( bone, matrixWorldInv ) {
  177. return _vector
  178. .setFromMatrixPosition( bone.matrixWorld )
  179. .applyMatrix4( matrixWorldInv );
  180. }
  181. function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
  182. const v = getPosition( bone, matrixWorldInv );
  183. array[ index * 3 + 0 ] = v.x;
  184. array[ index * 3 + 1 ] = v.y;
  185. array[ index * 3 + 2 ] = v.z;
  186. }
  187. /**
  188. * Visualize IK bones
  189. *
  190. * @param {SkinnedMesh} mesh
  191. * @param {Array<Object>} iks
  192. */
  193. class CCDIKHelper extends Object3D {
  194. constructor( mesh, iks = [] ) {
  195. super();
  196. this.root = mesh;
  197. this.iks = iks;
  198. this.matrix.copy( mesh.matrixWorld );
  199. this.matrixAutoUpdate = false;
  200. this.sphereGeometry = new SphereGeometry( 0.25, 16, 8 );
  201. this.targetSphereMaterial = new MeshBasicMaterial( {
  202. color: new Color( 0xff8888 ),
  203. depthTest: false,
  204. depthWrite: false,
  205. transparent: true
  206. } );
  207. this.effectorSphereMaterial = new MeshBasicMaterial( {
  208. color: new Color( 0x88ff88 ),
  209. depthTest: false,
  210. depthWrite: false,
  211. transparent: true
  212. } );
  213. this.linkSphereMaterial = new MeshBasicMaterial( {
  214. color: new Color( 0x8888ff ),
  215. depthTest: false,
  216. depthWrite: false,
  217. transparent: true
  218. } );
  219. this.lineMaterial = new LineBasicMaterial( {
  220. color: new Color( 0xff0000 ),
  221. depthTest: false,
  222. depthWrite: false,
  223. transparent: true
  224. } );
  225. this._init();
  226. }
  227. /**
  228. * Updates IK bones visualization.
  229. */
  230. updateMatrixWorld( force ) {
  231. const mesh = this.root;
  232. if ( this.visible ) {
  233. let offset = 0;
  234. const iks = this.iks;
  235. const bones = mesh.skeleton.bones;
  236. _matrix.copy( mesh.matrixWorld ).invert();
  237. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  238. const ik = iks[ i ];
  239. const targetBone = bones[ ik.target ];
  240. const effectorBone = bones[ ik.effector ];
  241. const targetMesh = this.children[ offset ++ ];
  242. const effectorMesh = this.children[ offset ++ ];
  243. targetMesh.position.copy( getPosition( targetBone, _matrix ) );
  244. effectorMesh.position.copy( getPosition( effectorBone, _matrix ) );
  245. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  246. const link = ik.links[ j ];
  247. const linkBone = bones[ link.index ];
  248. const linkMesh = this.children[ offset ++ ];
  249. linkMesh.position.copy( getPosition( linkBone, _matrix ) );
  250. }
  251. const line = this.children[ offset ++ ];
  252. const array = line.geometry.attributes.position.array;
  253. setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix );
  254. setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix );
  255. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  256. const link = ik.links[ j ];
  257. const linkBone = bones[ link.index ];
  258. setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix );
  259. }
  260. line.geometry.attributes.position.needsUpdate = true;
  261. }
  262. }
  263. this.matrix.copy( mesh.matrixWorld );
  264. super.updateMatrixWorld( force );
  265. }
  266. // private method
  267. _init() {
  268. const scope = this;
  269. const iks = this.iks;
  270. function createLineGeometry( ik ) {
  271. const geometry = new BufferGeometry();
  272. const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
  273. geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  274. return geometry;
  275. }
  276. function createTargetMesh() {
  277. return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial );
  278. }
  279. function createEffectorMesh() {
  280. return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial );
  281. }
  282. function createLinkMesh() {
  283. return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial );
  284. }
  285. function createLine( ik ) {
  286. return new Line( createLineGeometry( ik ), scope.lineMaterial );
  287. }
  288. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  289. const ik = iks[ i ];
  290. this.add( createTargetMesh() );
  291. this.add( createEffectorMesh() );
  292. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  293. this.add( createLinkMesh() );
  294. }
  295. this.add( createLine( ik ) );
  296. }
  297. }
  298. }
  299. export { CCDIKSolver, CCDIKHelper };