CCDIKSolver.js 9.8 KB

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