MMDPhysics.js 30 KB

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