MMDAnimationHelper.js 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. ( function () {
  2. /**
  3. * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader
  4. * with MMD special features as IK, Grant, and Physics.
  5. *
  6. * Dependencies
  7. * - ammo.js https://github.com/kripken/ammo.js
  8. * - THREE.MMDPhysics
  9. * - THREE.CCDIKSolver
  10. *
  11. * TODO
  12. * - more precise grant skinning support.
  13. */
  14. class MMDAnimationHelper {
  15. /**
  16. * @param {Object} params - (optional)
  17. * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true.
  18. * @param {Number} params.afterglow - Default is 0.0.
  19. * @param {boolean} params.resetPhysicsOnLoop - Default is true.
  20. */
  21. constructor( params = {} ) {
  22. this.meshes = [];
  23. this.camera = null;
  24. this.cameraTarget = new THREE.Object3D();
  25. this.cameraTarget.name = 'target';
  26. this.audio = null;
  27. this.audioManager = null;
  28. this.objects = new WeakMap();
  29. this.configuration = {
  30. sync: params.sync !== undefined ? params.sync : true,
  31. afterglow: params.afterglow !== undefined ? params.afterglow : 0.0,
  32. resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true,
  33. pmxAnimation: params.pmxAnimation !== undefined ? params.pmxAnimation : false
  34. };
  35. this.enabled = {
  36. animation: true,
  37. ik: true,
  38. grant: true,
  39. physics: true,
  40. cameraAnimation: true
  41. };
  42. this.onBeforePhysics = function /* mesh */ () {};
  43. // experimental
  44. this.sharedPhysics = false;
  45. this.masterPhysics = null;
  46. }
  47. /**
  48. * Adds an Three.js Object to helper and setups animation.
  49. * The anmation durations of added objects are synched
  50. * if this.configuration.sync is true.
  51. *
  52. * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object
  53. * @param {Object} params - (optional)
  54. * @param {THREE.AnimationClip|Array<THREE.AnimationClip>} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined.
  55. * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true.
  56. * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60.
  57. * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65.
  58. * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3.
  59. * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ).
  60. * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0.
  61. * @return {MMDAnimationHelper}
  62. */
  63. add( object, params = {} ) {
  64. if ( object.isSkinnedMesh ) {
  65. this._addMesh( object, params );
  66. } else if ( object.isCamera ) {
  67. this._setupCamera( object, params );
  68. } else if ( object.type === 'Audio' ) {
  69. this._setupAudio( object, params );
  70. } else {
  71. throw new Error( 'THREE.MMDAnimationHelper.add: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.' );
  72. }
  73. if ( this.configuration.sync ) this._syncDuration();
  74. return this;
  75. }
  76. /**
  77. * Removes an Three.js Object from helper.
  78. *
  79. * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object
  80. * @return {MMDAnimationHelper}
  81. */
  82. remove( object ) {
  83. if ( object.isSkinnedMesh ) {
  84. this._removeMesh( object );
  85. } else if ( object.isCamera ) {
  86. this._clearCamera( object );
  87. } else if ( object.type === 'Audio' ) {
  88. this._clearAudio( object );
  89. } else {
  90. throw new Error( 'THREE.MMDAnimationHelper.remove: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.' );
  91. }
  92. if ( this.configuration.sync ) this._syncDuration();
  93. return this;
  94. }
  95. /**
  96. * Updates the animation.
  97. *
  98. * @param {Number} delta
  99. * @return {MMDAnimationHelper}
  100. */
  101. update( delta ) {
  102. if ( this.audioManager !== null ) this.audioManager.control( delta );
  103. for ( let i = 0; i < this.meshes.length; i ++ ) {
  104. this._animateMesh( this.meshes[ i ], delta );
  105. }
  106. if ( this.sharedPhysics ) this._updateSharedPhysics( delta );
  107. if ( this.camera !== null ) this._animateCamera( this.camera, delta );
  108. return this;
  109. }
  110. /**
  111. * Changes the pose of SkinnedMesh as VPD specifies.
  112. *
  113. * @param {THREE.SkinnedMesh} mesh
  114. * @param {Object} vpd - VPD content parsed MMDParser
  115. * @param {Object} params - (optional)
  116. * @param {boolean} params.resetPose - Default is true.
  117. * @param {boolean} params.ik - Default is true.
  118. * @param {boolean} params.grant - Default is true.
  119. * @return {MMDAnimationHelper}
  120. */
  121. pose( mesh, vpd, params = {} ) {
  122. if ( params.resetPose !== false ) mesh.pose();
  123. const bones = mesh.skeleton.bones;
  124. const boneParams = vpd.bones;
  125. const boneNameDictionary = {};
  126. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  127. boneNameDictionary[ bones[ i ].name ] = i;
  128. }
  129. const vector = new THREE.Vector3();
  130. const quaternion = new THREE.Quaternion();
  131. for ( let i = 0, il = boneParams.length; i < il; i ++ ) {
  132. const boneParam = boneParams[ i ];
  133. const boneIndex = boneNameDictionary[ boneParam.name ];
  134. if ( boneIndex === undefined ) continue;
  135. const bone = bones[ boneIndex ];
  136. bone.position.add( vector.fromArray( boneParam.translation ) );
  137. bone.quaternion.multiply( quaternion.fromArray( boneParam.quaternion ) );
  138. }
  139. mesh.updateMatrixWorld( true );
  140. // PMX animation system special path
  141. if ( this.configuration.pmxAnimation && mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) {
  142. const sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() );
  143. const ikSolver = params.ik !== false ? this._createCCDIKSolver( mesh ) : null;
  144. const grantSolver = params.grant !== false ? this.createGrantSolver( mesh ) : null;
  145. this._animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver );
  146. } else {
  147. if ( params.ik !== false ) {
  148. this._createCCDIKSolver( mesh ).update();
  149. }
  150. if ( params.grant !== false ) {
  151. this.createGrantSolver( mesh ).update();
  152. }
  153. }
  154. return this;
  155. }
  156. /**
  157. * Enabes/Disables an animation feature.
  158. *
  159. * @param {string} key
  160. * @param {boolean} enabled
  161. * @return {MMDAnimationHelper}
  162. */
  163. enable( key, enabled ) {
  164. if ( this.enabled[ key ] === undefined ) {
  165. throw new Error( 'THREE.MMDAnimationHelper.enable: ' + 'unknown key ' + key );
  166. }
  167. this.enabled[ key ] = enabled;
  168. if ( key === 'physics' ) {
  169. for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {
  170. this._optimizeIK( this.meshes[ i ], enabled );
  171. }
  172. }
  173. return this;
  174. }
  175. /**
  176. * Creates an GrantSolver instance.
  177. *
  178. * @param {THREE.SkinnedMesh} mesh
  179. * @return {GrantSolver}
  180. */
  181. createGrantSolver( mesh ) {
  182. return new GrantSolver( mesh, mesh.geometry.userData.MMD.grants );
  183. }
  184. // private methods
  185. _addMesh( mesh, params ) {
  186. if ( this.meshes.indexOf( mesh ) >= 0 ) {
  187. throw new Error( 'THREE.MMDAnimationHelper._addMesh: ' + 'SkinnedMesh \'' + mesh.name + '\' has already been added.' );
  188. }
  189. this.meshes.push( mesh );
  190. this.objects.set( mesh, {
  191. looped: false
  192. } );
  193. this._setupMeshAnimation( mesh, params.animation );
  194. if ( params.physics !== false ) {
  195. this._setupMeshPhysics( mesh, params );
  196. }
  197. return this;
  198. }
  199. _setupCamera( camera, params ) {
  200. if ( this.camera === camera ) {
  201. throw new Error( 'THREE.MMDAnimationHelper._setupCamera: ' + 'Camera \'' + camera.name + '\' has already been set.' );
  202. }
  203. if ( this.camera ) this.clearCamera( this.camera );
  204. this.camera = camera;
  205. camera.add( this.cameraTarget );
  206. this.objects.set( camera, {} );
  207. if ( params.animation !== undefined ) {
  208. this._setupCameraAnimation( camera, params.animation );
  209. }
  210. return this;
  211. }
  212. _setupAudio( audio, params ) {
  213. if ( this.audio === audio ) {
  214. throw new Error( 'THREE.MMDAnimationHelper._setupAudio: ' + 'Audio \'' + audio.name + '\' has already been set.' );
  215. }
  216. if ( this.audio ) this.clearAudio( this.audio );
  217. this.audio = audio;
  218. this.audioManager = new AudioManager( audio, params );
  219. this.objects.set( this.audioManager, {
  220. duration: this.audioManager.duration
  221. } );
  222. return this;
  223. }
  224. _removeMesh( mesh ) {
  225. let found = false;
  226. let writeIndex = 0;
  227. for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {
  228. if ( this.meshes[ i ] === mesh ) {
  229. this.objects.delete( mesh );
  230. found = true;
  231. continue;
  232. }
  233. this.meshes[ writeIndex ++ ] = this.meshes[ i ];
  234. }
  235. if ( ! found ) {
  236. throw new Error( 'THREE.MMDAnimationHelper._removeMesh: ' + 'SkinnedMesh \'' + mesh.name + '\' has not been added yet.' );
  237. }
  238. this.meshes.length = writeIndex;
  239. return this;
  240. }
  241. _clearCamera( camera ) {
  242. if ( camera !== this.camera ) {
  243. throw new Error( 'THREE.MMDAnimationHelper._clearCamera: ' + 'Camera \'' + camera.name + '\' has not been set yet.' );
  244. }
  245. this.camera.remove( this.cameraTarget );
  246. this.objects.delete( this.camera );
  247. this.camera = null;
  248. return this;
  249. }
  250. _clearAudio( audio ) {
  251. if ( audio !== this.audio ) {
  252. throw new Error( 'THREE.MMDAnimationHelper._clearAudio: ' + 'Audio \'' + audio.name + '\' has not been set yet.' );
  253. }
  254. this.objects.delete( this.audioManager );
  255. this.audio = null;
  256. this.audioManager = null;
  257. return this;
  258. }
  259. _setupMeshAnimation( mesh, animation ) {
  260. const objects = this.objects.get( mesh );
  261. if ( animation !== undefined ) {
  262. const animations = Array.isArray( animation ) ? animation : [ animation ];
  263. objects.mixer = new THREE.AnimationMixer( mesh );
  264. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  265. objects.mixer.clipAction( animations[ i ] ).play();
  266. }
  267. // TODO: find a workaround not to access ._clip looking like a private property
  268. objects.mixer.addEventListener( 'loop', function ( event ) {
  269. const tracks = event.action._clip.tracks;
  270. if ( tracks.length > 0 && tracks[ 0 ].name.slice( 0, 6 ) !== '.bones' ) return;
  271. objects.looped = true;
  272. } );
  273. }
  274. objects.ikSolver = this._createCCDIKSolver( mesh );
  275. objects.grantSolver = this.createGrantSolver( mesh );
  276. return this;
  277. }
  278. _setupCameraAnimation( camera, animation ) {
  279. const animations = Array.isArray( animation ) ? animation : [ animation ];
  280. const objects = this.objects.get( camera );
  281. objects.mixer = new THREE.AnimationMixer( camera );
  282. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  283. objects.mixer.clipAction( animations[ i ] ).play();
  284. }
  285. }
  286. _setupMeshPhysics( mesh, params ) {
  287. const objects = this.objects.get( mesh );
  288. // shared physics is experimental
  289. if ( params.world === undefined && this.sharedPhysics ) {
  290. const masterPhysics = this._getMasterPhysics();
  291. if ( masterPhysics !== null ) world = masterPhysics.world; // eslint-disable-line no-undef
  292. }
  293. objects.physics = this._createMMDPhysics( mesh, params );
  294. if ( objects.mixer && params.animationWarmup !== false ) {
  295. this._animateMesh( mesh, 0 );
  296. objects.physics.reset();
  297. }
  298. objects.physics.warmup( params.warmup !== undefined ? params.warmup : 60 );
  299. this._optimizeIK( mesh, true );
  300. }
  301. _animateMesh( mesh, delta ) {
  302. const objects = this.objects.get( mesh );
  303. const mixer = objects.mixer;
  304. const ikSolver = objects.ikSolver;
  305. const grantSolver = objects.grantSolver;
  306. const physics = objects.physics;
  307. const looped = objects.looped;
  308. if ( mixer && this.enabled.animation ) {
  309. // alternate solution to save/restore bones but less performant?
  310. //mesh.pose();
  311. //this._updatePropertyMixersBuffer( mesh );
  312. this._restoreBones( mesh );
  313. mixer.update( delta );
  314. this._saveBones( mesh );
  315. // PMX animation system special path
  316. if ( this.configuration.pmxAnimation && mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) {
  317. if ( ! objects.sortedBonesData ) objects.sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() );
  318. this._animatePMXMesh( mesh, objects.sortedBonesData, ikSolver && this.enabled.ik ? ikSolver : null, grantSolver && this.enabled.grant ? grantSolver : null );
  319. } else {
  320. if ( ikSolver && this.enabled.ik ) {
  321. mesh.updateMatrixWorld( true );
  322. ikSolver.update();
  323. }
  324. if ( grantSolver && this.enabled.grant ) {
  325. grantSolver.update();
  326. }
  327. }
  328. }
  329. if ( looped === true && this.enabled.physics ) {
  330. if ( physics && this.configuration.resetPhysicsOnLoop ) physics.reset();
  331. objects.looped = false;
  332. }
  333. if ( physics && this.enabled.physics && ! this.sharedPhysics ) {
  334. this.onBeforePhysics( mesh );
  335. physics.update( delta );
  336. }
  337. }
  338. // Sort bones in order by 1. transformationClass and 2. bone index.
  339. // In PMX animation system, bone transformations should be processed
  340. // in this order.
  341. _sortBoneDataArray( boneDataArray ) {
  342. return boneDataArray.sort( function ( a, b ) {
  343. if ( a.transformationClass !== b.transformationClass ) {
  344. return a.transformationClass - b.transformationClass;
  345. } else {
  346. return a.index - b.index;
  347. }
  348. } );
  349. }
  350. // PMX Animation system is a bit too complex and doesn't great match to
  351. // Three.js Animation system. This method attempts to simulate it as much as
  352. // possible but doesn't perfectly simulate.
  353. // This method is more costly than the regular one so
  354. // you are recommended to set constructor parameter "pmxAnimation: true"
  355. // only if your PMX model animation doesn't work well.
  356. // If you need better method you would be required to write your own.
  357. _animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver ) {
  358. _quaternionIndex = 0;
  359. _grantResultMap.clear();
  360. for ( let i = 0, il = sortedBonesData.length; i < il; i ++ ) {
  361. updateOne( mesh, sortedBonesData[ i ].index, ikSolver, grantSolver );
  362. }
  363. mesh.updateMatrixWorld( true );
  364. return this;
  365. }
  366. _animateCamera( camera, delta ) {
  367. const mixer = this.objects.get( camera ).mixer;
  368. if ( mixer && this.enabled.cameraAnimation ) {
  369. mixer.update( delta );
  370. camera.updateProjectionMatrix();
  371. camera.up.set( 0, 1, 0 );
  372. camera.up.applyQuaternion( camera.quaternion );
  373. camera.lookAt( this.cameraTarget.position );
  374. }
  375. }
  376. _optimizeIK( mesh, physicsEnabled ) {
  377. const iks = mesh.geometry.userData.MMD.iks;
  378. const bones = mesh.geometry.userData.MMD.bones;
  379. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  380. const ik = iks[ i ];
  381. const links = ik.links;
  382. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  383. const link = links[ j ];
  384. if ( physicsEnabled === true ) {
  385. // disable IK of the bone the corresponding rigidBody type of which is 1 or 2
  386. // because its rotation will be overriden by physics
  387. link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true;
  388. } else {
  389. link.enabled = true;
  390. }
  391. }
  392. }
  393. }
  394. _createCCDIKSolver( mesh ) {
  395. if ( THREE.CCDIKSolver === undefined ) {
  396. throw new Error( 'THREE.MMDAnimationHelper: Import THREE.CCDIKSolver.' );
  397. }
  398. return new THREE.CCDIKSolver( mesh, mesh.geometry.userData.MMD.iks );
  399. }
  400. _createMMDPhysics( mesh, params ) {
  401. if ( THREE.MMDPhysics === undefined ) {
  402. throw new Error( 'THREE.MMDPhysics: Import THREE.MMDPhysics.' );
  403. }
  404. return new THREE.MMDPhysics( mesh, mesh.geometry.userData.MMD.rigidBodies, mesh.geometry.userData.MMD.constraints, params );
  405. }
  406. /*
  407. * Detects the longest duration and then sets it to them to sync.
  408. * TODO: Not to access private properties ( ._actions and ._clip )
  409. */
  410. _syncDuration() {
  411. let max = 0.0;
  412. const objects = this.objects;
  413. const meshes = this.meshes;
  414. const camera = this.camera;
  415. const audioManager = this.audioManager;
  416. // get the longest duration
  417. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  418. const mixer = this.objects.get( meshes[ i ] ).mixer;
  419. if ( mixer === undefined ) continue;
  420. for ( let j = 0; j < mixer._actions.length; j ++ ) {
  421. const clip = mixer._actions[ j ]._clip;
  422. if ( ! objects.has( clip ) ) {
  423. objects.set( clip, {
  424. duration: clip.duration
  425. } );
  426. }
  427. max = Math.max( max, objects.get( clip ).duration );
  428. }
  429. }
  430. if ( camera !== null ) {
  431. const mixer = this.objects.get( camera ).mixer;
  432. if ( mixer !== undefined ) {
  433. for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) {
  434. const clip = mixer._actions[ i ]._clip;
  435. if ( ! objects.has( clip ) ) {
  436. objects.set( clip, {
  437. duration: clip.duration
  438. } );
  439. }
  440. max = Math.max( max, objects.get( clip ).duration );
  441. }
  442. }
  443. }
  444. if ( audioManager !== null ) {
  445. max = Math.max( max, objects.get( audioManager ).duration );
  446. }
  447. max += this.configuration.afterglow;
  448. // update the duration
  449. for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {
  450. const mixer = this.objects.get( this.meshes[ i ] ).mixer;
  451. if ( mixer === undefined ) continue;
  452. for ( let j = 0, jl = mixer._actions.length; j < jl; j ++ ) {
  453. mixer._actions[ j ]._clip.duration = max;
  454. }
  455. }
  456. if ( camera !== null ) {
  457. const mixer = this.objects.get( camera ).mixer;
  458. if ( mixer !== undefined ) {
  459. for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) {
  460. mixer._actions[ i ]._clip.duration = max;
  461. }
  462. }
  463. }
  464. if ( audioManager !== null ) {
  465. audioManager.duration = max;
  466. }
  467. }
  468. // workaround
  469. _updatePropertyMixersBuffer( mesh ) {
  470. const mixer = this.objects.get( mesh ).mixer;
  471. const propertyMixers = mixer._bindings;
  472. const accuIndex = mixer._accuIndex;
  473. for ( let i = 0, il = propertyMixers.length; i < il; i ++ ) {
  474. const propertyMixer = propertyMixers[ i ];
  475. const buffer = propertyMixer.buffer;
  476. const stride = propertyMixer.valueSize;
  477. const offset = ( accuIndex + 1 ) * stride;
  478. propertyMixer.binding.getValue( buffer, offset );
  479. }
  480. }
  481. /*
  482. * Avoiding these two issues by restore/save bones before/after mixer animation.
  483. *
  484. * 1. PropertyMixer used by THREE.AnimationMixer holds cache value in .buffer.
  485. * Calculating IK, Grant, and Physics after mixer animation can break
  486. * the cache coherency.
  487. *
  488. * 2. Applying Grant two or more times without reset the posing breaks model.
  489. */
  490. _saveBones( mesh ) {
  491. const objects = this.objects.get( mesh );
  492. const bones = mesh.skeleton.bones;
  493. let backupBones = objects.backupBones;
  494. if ( backupBones === undefined ) {
  495. backupBones = new Float32Array( bones.length * 7 );
  496. objects.backupBones = backupBones;
  497. }
  498. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  499. const bone = bones[ i ];
  500. bone.position.toArray( backupBones, i * 7 );
  501. bone.quaternion.toArray( backupBones, i * 7 + 3 );
  502. }
  503. }
  504. _restoreBones( mesh ) {
  505. const objects = this.objects.get( mesh );
  506. const backupBones = objects.backupBones;
  507. if ( backupBones === undefined ) return;
  508. const bones = mesh.skeleton.bones;
  509. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  510. const bone = bones[ i ];
  511. bone.position.fromArray( backupBones, i * 7 );
  512. bone.quaternion.fromArray( backupBones, i * 7 + 3 );
  513. }
  514. }
  515. // experimental
  516. _getMasterPhysics() {
  517. if ( this.masterPhysics !== null ) return this.masterPhysics;
  518. for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {
  519. const physics = this.meshes[ i ].physics;
  520. if ( physics !== undefined && physics !== null ) {
  521. this.masterPhysics = physics;
  522. return this.masterPhysics;
  523. }
  524. }
  525. return null;
  526. }
  527. _updateSharedPhysics( delta ) {
  528. if ( this.meshes.length === 0 || ! this.enabled.physics || ! this.sharedPhysics ) return;
  529. const physics = this._getMasterPhysics();
  530. if ( physics === null ) return;
  531. for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {
  532. const p = this.meshes[ i ].physics;
  533. if ( p !== null && p !== undefined ) {
  534. p.updateRigidBodies();
  535. }
  536. }
  537. physics.stepSimulation( delta );
  538. for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {
  539. const p = this.meshes[ i ].physics;
  540. if ( p !== null && p !== undefined ) {
  541. p.updateBones();
  542. }
  543. }
  544. }
  545. }
  546. // Keep working quaternions for less GC
  547. const _quaternions = [];
  548. let _quaternionIndex = 0;
  549. function getQuaternion() {
  550. if ( _quaternionIndex >= _quaternions.length ) {
  551. _quaternions.push( new THREE.Quaternion() );
  552. }
  553. return _quaternions[ _quaternionIndex ++ ];
  554. }
  555. // Save rotation whose grant and IK are already applied
  556. // used by grant children
  557. const _grantResultMap = new Map();
  558. function updateOne( mesh, boneIndex, ikSolver, grantSolver ) {
  559. const bones = mesh.skeleton.bones;
  560. const bonesData = mesh.geometry.userData.MMD.bones;
  561. const boneData = bonesData[ boneIndex ];
  562. const bone = bones[ boneIndex ];
  563. // Return if already updated by being referred as a grant parent.
  564. if ( _grantResultMap.has( boneIndex ) ) return;
  565. const quaternion = getQuaternion();
  566. // Initialize grant result here to prevent infinite loop.
  567. // If it's referred before updating with actual result later
  568. // result without applyting IK or grant is gotten
  569. // but better than composing of infinite loop.
  570. _grantResultMap.set( boneIndex, quaternion.copy( bone.quaternion ) );
  571. // @TODO: Support global grant and grant position
  572. if ( grantSolver && boneData.grant && ! boneData.grant.isLocal && boneData.grant.affectRotation ) {
  573. const parentIndex = boneData.grant.parentIndex;
  574. const ratio = boneData.grant.ratio;
  575. if ( ! _grantResultMap.has( parentIndex ) ) {
  576. updateOne( mesh, parentIndex, ikSolver, grantSolver );
  577. }
  578. grantSolver.addGrantRotation( bone, _grantResultMap.get( parentIndex ), ratio );
  579. }
  580. if ( ikSolver && boneData.ik ) {
  581. // @TODO: Updating world matrices every time solving an IK bone is
  582. // costly. Optimize if possible.
  583. mesh.updateMatrixWorld( true );
  584. ikSolver.updateOne( boneData.ik );
  585. // No confident, but it seems the grant results with ik links should be updated?
  586. const links = boneData.ik.links;
  587. for ( let i = 0, il = links.length; i < il; i ++ ) {
  588. const link = links[ i ];
  589. if ( link.enabled === false ) continue;
  590. const linkIndex = link.index;
  591. if ( _grantResultMap.has( linkIndex ) ) {
  592. _grantResultMap.set( linkIndex, _grantResultMap.get( linkIndex ).copy( bones[ linkIndex ].quaternion ) );
  593. }
  594. }
  595. }
  596. // Update with the actual result here
  597. quaternion.copy( bone.quaternion );
  598. }
  599. //
  600. class AudioManager {
  601. /**
  602. * @param {THREE.Audio} audio
  603. * @param {Object} params - (optional)
  604. * @param {Nuumber} params.delayTime
  605. */
  606. constructor( audio, params = {} ) {
  607. this.audio = audio;
  608. this.elapsedTime = 0.0;
  609. this.currentTime = 0.0;
  610. this.delayTime = params.delayTime !== undefined ? params.delayTime : 0.0;
  611. this.audioDuration = this.audio.buffer.duration;
  612. this.duration = this.audioDuration + this.delayTime;
  613. }
  614. /**
  615. * @param {Number} delta
  616. * @return {AudioManager}
  617. */
  618. control( delta ) {
  619. this.elapsed += delta;
  620. this.currentTime += delta;
  621. if ( this._shouldStopAudio() ) this.audio.stop();
  622. if ( this._shouldStartAudio() ) this.audio.play();
  623. return this;
  624. }
  625. // private methods
  626. _shouldStartAudio() {
  627. if ( this.audio.isPlaying ) return false;
  628. while ( this.currentTime >= this.duration ) {
  629. this.currentTime -= this.duration;
  630. }
  631. if ( this.currentTime < this.delayTime ) return false;
  632. // 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration
  633. if ( this.currentTime - this.delayTime > this.audioDuration ) return false;
  634. return true;
  635. }
  636. _shouldStopAudio() {
  637. return this.audio.isPlaying && this.currentTime >= this.duration;
  638. }
  639. }
  640. const _q = new THREE.Quaternion();
  641. /**
  642. * Solver for Grant (Fuyo in Japanese. I just google translated because
  643. * Fuyo may be MMD specific term and may not be common word in 3D CG terms.)
  644. * Grant propagates a bone's transform to other bones transforms even if
  645. * they are not children.
  646. * @param {THREE.SkinnedMesh} mesh
  647. * @param {Array<Object>} grants
  648. */
  649. class GrantSolver {
  650. constructor( mesh, grants = [] ) {
  651. this.mesh = mesh;
  652. this.grants = grants;
  653. }
  654. /**
  655. * Solve all the grant bones
  656. * @return {GrantSolver}
  657. */
  658. update() {
  659. const grants = this.grants;
  660. for ( let i = 0, il = grants.length; i < il; i ++ ) {
  661. this.updateOne( grants[ i ] );
  662. }
  663. return this;
  664. }
  665. /**
  666. * Solve a grant bone
  667. * @param {Object} grant - grant parameter
  668. * @return {GrantSolver}
  669. */
  670. updateOne( grant ) {
  671. const bones = this.mesh.skeleton.bones;
  672. const bone = bones[ grant.index ];
  673. const parentBone = bones[ grant.parentIndex ];
  674. if ( grant.isLocal ) {
  675. // TODO: implement
  676. if ( grant.affectPosition ) {}
  677. // TODO: implement
  678. if ( grant.affectRotation ) {}
  679. } else {
  680. // TODO: implement
  681. if ( grant.affectPosition ) {}
  682. if ( grant.affectRotation ) {
  683. this.addGrantRotation( bone, parentBone.quaternion, grant.ratio );
  684. }
  685. }
  686. return this;
  687. }
  688. addGrantRotation( bone, q, ratio ) {
  689. _q.set( 0, 0, 0, 1 );
  690. _q.slerp( q, ratio );
  691. bone.quaternion.multiply( _q );
  692. return this;
  693. }
  694. }
  695. THREE.MMDAnimationHelper = MMDAnimationHelper;
  696. } )();