MMDPhysics.js 30 KB

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