MMDPhysics.js 30 KB

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