MMDPhysics.js 30 KB

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