MMDPhysics.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  1. import {
  2. Bone,
  3. BoxGeometry,
  4. Color,
  5. CylinderGeometry,
  6. Euler,
  7. Matrix4,
  8. Mesh,
  9. MeshBasicMaterial,
  10. Object3D,
  11. Quaternion,
  12. SphereGeometry,
  13. Vector3
  14. } from '../../../build/three.module.js';
  15. /**
  16. * Dependencies
  17. * - Ammo.js https://github.com/kripken/ammo.js
  18. *
  19. * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine)
  20. * for MMD model loaded by MMDLoader.
  21. *
  22. * TODO
  23. * - Physics in Worker
  24. */
  25. /* global Ammo */
  26. class MMDPhysics {
  27. /**
  28. * @param {THREE.SkinnedMesh} mesh
  29. * @param {Array<Object>} rigidBodyParams
  30. * @param {Array<Object>} (optional) constraintParams
  31. * @param {Object} params - (optional)
  32. * @param {Number} params.unitStep - Default is 1 / 65.
  33. * @param {Integer} params.maxStepNum - Default is 3.
  34. * @param {Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 )
  35. */
  36. constructor( mesh, rigidBodyParams, constraintParams = [], params = {} ) {
  37. if ( typeof Ammo === 'undefined' ) {
  38. throw new Error( 'THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js' );
  39. }
  40. this.manager = new ResourceManager();
  41. this.mesh = mesh;
  42. /*
  43. * I don't know why but 1/60 unitStep easily breaks models
  44. * so I set it 1/65 so far.
  45. * Don't set too small unitStep because
  46. * the smaller unitStep can make the performance worse.
  47. */
  48. this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65;
  49. this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3;
  50. this.gravity = new Vector3( 0, - 9.8 * 10, 0 );
  51. if ( params.gravity !== undefined ) this.gravity.copy( params.gravity );
  52. this.world = params.world !== undefined ? params.world : null; // experimental
  53. this.bodies = [];
  54. this.constraints = [];
  55. this._init( mesh, rigidBodyParams, constraintParams );
  56. }
  57. /**
  58. * Advances Physics calculation and updates bones.
  59. *
  60. * @param {Number} delta - time in second
  61. * @return {MMDPhysics}
  62. */
  63. update( delta ) {
  64. const manager = this.manager;
  65. const mesh = this.mesh;
  66. // rigid bodies and constrains are for
  67. // mesh's world scale (1, 1, 1).
  68. // Convert to (1, 1, 1) if it isn't.
  69. let isNonDefaultScale = false;
  70. const position = manager.allocThreeVector3();
  71. const quaternion = manager.allocThreeQuaternion();
  72. const scale = manager.allocThreeVector3();
  73. mesh.matrixWorld.decompose( position, quaternion, scale );
  74. if ( scale.x !== 1 || scale.y !== 1 || scale.z !== 1 ) {
  75. isNonDefaultScale = true;
  76. }
  77. let parent;
  78. if ( isNonDefaultScale ) {
  79. parent = mesh.parent;
  80. if ( parent !== null ) mesh.parent = null;
  81. scale.copy( this.mesh.scale );
  82. mesh.scale.set( 1, 1, 1 );
  83. mesh.updateMatrixWorld( true );
  84. }
  85. // calculate physics and update bones
  86. this._updateRigidBodies();
  87. this._stepSimulation( delta );
  88. this._updateBones();
  89. // restore mesh if converted above
  90. if ( isNonDefaultScale ) {
  91. if ( parent !== null ) mesh.parent = parent;
  92. mesh.scale.copy( scale );
  93. }
  94. manager.freeThreeVector3( scale );
  95. manager.freeThreeQuaternion( quaternion );
  96. manager.freeThreeVector3( position );
  97. return this;
  98. }
  99. /**
  100. * Resets rigid bodies transorm to current bone's.
  101. *
  102. * @return {MMDPhysics}
  103. */
  104. reset() {
  105. for ( let i = 0, il = this.bodies.length; i < il; i ++ ) {
  106. this.bodies[ i ].reset();
  107. }
  108. return this;
  109. }
  110. /**
  111. * Warm ups Rigid bodies. Calculates cycles steps.
  112. *
  113. * @param {Integer} cycles
  114. * @return {MMDPhysics}
  115. */
  116. warmup( cycles ) {
  117. for ( let i = 0; i < cycles; i ++ ) {
  118. this.update( 1 / 60 );
  119. }
  120. return this;
  121. }
  122. /**
  123. * Sets gravity.
  124. *
  125. * @param {Vector3} gravity
  126. * @return {MMDPhysicsHelper}
  127. */
  128. setGravity( gravity ) {
  129. this.world.setGravity( new Ammo.btVector3( gravity.x, gravity.y, gravity.z ) );
  130. this.gravity.copy( gravity );
  131. return this;
  132. }
  133. /**
  134. * Creates MMDPhysicsHelper
  135. *
  136. * @return {MMDPhysicsHelper}
  137. */
  138. createHelper() {
  139. return new MMDPhysicsHelper( this.mesh, this );
  140. }
  141. // private methods
  142. _init( mesh, rigidBodyParams, constraintParams ) {
  143. const manager = this.manager;
  144. // rigid body/constraint parameters are for
  145. // mesh's default world transform as position(0, 0, 0),
  146. // quaternion(0, 0, 0, 1) and scale(0, 0, 0)
  147. let parent = mesh.parent;
  148. if ( parent !== null ) parent = null;
  149. const currentPosition = manager.allocThreeVector3();
  150. const currentQuaternion = manager.allocThreeQuaternion();
  151. const currentScale = manager.allocThreeVector3();
  152. currentPosition.copy( mesh.position );
  153. currentQuaternion.copy( mesh.quaternion );
  154. currentScale.copy( mesh.scale );
  155. mesh.position.set( 0, 0, 0 );
  156. mesh.quaternion.set( 0, 0, 0, 1 );
  157. mesh.scale.set( 1, 1, 1 );
  158. mesh.updateMatrixWorld( true );
  159. if ( this.world === null ) {
  160. this.world = this._createWorld();
  161. this.setGravity( this.gravity );
  162. }
  163. this._initRigidBodies( rigidBodyParams );
  164. this._initConstraints( constraintParams );
  165. if ( parent !== null ) mesh.parent = parent;
  166. mesh.position.copy( currentPosition );
  167. mesh.quaternion.copy( currentQuaternion );
  168. mesh.scale.copy( currentScale );
  169. mesh.updateMatrixWorld( true );
  170. this.reset();
  171. manager.freeThreeVector3( currentPosition );
  172. manager.freeThreeQuaternion( currentQuaternion );
  173. manager.freeThreeVector3( currentScale );
  174. }
  175. _createWorld() {
  176. const config = new Ammo.btDefaultCollisionConfiguration();
  177. const dispatcher = new Ammo.btCollisionDispatcher( config );
  178. const cache = new Ammo.btDbvtBroadphase();
  179. const solver = new Ammo.btSequentialImpulseConstraintSolver();
  180. const world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config );
  181. return world;
  182. }
  183. _initRigidBodies( rigidBodies ) {
  184. for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) {
  185. this.bodies.push( new RigidBody(
  186. this.mesh, this.world, rigidBodies[ i ], this.manager ) );
  187. }
  188. }
  189. _initConstraints( constraints ) {
  190. for ( let i = 0, il = constraints.length; i < il; i ++ ) {
  191. const params = constraints[ i ];
  192. const bodyA = this.bodies[ params.rigidBodyIndex1 ];
  193. const bodyB = this.bodies[ params.rigidBodyIndex2 ];
  194. this.constraints.push( new Constraint( this.mesh, this.world, bodyA, bodyB, params, this.manager ) );
  195. }
  196. }
  197. _stepSimulation( delta ) {
  198. const unitStep = this.unitStep;
  199. let stepTime = delta;
  200. let maxStepNum = ( ( delta / unitStep ) | 0 ) + 1;
  201. if ( stepTime < unitStep ) {
  202. stepTime = unitStep;
  203. maxStepNum = 1;
  204. }
  205. if ( maxStepNum > this.maxStepNum ) {
  206. maxStepNum = this.maxStepNum;
  207. }
  208. this.world.stepSimulation( stepTime, maxStepNum, unitStep );
  209. }
  210. _updateRigidBodies() {
  211. for ( let i = 0, il = this.bodies.length; i < il; i ++ ) {
  212. this.bodies[ i ].updateFromBone();
  213. }
  214. }
  215. _updateBones() {
  216. for ( let i = 0, il = this.bodies.length; i < il; i ++ ) {
  217. this.bodies[ i ].updateBone();
  218. }
  219. }
  220. }
  221. /**
  222. * This manager's responsibilies are
  223. *
  224. * 1. manage Ammo.js and Three.js object resources and
  225. * improve the performance and the memory consumption by
  226. * reusing objects.
  227. *
  228. * 2. provide simple Ammo object operations.
  229. */
  230. class ResourceManager {
  231. constructor() {
  232. // for Three.js
  233. this.threeVector3s = [];
  234. this.threeMatrix4s = [];
  235. this.threeQuaternions = [];
  236. this.threeEulers = [];
  237. // for Ammo.js
  238. this.transforms = [];
  239. this.quaternions = [];
  240. this.vector3s = [];
  241. }
  242. allocThreeVector3() {
  243. return ( this.threeVector3s.length > 0 )
  244. ? this.threeVector3s.pop()
  245. : new Vector3();
  246. }
  247. freeThreeVector3( v ) {
  248. this.threeVector3s.push( v );
  249. }
  250. allocThreeMatrix4() {
  251. return ( this.threeMatrix4s.length > 0 )
  252. ? this.threeMatrix4s.pop()
  253. : new Matrix4();
  254. }
  255. freeThreeMatrix4( m ) {
  256. this.threeMatrix4s.push( m );
  257. }
  258. allocThreeQuaternion() {
  259. return ( this.threeQuaternions.length > 0 )
  260. ? this.threeQuaternions.pop()
  261. : new Quaternion();
  262. }
  263. freeThreeQuaternion( q ) {
  264. this.threeQuaternions.push( q );
  265. }
  266. allocThreeEuler() {
  267. return ( this.threeEulers.length > 0 )
  268. ? this.threeEulers.pop()
  269. : new Euler();
  270. }
  271. freeThreeEuler( e ) {
  272. this.threeEulers.push( e );
  273. }
  274. allocTransform() {
  275. return ( this.transforms.length > 0 )
  276. ? this.transforms.pop()
  277. : new Ammo.btTransform();
  278. }
  279. freeTransform( t ) {
  280. this.transforms.push( t );
  281. }
  282. allocQuaternion() {
  283. return ( this.quaternions.length > 0 )
  284. ? this.quaternions.pop()
  285. : new Ammo.btQuaternion();
  286. }
  287. freeQuaternion( q ) {
  288. this.quaternions.push( q );
  289. }
  290. allocVector3() {
  291. return ( this.vector3s.length > 0 )
  292. ? this.vector3s.pop()
  293. : new Ammo.btVector3();
  294. }
  295. freeVector3( v ) {
  296. this.vector3s.push( v );
  297. }
  298. setIdentity( t ) {
  299. t.setIdentity();
  300. }
  301. getBasis( t ) {
  302. var q = this.allocQuaternion();
  303. t.getBasis().getRotation( q );
  304. return q;
  305. }
  306. getBasisAsMatrix3( t ) {
  307. var q = this.getBasis( t );
  308. var m = this.quaternionToMatrix3( q );
  309. this.freeQuaternion( q );
  310. return m;
  311. }
  312. getOrigin( t ) {
  313. return t.getOrigin();
  314. }
  315. setOrigin( t, v ) {
  316. t.getOrigin().setValue( v.x(), v.y(), v.z() );
  317. }
  318. copyOrigin( t1, t2 ) {
  319. var o = t2.getOrigin();
  320. this.setOrigin( t1, o );
  321. }
  322. setBasis( t, q ) {
  323. t.setRotation( q );
  324. }
  325. setBasisFromMatrix3( t, m ) {
  326. var q = this.matrix3ToQuaternion( m );
  327. this.setBasis( t, q );
  328. this.freeQuaternion( q );
  329. }
  330. setOriginFromArray3( t, a ) {
  331. t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] );
  332. }
  333. setOriginFromThreeVector3( t, v ) {
  334. t.getOrigin().setValue( v.x, v.y, v.z );
  335. }
  336. setBasisFromArray3( t, a ) {
  337. var thQ = this.allocThreeQuaternion();
  338. var thE = this.allocThreeEuler();
  339. thE.set( a[ 0 ], a[ 1 ], a[ 2 ] );
  340. this.setBasisFromThreeQuaternion( t, thQ.setFromEuler( thE ) );
  341. this.freeThreeEuler( thE );
  342. this.freeThreeQuaternion( thQ );
  343. }
  344. setBasisFromThreeQuaternion( t, a ) {
  345. var q = this.allocQuaternion();
  346. q.setX( a.x );
  347. q.setY( a.y );
  348. q.setZ( a.z );
  349. q.setW( a.w );
  350. this.setBasis( t, q );
  351. this.freeQuaternion( q );
  352. }
  353. multiplyTransforms( t1, t2 ) {
  354. var t = this.allocTransform();
  355. this.setIdentity( t );
  356. var m1 = this.getBasisAsMatrix3( t1 );
  357. var m2 = this.getBasisAsMatrix3( t2 );
  358. var o1 = this.getOrigin( t1 );
  359. var o2 = this.getOrigin( t2 );
  360. var v1 = this.multiplyMatrix3ByVector3( m1, o2 );
  361. var v2 = this.addVector3( v1, o1 );
  362. this.setOrigin( t, v2 );
  363. var m3 = this.multiplyMatrices3( m1, m2 );
  364. this.setBasisFromMatrix3( t, m3 );
  365. this.freeVector3( v1 );
  366. this.freeVector3( v2 );
  367. return t;
  368. }
  369. inverseTransform( t ) {
  370. var t2 = this.allocTransform();
  371. var m1 = this.getBasisAsMatrix3( t );
  372. var o = this.getOrigin( t );
  373. var m2 = this.transposeMatrix3( m1 );
  374. var v1 = this.negativeVector3( o );
  375. var v2 = this.multiplyMatrix3ByVector3( m2, v1 );
  376. this.setOrigin( t2, v2 );
  377. this.setBasisFromMatrix3( t2, m2 );
  378. this.freeVector3( v1 );
  379. this.freeVector3( v2 );
  380. return t2;
  381. }
  382. multiplyMatrices3( m1, m2 ) {
  383. var m3 = [];
  384. var v10 = this.rowOfMatrix3( m1, 0 );
  385. var v11 = this.rowOfMatrix3( m1, 1 );
  386. var v12 = this.rowOfMatrix3( m1, 2 );
  387. var v20 = this.columnOfMatrix3( m2, 0 );
  388. var v21 = this.columnOfMatrix3( m2, 1 );
  389. var v22 = this.columnOfMatrix3( m2, 2 );
  390. m3[ 0 ] = this.dotVectors3( v10, v20 );
  391. m3[ 1 ] = this.dotVectors3( v10, v21 );
  392. m3[ 2 ] = this.dotVectors3( v10, v22 );
  393. m3[ 3 ] = this.dotVectors3( v11, v20 );
  394. m3[ 4 ] = this.dotVectors3( v11, v21 );
  395. m3[ 5 ] = this.dotVectors3( v11, v22 );
  396. m3[ 6 ] = this.dotVectors3( v12, v20 );
  397. m3[ 7 ] = this.dotVectors3( v12, v21 );
  398. m3[ 8 ] = this.dotVectors3( v12, v22 );
  399. this.freeVector3( v10 );
  400. this.freeVector3( v11 );
  401. this.freeVector3( v12 );
  402. this.freeVector3( v20 );
  403. this.freeVector3( v21 );
  404. this.freeVector3( v22 );
  405. return m3;
  406. }
  407. addVector3( v1, v2 ) {
  408. var v = this.allocVector3();
  409. v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() );
  410. return v;
  411. }
  412. dotVectors3( v1, v2 ) {
  413. return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z();
  414. }
  415. rowOfMatrix3( m, i ) {
  416. var v = this.allocVector3();
  417. v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] );
  418. return v;
  419. }
  420. columnOfMatrix3( m, i ) {
  421. var v = this.allocVector3();
  422. v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] );
  423. return v;
  424. }
  425. negativeVector3( v ) {
  426. var v2 = this.allocVector3();
  427. v2.setValue( - v.x(), - v.y(), - v.z() );
  428. return v2;
  429. }
  430. multiplyMatrix3ByVector3( m, v ) {
  431. var v4 = this.allocVector3();
  432. var v0 = this.rowOfMatrix3( m, 0 );
  433. var v1 = this.rowOfMatrix3( m, 1 );
  434. var v2 = this.rowOfMatrix3( m, 2 );
  435. var x = this.dotVectors3( v0, v );
  436. var y = this.dotVectors3( v1, v );
  437. var z = this.dotVectors3( v2, v );
  438. v4.setValue( x, y, z );
  439. this.freeVector3( v0 );
  440. this.freeVector3( v1 );
  441. this.freeVector3( v2 );
  442. return v4;
  443. }
  444. transposeMatrix3( m ) {
  445. var m2 = [];
  446. m2[ 0 ] = m[ 0 ];
  447. m2[ 1 ] = m[ 3 ];
  448. m2[ 2 ] = m[ 6 ];
  449. m2[ 3 ] = m[ 1 ];
  450. m2[ 4 ] = m[ 4 ];
  451. m2[ 5 ] = m[ 7 ];
  452. m2[ 6 ] = m[ 2 ];
  453. m2[ 7 ] = m[ 5 ];
  454. m2[ 8 ] = m[ 8 ];
  455. return m2;
  456. }
  457. quaternionToMatrix3( q ) {
  458. var m = [];
  459. var x = q.x();
  460. var y = q.y();
  461. var z = q.z();
  462. var w = q.w();
  463. var xx = x * x;
  464. var yy = y * y;
  465. var zz = z * z;
  466. var xy = x * y;
  467. var yz = y * z;
  468. var zx = z * x;
  469. var xw = x * w;
  470. var yw = y * w;
  471. var zw = z * w;
  472. m[ 0 ] = 1 - 2 * ( yy + zz );
  473. m[ 1 ] = 2 * ( xy - zw );
  474. m[ 2 ] = 2 * ( zx + yw );
  475. m[ 3 ] = 2 * ( xy + zw );
  476. m[ 4 ] = 1 - 2 * ( zz + xx );
  477. m[ 5 ] = 2 * ( yz - xw );
  478. m[ 6 ] = 2 * ( zx - yw );
  479. m[ 7 ] = 2 * ( yz + xw );
  480. m[ 8 ] = 1 - 2 * ( xx + yy );
  481. return m;
  482. }
  483. matrix3ToQuaternion( m ) {
  484. var t = m[ 0 ] + m[ 4 ] + m[ 8 ];
  485. var s, x, y, z, w;
  486. if ( t > 0 ) {
  487. s = Math.sqrt( t + 1.0 ) * 2;
  488. w = 0.25 * s;
  489. x = ( m[ 7 ] - m[ 5 ] ) / s;
  490. y = ( m[ 2 ] - m[ 6 ] ) / s;
  491. z = ( m[ 3 ] - m[ 1 ] ) / s;
  492. } else if ( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) {
  493. s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2;
  494. w = ( m[ 7 ] - m[ 5 ] ) / s;
  495. x = 0.25 * s;
  496. y = ( m[ 1 ] + m[ 3 ] ) / s;
  497. z = ( m[ 2 ] + m[ 6 ] ) / s;
  498. } else if ( m[ 4 ] > m[ 8 ] ) {
  499. s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2;
  500. w = ( m[ 2 ] - m[ 6 ] ) / s;
  501. x = ( m[ 1 ] + m[ 3 ] ) / s;
  502. y = 0.25 * s;
  503. z = ( m[ 5 ] + m[ 7 ] ) / s;
  504. } else {
  505. s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2;
  506. w = ( m[ 3 ] - m[ 1 ] ) / s;
  507. x = ( m[ 2 ] + m[ 6 ] ) / s;
  508. y = ( m[ 5 ] + m[ 7 ] ) / s;
  509. z = 0.25 * s;
  510. }
  511. var q = this.allocQuaternion();
  512. q.setX( x );
  513. q.setY( y );
  514. q.setZ( z );
  515. q.setW( w );
  516. return q;
  517. }
  518. }
  519. /**
  520. * @param {THREE.SkinnedMesh} mesh
  521. * @param {Ammo.btDiscreteDynamicsWorld} world
  522. * @param {Object} params
  523. * @param {ResourceManager} manager
  524. */
  525. class RigidBody {
  526. constructor( mesh, world, params, manager ) {
  527. this.mesh = mesh;
  528. this.world = world;
  529. this.params = params;
  530. this.manager = manager;
  531. this.body = null;
  532. this.bone = null;
  533. this.boneOffsetForm = null;
  534. this.boneOffsetFormInverse = null;
  535. this._init();
  536. }
  537. /**
  538. * Resets rigid body transform to the current bone's.
  539. *
  540. * @return {RigidBody}
  541. */
  542. reset() {
  543. this._setTransformFromBone();
  544. return this;
  545. }
  546. /**
  547. * Updates rigid body's transform from the current bone.
  548. *
  549. * @return {RidigBody}
  550. */
  551. updateFromBone() {
  552. if ( this.params.boneIndex !== - 1 && this.params.type === 0 ) {
  553. this._setTransformFromBone();
  554. }
  555. return this;
  556. }
  557. /**
  558. * Updates bone from the current ridid body's transform.
  559. *
  560. * @return {RidigBody}
  561. */
  562. updateBone() {
  563. if ( this.params.type === 0 || this.params.boneIndex === - 1 ) {
  564. return this;
  565. }
  566. this._updateBoneRotation();
  567. if ( this.params.type === 1 ) {
  568. this._updateBonePosition();
  569. }
  570. this.bone.updateMatrixWorld( true );
  571. if ( this.params.type === 2 ) {
  572. this._setPositionFromBone();
  573. }
  574. return this;
  575. }
  576. // private methods
  577. _init() {
  578. function generateShape( p ) {
  579. switch ( p.shapeType ) {
  580. case 0:
  581. return new Ammo.btSphereShape( p.width );
  582. case 1:
  583. return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) );
  584. case 2:
  585. return new Ammo.btCapsuleShape( p.width, p.height );
  586. default:
  587. throw 'unknown shape type ' + p.shapeType;
  588. }
  589. }
  590. const manager = this.manager;
  591. const params = this.params;
  592. const bones = this.mesh.skeleton.bones;
  593. const bone = ( params.boneIndex === - 1 )
  594. ? new Bone()
  595. : bones[ params.boneIndex ];
  596. const shape = generateShape( params );
  597. const weight = ( params.type === 0 ) ? 0 : params.weight;
  598. const localInertia = manager.allocVector3();
  599. localInertia.setValue( 0, 0, 0 );
  600. if ( weight !== 0 ) {
  601. shape.calculateLocalInertia( weight, localInertia );
  602. }
  603. const boneOffsetForm = manager.allocTransform();
  604. manager.setIdentity( boneOffsetForm );
  605. manager.setOriginFromArray3( boneOffsetForm, params.position );
  606. manager.setBasisFromArray3( boneOffsetForm, params.rotation );
  607. const vector = manager.allocThreeVector3();
  608. const boneForm = manager.allocTransform();
  609. manager.setIdentity( boneForm );
  610. manager.setOriginFromThreeVector3( boneForm, bone.getWorldPosition( vector ) );
  611. const form = manager.multiplyTransforms( boneForm, boneOffsetForm );
  612. const state = new Ammo.btDefaultMotionState( form );
  613. const info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia );
  614. info.set_m_friction( params.friction );
  615. info.set_m_restitution( params.restitution );
  616. const body = new Ammo.btRigidBody( info );
  617. if ( params.type === 0 ) {
  618. body.setCollisionFlags( body.getCollisionFlags() | 2 );
  619. /*
  620. * It'd be better to comment out this line though in general I should call this method
  621. * because I'm not sure why but physics will be more like MMD's
  622. * if I comment out.
  623. */
  624. body.setActivationState( 4 );
  625. }
  626. body.setDamping( params.positionDamping, params.rotationDamping );
  627. body.setSleepingThresholds( 0, 0 );
  628. this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget );
  629. this.body = body;
  630. this.bone = bone;
  631. this.boneOffsetForm = boneOffsetForm;
  632. this.boneOffsetFormInverse = manager.inverseTransform( boneOffsetForm );
  633. manager.freeVector3( localInertia );
  634. manager.freeTransform( form );
  635. manager.freeTransform( boneForm );
  636. manager.freeThreeVector3( vector );
  637. }
  638. _getBoneTransform() {
  639. const manager = this.manager;
  640. const p = manager.allocThreeVector3();
  641. const q = manager.allocThreeQuaternion();
  642. const s = manager.allocThreeVector3();
  643. this.bone.matrixWorld.decompose( p, q, s );
  644. const tr = manager.allocTransform();
  645. manager.setOriginFromThreeVector3( tr, p );
  646. manager.setBasisFromThreeQuaternion( tr, q );
  647. const form = manager.multiplyTransforms( tr, this.boneOffsetForm );
  648. manager.freeTransform( tr );
  649. manager.freeThreeVector3( s );
  650. manager.freeThreeQuaternion( q );
  651. manager.freeThreeVector3( p );
  652. return form;
  653. }
  654. _getWorldTransformForBone() {
  655. const manager = this.manager;
  656. const tr = this.body.getCenterOfMassTransform();
  657. return manager.multiplyTransforms( tr, this.boneOffsetFormInverse );
  658. }
  659. _setTransformFromBone() {
  660. const manager = this.manager;
  661. const form = this._getBoneTransform();
  662. // TODO: check the most appropriate way to set
  663. //this.body.setWorldTransform( form );
  664. this.body.setCenterOfMassTransform( form );
  665. this.body.getMotionState().setWorldTransform( form );
  666. manager.freeTransform( form );
  667. }
  668. _setPositionFromBone() {
  669. const manager = this.manager;
  670. const form = this._getBoneTransform();
  671. const tr = manager.allocTransform();
  672. this.body.getMotionState().getWorldTransform( tr );
  673. manager.copyOrigin( tr, form );
  674. // TODO: check the most appropriate way to set
  675. //this.body.setWorldTransform( tr );
  676. this.body.setCenterOfMassTransform( tr );
  677. this.body.getMotionState().setWorldTransform( tr );
  678. manager.freeTransform( tr );
  679. manager.freeTransform( form );
  680. }
  681. _updateBoneRotation() {
  682. const manager = this.manager;
  683. const tr = this._getWorldTransformForBone();
  684. const q = manager.getBasis( tr );
  685. const thQ = manager.allocThreeQuaternion();
  686. const thQ2 = manager.allocThreeQuaternion();
  687. const thQ3 = manager.allocThreeQuaternion();
  688. thQ.set( q.x(), q.y(), q.z(), q.w() );
  689. thQ2.setFromRotationMatrix( this.bone.matrixWorld );
  690. thQ2.conjugate();
  691. thQ2.multiply( thQ );
  692. //this.bone.quaternion.multiply( thQ2 );
  693. thQ3.setFromRotationMatrix( this.bone.matrix );
  694. // Renormalizing quaternion here because repeatedly transforming
  695. // quaternion continuously accumulates floating point error and
  696. // can end up being overflow. See #15335
  697. this.bone.quaternion.copy( thQ2.multiply( thQ3 ).normalize() );
  698. manager.freeThreeQuaternion( thQ );
  699. manager.freeThreeQuaternion( thQ2 );
  700. manager.freeThreeQuaternion( thQ3 );
  701. manager.freeQuaternion( q );
  702. manager.freeTransform( tr );
  703. }
  704. _updateBonePosition() {
  705. const manager = this.manager;
  706. const tr = this._getWorldTransformForBone();
  707. const thV = manager.allocThreeVector3();
  708. const o = manager.getOrigin( tr );
  709. thV.set( o.x(), o.y(), o.z() );
  710. if ( this.bone.parent ) {
  711. this.bone.parent.worldToLocal( thV );
  712. }
  713. this.bone.position.copy( thV );
  714. manager.freeThreeVector3( thV );
  715. manager.freeTransform( tr );
  716. }
  717. }
  718. //
  719. class Constraint {
  720. /**
  721. * @param {THREE.SkinnedMesh} mesh
  722. * @param {Ammo.btDiscreteDynamicsWorld} world
  723. * @param {RigidBody} bodyA
  724. * @param {RigidBody} bodyB
  725. * @param {Object} params
  726. * @param {ResourceManager} manager
  727. */
  728. constructor( mesh, world, bodyA, bodyB, params, manager ) {
  729. this.mesh = mesh;
  730. this.world = world;
  731. this.bodyA = bodyA;
  732. this.bodyB = bodyB;
  733. this.params = params;
  734. this.manager = manager;
  735. this.constraint = null;
  736. this._init();
  737. }
  738. // private method
  739. _init() {
  740. const manager = this.manager;
  741. const params = this.params;
  742. const bodyA = this.bodyA;
  743. const bodyB = this.bodyB;
  744. const form = manager.allocTransform();
  745. manager.setIdentity( form );
  746. manager.setOriginFromArray3( form, params.position );
  747. manager.setBasisFromArray3( form, params.rotation );
  748. const formA = manager.allocTransform();
  749. const formB = manager.allocTransform();
  750. bodyA.body.getMotionState().getWorldTransform( formA );
  751. bodyB.body.getMotionState().getWorldTransform( formB );
  752. const formInverseA = manager.inverseTransform( formA );
  753. const formInverseB = manager.inverseTransform( formB );
  754. const formA2 = manager.multiplyTransforms( formInverseA, form );
  755. const formB2 = manager.multiplyTransforms( formInverseB, form );
  756. const constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true );
  757. const lll = manager.allocVector3();
  758. const lul = manager.allocVector3();
  759. const all = manager.allocVector3();
  760. const aul = manager.allocVector3();
  761. lll.setValue( params.translationLimitation1[ 0 ],
  762. params.translationLimitation1[ 1 ],
  763. params.translationLimitation1[ 2 ] );
  764. lul.setValue( params.translationLimitation2[ 0 ],
  765. params.translationLimitation2[ 1 ],
  766. params.translationLimitation2[ 2 ] );
  767. all.setValue( params.rotationLimitation1[ 0 ],
  768. params.rotationLimitation1[ 1 ],
  769. params.rotationLimitation1[ 2 ] );
  770. aul.setValue( params.rotationLimitation2[ 0 ],
  771. params.rotationLimitation2[ 1 ],
  772. params.rotationLimitation2[ 2 ] );
  773. constraint.setLinearLowerLimit( lll );
  774. constraint.setLinearUpperLimit( lul );
  775. constraint.setAngularLowerLimit( all );
  776. constraint.setAngularUpperLimit( aul );
  777. for ( let i = 0; i < 3; i ++ ) {
  778. if ( params.springPosition[ i ] !== 0 ) {
  779. constraint.enableSpring( i, true );
  780. constraint.setStiffness( i, params.springPosition[ i ] );
  781. }
  782. }
  783. for ( let i = 0; i < 3; i ++ ) {
  784. if ( params.springRotation[ i ] !== 0 ) {
  785. constraint.enableSpring( i + 3, true );
  786. constraint.setStiffness( i + 3, params.springRotation[ i ] );
  787. }
  788. }
  789. /*
  790. * Currently(10/31/2016) official ammo.js doesn't support
  791. * btGeneric6DofSpringConstraint.setParam method.
  792. * You need custom ammo.js (add the method into idl) if you wanna use.
  793. * By setting this parameter, physics will be more like MMD's
  794. */
  795. if ( constraint.setParam !== undefined ) {
  796. for ( let i = 0; i < 6; i ++ ) {
  797. // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  798. constraint.setParam( 2, 0.475, i );
  799. }
  800. }
  801. this.world.addConstraint( constraint, true );
  802. this.constraint = constraint;
  803. manager.freeTransform( form );
  804. manager.freeTransform( formA );
  805. manager.freeTransform( formB );
  806. manager.freeTransform( formInverseA );
  807. manager.freeTransform( formInverseB );
  808. manager.freeTransform( formA2 );
  809. manager.freeTransform( formB2 );
  810. manager.freeVector3( lll );
  811. manager.freeVector3( lul );
  812. manager.freeVector3( all );
  813. manager.freeVector3( aul );
  814. }
  815. }
  816. //
  817. const _position = new Vector3();
  818. const _quaternion = new Quaternion();
  819. const _scale = new Vector3();
  820. const _matrixWorldInv = new Matrix4();
  821. class MMDPhysicsHelper extends Object3D {
  822. /**
  823. * Visualize Rigid bodies
  824. *
  825. * @param {THREE.SkinnedMesh} mesh
  826. * @param {Physics} physics
  827. */
  828. constructor( mesh, physics ) {
  829. super();
  830. this.root = mesh;
  831. this.physics = physics;
  832. this.matrix.copy( mesh.matrixWorld );
  833. this.matrixAutoUpdate = false;
  834. this.materials = [];
  835. this.materials.push(
  836. new MeshBasicMaterial( {
  837. color: new Color( 0xff8888 ),
  838. wireframe: true,
  839. depthTest: false,
  840. depthWrite: false,
  841. opacity: 0.25,
  842. transparent: true
  843. } )
  844. );
  845. this.materials.push(
  846. new MeshBasicMaterial( {
  847. color: new Color( 0x88ff88 ),
  848. wireframe: true,
  849. depthTest: false,
  850. depthWrite: false,
  851. opacity: 0.25,
  852. transparent: true
  853. } )
  854. );
  855. this.materials.push(
  856. new MeshBasicMaterial( {
  857. color: new Color( 0x8888ff ),
  858. wireframe: true,
  859. depthTest: false,
  860. depthWrite: false,
  861. opacity: 0.25,
  862. transparent: true
  863. } )
  864. );
  865. this._init();
  866. }
  867. /**
  868. * Updates Rigid Bodies visualization.
  869. */
  870. updateMatrixWorld( force ) {
  871. var mesh = this.root;
  872. if ( this.visible ) {
  873. var bodies = this.physics.bodies;
  874. _matrixWorldInv
  875. .copy( mesh.matrixWorld )
  876. .decompose( _position, _quaternion, _scale )
  877. .compose( _position, _quaternion, _scale.set( 1, 1, 1 ) )
  878. .invert();
  879. for ( var i = 0, il = bodies.length; i < il; i ++ ) {
  880. var body = bodies[ i ].body;
  881. var child = this.children[ i ];
  882. var tr = body.getCenterOfMassTransform();
  883. var origin = tr.getOrigin();
  884. var rotation = tr.getRotation();
  885. child.position
  886. .set( origin.x(), origin.y(), origin.z() )
  887. .applyMatrix4( _matrixWorldInv );
  888. child.quaternion
  889. .setFromRotationMatrix( _matrixWorldInv )
  890. .multiply(
  891. _quaternion.set( rotation.x(), rotation.y(), rotation.z(), rotation.w() )
  892. );
  893. }
  894. }
  895. this.matrix
  896. .copy( mesh.matrixWorld )
  897. .decompose( _position, _quaternion, _scale )
  898. .compose( _position, _quaternion, _scale.set( 1, 1, 1 ) );
  899. super.updateMatrixWorld( force );
  900. }
  901. // private method
  902. _init() {
  903. var bodies = this.physics.bodies;
  904. function createGeometry( param ) {
  905. switch ( param.shapeType ) {
  906. case 0:
  907. return new SphereGeometry( param.width, 16, 8 );
  908. case 1:
  909. return new BoxGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 );
  910. case 2:
  911. return new createCapsuleGeometry( param.width, param.height, 16, 8 );
  912. default:
  913. return null;
  914. }
  915. }
  916. // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815
  917. function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) {
  918. var geometry = new CylinderGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true );
  919. var upperSphere = new Mesh( new SphereGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) );
  920. var lowerSphere = new Mesh( new SphereGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) );
  921. upperSphere.position.set( 0, cylinderHeight / 2, 0 );
  922. lowerSphere.position.set( 0, - cylinderHeight / 2, 0 );
  923. upperSphere.updateMatrix();
  924. lowerSphere.updateMatrix();
  925. geometry.merge( upperSphere.geometry, upperSphere.matrix );
  926. geometry.merge( lowerSphere.geometry, lowerSphere.matrix );
  927. return geometry;
  928. }
  929. for ( var i = 0, il = bodies.length; i < il; i ++ ) {
  930. var param = bodies[ i ].params;
  931. this.add( new Mesh( createGeometry( param ), this.materials[ param.type ] ) );
  932. }
  933. }
  934. }
  935. export { MMDPhysics };