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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
import {
	AnimationMixer,
	Object3D,
	Quaternion,
	Vector3
} from 'three';
import { CCDIKSolver } from '../animation/CCDIKSolver.js';
import { MMDPhysics } from '../animation/MMDPhysics.js';

/**
 * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader
 * with MMD special features as IK, Grant, and Physics.
 *
 * Dependencies
 *  - ammo.js https://github.com/kripken/ammo.js
 *  - MMDPhysics
 *  - CCDIKSolver
 *
 * TODO
 *  - more precise grant skinning support.
 */
class MMDAnimationHelper {

	/**
	 * @param {Object} params - (optional)
	 * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true.
	 * @param {Number} params.afterglow - Default is 0.0.
	 * @param {boolean} params.resetPhysicsOnLoop - Default is true.
	 */
	constructor( params = {} ) {

		this.meshes = [];

		this.camera = null;
		this.cameraTarget = new Object3D();
		this.cameraTarget.name = 'target';

		this.audio = null;
		this.audioManager = null;

		this.objects = new WeakMap();

		this.configuration = {
			sync: params.sync !== undefined ? params.sync : true,
			afterglow: params.afterglow !== undefined ? params.afterglow : 0.0,
			resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true,
			pmxAnimation: params.pmxAnimation !== undefined ? params.pmxAnimation : false
		};

		this.enabled = {
			animation: true,
			ik: true,
			grant: true,
			physics: true,
			cameraAnimation: true
		};

		this.onBeforePhysics = function ( /* mesh */ ) {};

		// experimental
		this.sharedPhysics = false;
		this.masterPhysics = null;

	}

	/**
	 * Adds an Three.js Object to helper and setups animation.
	 * The anmation durations of added objects are synched
	 * if this.configuration.sync is true.
	 *
	 * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object
	 * @param {Object} params - (optional)
	 * @param {THREE.AnimationClip|Array<THREE.AnimationClip>} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined.
	 * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true.
	 * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60.
	 * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65.
	 * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3.
	 * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ).
	 * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0.
	 * @return {MMDAnimationHelper}
	 */
	add( object, params = {} ) {

		if ( object.isSkinnedMesh ) {

			this._addMesh( object, params );

		} else if ( object.isCamera ) {

			this._setupCamera( object, params );

		} else if ( object.type === 'Audio' ) {

			this._setupAudio( object, params );

		} else {

			throw new Error( 'THREE.MMDAnimationHelper.add: '
				+ 'accepts only '
				+ 'THREE.SkinnedMesh or '
				+ 'THREE.Camera or '
				+ 'THREE.Audio instance.' );

		}

		if ( this.configuration.sync ) this._syncDuration();

		return this;

	}

	/**
	 * Removes an Three.js Object from helper.
	 *
	 * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object
	 * @return {MMDAnimationHelper}
	 */
	remove( object ) {

		if ( object.isSkinnedMesh ) {

			this._removeMesh( object );

		} else if ( object.isCamera ) {

			this._clearCamera( object );

		} else if ( object.type === 'Audio' ) {

			this._clearAudio( object );

		} else {

			throw new Error( 'THREE.MMDAnimationHelper.remove: '
				+ 'accepts only '
				+ 'THREE.SkinnedMesh or '
				+ 'THREE.Camera or '
				+ 'THREE.Audio instance.' );

		}

		if ( this.configuration.sync ) this._syncDuration();

		return this;

	}

	/**
	 * Updates the animation.
	 *
	 * @param {Number} delta
	 * @return {MMDAnimationHelper}
	 */
	update( delta ) {

		if ( this.audioManager !== null ) this.audioManager.control( delta );

		for ( let i = 0; i < this.meshes.length; i ++ ) {

			this._animateMesh( this.meshes[ i ], delta );

		}

		if ( this.sharedPhysics ) this._updateSharedPhysics( delta );

		if ( this.camera !== null ) this._animateCamera( this.camera, delta );

		return this;

	}

	/**
	 * Changes the pose of SkinnedMesh as VPD specifies.
	 *
	 * @param {THREE.SkinnedMesh} mesh
	 * @param {Object} vpd - VPD content parsed MMDParser
	 * @param {Object} params - (optional)
	 * @param {boolean} params.resetPose - Default is true.
	 * @param {boolean} params.ik - Default is true.
	 * @param {boolean} params.grant - Default is true.
	 * @return {MMDAnimationHelper}
	 */
	pose( mesh, vpd, params = {} ) {

		if ( params.resetPose !== false ) mesh.pose();

		const bones = mesh.skeleton.bones;
		const boneParams = vpd.bones;

		const boneNameDictionary = {};

		for ( let i = 0, il = bones.length; i < il; i ++ ) {

			boneNameDictionary[ bones[ i ].name ] = i;

		}

		const vector = new Vector3();
		const quaternion = new Quaternion();

		for ( let i = 0, il = boneParams.length; i < il; i ++ ) {

			const boneParam = boneParams[ i ];
			const boneIndex = boneNameDictionary[ boneParam.name ];

			if ( boneIndex === undefined ) continue;

			const bone = bones[ boneIndex ];
			bone.position.add( vector.fromArray( boneParam.translation ) );
			bone.quaternion.multiply( quaternion.fromArray( boneParam.quaternion ) );

		}

		mesh.updateMatrixWorld( true );

		// PMX animation system special path
		if ( this.configuration.pmxAnimation &&
			mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) {

			const sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() );
			const ikSolver = params.ik !== false ? this._createCCDIKSolver( mesh ) : null;
			const grantSolver = params.grant !== false ? this.createGrantSolver( mesh ) : null;
			this._animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver );

		} else {

			if ( params.ik !== false ) {

				this._createCCDIKSolver( mesh ).update();

			}

			if ( params.grant !== false ) {

				this.createGrantSolver( mesh ).update();

			}

		}

		return this;

	}

	/**
	 * Enabes/Disables an animation feature.
	 *
	 * @param {string} key
	 * @param {boolean} enabled
	 * @return {MMDAnimationHelper}
	 */
	enable( key, enabled ) {

		if ( this.enabled[ key ] === undefined ) {

			throw new Error( 'THREE.MMDAnimationHelper.enable: '
				+ 'unknown key ' + key );

		}

		this.enabled[ key ] = enabled;

		if ( key === 'physics' ) {

			for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {

				this._optimizeIK( this.meshes[ i ], enabled );

			}

		}

		return this;

	}

	/**
	 * Creates an GrantSolver instance.
	 *
	 * @param {THREE.SkinnedMesh} mesh
	 * @return {GrantSolver}
	 */
	createGrantSolver( mesh ) {

		return new GrantSolver( mesh, mesh.geometry.userData.MMD.grants );

	}

	// private methods

	_addMesh( mesh, params ) {

		if ( this.meshes.indexOf( mesh ) >= 0 ) {

			throw new Error( 'THREE.MMDAnimationHelper._addMesh: '
				+ 'SkinnedMesh \'' + mesh.name + '\' has already been added.' );

		}

		this.meshes.push( mesh );
		this.objects.set( mesh, { looped: false } );

		this._setupMeshAnimation( mesh, params.animation );

		if ( params.physics !== false ) {

			this._setupMeshPhysics( mesh, params );

		}

		return this;

	}

	_setupCamera( camera, params ) {

		if ( this.camera === camera ) {

			throw new Error( 'THREE.MMDAnimationHelper._setupCamera: '
				+ 'Camera \'' + camera.name + '\' has already been set.' );

		}

		if ( this.camera ) this.clearCamera( this.camera );

		this.camera = camera;

		camera.add( this.cameraTarget );

		this.objects.set( camera, {} );

		if ( params.animation !== undefined ) {

			this._setupCameraAnimation( camera, params.animation );

		}

		return this;

	}

	_setupAudio( audio, params ) {

		if ( this.audio === audio ) {

			throw new Error( 'THREE.MMDAnimationHelper._setupAudio: '
				+ 'Audio \'' + audio.name + '\' has already been set.' );

		}

		if ( this.audio ) this.clearAudio( this.audio );

		this.audio = audio;
		this.audioManager = new AudioManager( audio, params );

		this.objects.set( this.audioManager, {
			duration: this.audioManager.duration
		} );

		return this;

	}

	_removeMesh( mesh ) {

		let found = false;
		let writeIndex = 0;

		for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {

			if ( this.meshes[ i ] === mesh ) {

				this.objects.delete( mesh );
				found = true;

				continue;

			}

			this.meshes[ writeIndex ++ ] = this.meshes[ i ];

		}

		if ( ! found ) {

			throw new Error( 'THREE.MMDAnimationHelper._removeMesh: '
				+ 'SkinnedMesh \'' + mesh.name + '\' has not been added yet.' );

		}

		this.meshes.length = writeIndex;

		return this;

	}

	_clearCamera( camera ) {

		if ( camera !== this.camera ) {

			throw new Error( 'THREE.MMDAnimationHelper._clearCamera: '
				+ 'Camera \'' + camera.name + '\' has not been set yet.' );

		}

		this.camera.remove( this.cameraTarget );

		this.objects.delete( this.camera );
		this.camera = null;

		return this;

	}

	_clearAudio( audio ) {

		if ( audio !== this.audio ) {

			throw new Error( 'THREE.MMDAnimationHelper._clearAudio: '
				+ 'Audio \'' + audio.name + '\' has not been set yet.' );

		}

		this.objects.delete( this.audioManager );

		this.audio = null;
		this.audioManager = null;

		return this;

	}

	_setupMeshAnimation( mesh, animation ) {

		const objects = this.objects.get( mesh );

		if ( animation !== undefined ) {

			const animations = Array.isArray( animation )
				? animation : [ animation ];

			objects.mixer = new AnimationMixer( mesh );

			for ( let i = 0, il = animations.length; i < il; i ++ ) {

				objects.mixer.clipAction( animations[ i ] ).play();

			}

			// TODO: find a workaround not to access ._clip looking like a private property
			objects.mixer.addEventListener( 'loop', function ( event ) {

				const tracks = event.action._clip.tracks;

				if ( tracks.length > 0 && tracks[ 0 ].name.slice( 0, 6 ) !== '.bones' ) return;

				objects.looped = true;

			} );

		}

		objects.ikSolver = this._createCCDIKSolver( mesh );
		objects.grantSolver = this.createGrantSolver( mesh );

		return this;

	}

	_setupCameraAnimation( camera, animation ) {

		const animations = Array.isArray( animation )
			? animation : [ animation ];

		const objects = this.objects.get( camera );

		objects.mixer = new AnimationMixer( camera );

		for ( let i = 0, il = animations.length; i < il; i ++ ) {

			objects.mixer.clipAction( animations[ i ] ).play();

		}

	}

	_setupMeshPhysics( mesh, params ) {

		const objects = this.objects.get( mesh );

		// shared physics is experimental

		if ( params.world === undefined && this.sharedPhysics ) {

			const masterPhysics = this._getMasterPhysics();

			if ( masterPhysics !== null ) world = masterPhysics.world; // eslint-disable-line no-undef

		}

		objects.physics = this._createMMDPhysics( mesh, params );

		if ( objects.mixer && params.animationWarmup !== false ) {

			this._animateMesh( mesh, 0 );
			objects.physics.reset();

		}

		objects.physics.warmup( params.warmup !== undefined ? params.warmup : 60 );

		this._optimizeIK( mesh, true );

	}

	_animateMesh( mesh, delta ) {

		const objects = this.objects.get( mesh );

		const mixer = objects.mixer;
		const ikSolver = objects.ikSolver;
		const grantSolver = objects.grantSolver;
		const physics = objects.physics;
		const looped = objects.looped;

		if ( mixer && this.enabled.animation ) {

			// alternate solution to save/restore bones but less performant?
			//mesh.pose();
			//this._updatePropertyMixersBuffer( mesh );

			this._restoreBones( mesh );

			mixer.update( delta );

			this._saveBones( mesh );

			// PMX animation system special path
			if ( this.configuration.pmxAnimation &&
				mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) {

				if ( ! objects.sortedBonesData ) objects.sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() );

				this._animatePMXMesh(
					mesh,
					objects.sortedBonesData,
					ikSolver && this.enabled.ik ? ikSolver : null,
					grantSolver && this.enabled.grant ? grantSolver : null
				);

			} else {

				if ( ikSolver && this.enabled.ik ) {

					mesh.updateMatrixWorld( true );
					ikSolver.update();

				}

				if ( grantSolver && this.enabled.grant ) {

					grantSolver.update();

				}

			}

		}

		if ( looped === true && this.enabled.physics ) {

			if ( physics && this.configuration.resetPhysicsOnLoop ) physics.reset();

			objects.looped = false;

		}

		if ( physics && this.enabled.physics && ! this.sharedPhysics ) {

			this.onBeforePhysics( mesh );
			physics.update( delta );

		}

	}

	// Sort bones in order by 1. transformationClass and 2. bone index.
	// In PMX animation system, bone transformations should be processed
	// in this order.
	_sortBoneDataArray( boneDataArray ) {

		return boneDataArray.sort( function ( a, b ) {

			if ( a.transformationClass !== b.transformationClass ) {

				return a.transformationClass - b.transformationClass;

			} else {

				return a.index - b.index;

			}

		} );

	}

	// PMX Animation system is a bit too complex and doesn't great match to
	// Three.js Animation system. This method attempts to simulate it as much as
	// possible but doesn't perfectly simulate.
	// This method is more costly than the regular one so
	// you are recommended to set constructor parameter "pmxAnimation: true"
	// only if your PMX model animation doesn't work well.
	// If you need better method you would be required to write your own.
	_animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver ) {

		_quaternionIndex = 0;
		_grantResultMap.clear();

		for ( let i = 0, il = sortedBonesData.length; i < il; i ++ ) {

			updateOne( mesh, sortedBonesData[ i ].index, ikSolver, grantSolver );

		}

		mesh.updateMatrixWorld( true );
		return this;

	}

	_animateCamera( camera, delta ) {

		const mixer = this.objects.get( camera ).mixer;

		if ( mixer && this.enabled.cameraAnimation ) {

			mixer.update( delta );

			camera.updateProjectionMatrix();

			camera.up.set( 0, 1, 0 );
			camera.up.applyQuaternion( camera.quaternion );
			camera.lookAt( this.cameraTarget.position );

		}

	}

	_optimizeIK( mesh, physicsEnabled ) {

		const iks = mesh.geometry.userData.MMD.iks;
		const bones = mesh.geometry.userData.MMD.bones;

		for ( let i = 0, il = iks.length; i < il; i ++ ) {

			const ik = iks[ i ];
			const links = ik.links;

			for ( let j = 0, jl = links.length; j < jl; j ++ ) {

				const link = links[ j ];

				if ( physicsEnabled === true ) {

					// disable IK of the bone the corresponding rigidBody type of which is 1 or 2
					// because its rotation will be overriden by physics
					link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true;

				} else {

					link.enabled = true;

				}

			}

		}

	}

	_createCCDIKSolver( mesh ) {

		if ( CCDIKSolver === undefined ) {

			throw new Error( 'THREE.MMDAnimationHelper: Import CCDIKSolver.' );

		}

		return new CCDIKSolver( mesh, mesh.geometry.userData.MMD.iks );

	}

	_createMMDPhysics( mesh, params ) {

		if ( MMDPhysics === undefined ) {

			throw new Error( 'THREE.MMDPhysics: Import MMDPhysics.' );

		}

		return new MMDPhysics(
			mesh,
			mesh.geometry.userData.MMD.rigidBodies,
			mesh.geometry.userData.MMD.constraints,
			params );

	}

	/*
	 * Detects the longest duration and then sets it to them to sync.
	 * TODO: Not to access private properties ( ._actions and ._clip )
	 */
	_syncDuration() {

		let max = 0.0;

		const objects = this.objects;
		const meshes = this.meshes;
		const camera = this.camera;
		const audioManager = this.audioManager;

		// get the longest duration

		for ( let i = 0, il = meshes.length; i < il; i ++ ) {

			const mixer = this.objects.get( meshes[ i ] ).mixer;

			if ( mixer === undefined ) continue;

			for ( let j = 0; j < mixer._actions.length; j ++ ) {

				const clip = mixer._actions[ j ]._clip;

				if ( ! objects.has( clip ) ) {

					objects.set( clip, {
						duration: clip.duration
					} );

				}

				max = Math.max( max, objects.get( clip ).duration );

			}

		}

		if ( camera !== null ) {

			const mixer = this.objects.get( camera ).mixer;

			if ( mixer !== undefined ) {

				for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) {

					const clip = mixer._actions[ i ]._clip;

					if ( ! objects.has( clip ) ) {

						objects.set( clip, {
							duration: clip.duration
						} );

					}

					max = Math.max( max, objects.get( clip ).duration );

				}

			}

		}

		if ( audioManager !== null ) {

			max = Math.max( max, objects.get( audioManager ).duration );

		}

		max += this.configuration.afterglow;

		// update the duration

		for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {

			const mixer = this.objects.get( this.meshes[ i ] ).mixer;

			if ( mixer === undefined ) continue;

			for ( let j = 0, jl = mixer._actions.length; j < jl; j ++ ) {

				mixer._actions[ j ]._clip.duration = max;

			}

		}

		if ( camera !== null ) {

			const mixer = this.objects.get( camera ).mixer;

			if ( mixer !== undefined ) {

				for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) {

					mixer._actions[ i ]._clip.duration = max;

				}

			}

		}

		if ( audioManager !== null ) {

			audioManager.duration = max;

		}

	}

	// workaround

	_updatePropertyMixersBuffer( mesh ) {

		const mixer = this.objects.get( mesh ).mixer;

		const propertyMixers = mixer._bindings;
		const accuIndex = mixer._accuIndex;

		for ( let i = 0, il = propertyMixers.length; i < il; i ++ ) {

			const propertyMixer = propertyMixers[ i ];
			const buffer = propertyMixer.buffer;
			const stride = propertyMixer.valueSize;
			const offset = ( accuIndex + 1 ) * stride;

			propertyMixer.binding.getValue( buffer, offset );

		}

	}

	/*
	 * Avoiding these two issues by restore/save bones before/after mixer animation.
	 *
	 * 1. PropertyMixer used by AnimationMixer holds cache value in .buffer.
	 *    Calculating IK, Grant, and Physics after mixer animation can break
	 *    the cache coherency.
	 *
	 * 2. Applying Grant two or more times without reset the posing breaks model.
	 */
	_saveBones( mesh ) {

		const objects = this.objects.get( mesh );

		const bones = mesh.skeleton.bones;

		let backupBones = objects.backupBones;

		if ( backupBones === undefined ) {

			backupBones = new Float32Array( bones.length * 7 );
			objects.backupBones = backupBones;

		}

		for ( let i = 0, il = bones.length; i < il; i ++ ) {

			const bone = bones[ i ];
			bone.position.toArray( backupBones, i * 7 );
			bone.quaternion.toArray( backupBones, i * 7 + 3 );

		}

	}

	_restoreBones( mesh ) {

		const objects = this.objects.get( mesh );

		const backupBones = objects.backupBones;

		if ( backupBones === undefined ) return;

		const bones = mesh.skeleton.bones;

		for ( let i = 0, il = bones.length; i < il; i ++ ) {

			const bone = bones[ i ];
			bone.position.fromArray( backupBones, i * 7 );
			bone.quaternion.fromArray( backupBones, i * 7 + 3 );

		}

	}

	// experimental

	_getMasterPhysics() {

		if ( this.masterPhysics !== null ) return this.masterPhysics;

		for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {

			const physics = this.meshes[ i ].physics;

			if ( physics !== undefined && physics !== null ) {

				this.masterPhysics = physics;
				return this.masterPhysics;

			}

		}

		return null;

	}

	_updateSharedPhysics( delta ) {

		if ( this.meshes.length === 0 || ! this.enabled.physics || ! this.sharedPhysics ) return;

		const physics = this._getMasterPhysics();

		if ( physics === null ) return;

		for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {

			const p = this.meshes[ i ].physics;

			if ( p !== null && p !== undefined ) {

				p.updateRigidBodies();

			}

		}

		physics.stepSimulation( delta );

		for ( let i = 0, il = this.meshes.length; i < il; i ++ ) {

			const p = this.meshes[ i ].physics;

			if ( p !== null && p !== undefined ) {

				p.updateBones();

			}

		}

	}

}

// Keep working quaternions for less GC
const _quaternions = [];
let _quaternionIndex = 0;

function getQuaternion() {

	if ( _quaternionIndex >= _quaternions.length ) {

		_quaternions.push( new Quaternion() );

	}

	return _quaternions[ _quaternionIndex ++ ];

}

// Save rotation whose grant and IK are already applied
// used by grant children
const _grantResultMap = new Map();

function updateOne( mesh, boneIndex, ikSolver, grantSolver ) {

	const bones = mesh.skeleton.bones;
	const bonesData = mesh.geometry.userData.MMD.bones;
	const boneData = bonesData[ boneIndex ];
	const bone = bones[ boneIndex ];

	// Return if already updated by being referred as a grant parent.
	if ( _grantResultMap.has( boneIndex ) ) return;

	const quaternion = getQuaternion();

	// Initialize grant result here to prevent infinite loop.
	// If it's referred before updating with actual result later
	// result without applyting IK or grant is gotten
	// but better than composing of infinite loop.
	_grantResultMap.set( boneIndex, quaternion.copy( bone.quaternion ) );

	// @TODO: Support global grant and grant position
	if ( grantSolver && boneData.grant &&
		! boneData.grant.isLocal && boneData.grant.affectRotation ) {

		const parentIndex = boneData.grant.parentIndex;
		const ratio = boneData.grant.ratio;

		if ( ! _grantResultMap.has( parentIndex ) ) {

			updateOne( mesh, parentIndex, ikSolver, grantSolver );

		}

		grantSolver.addGrantRotation( bone, _grantResultMap.get( parentIndex ), ratio );

	}

	if ( ikSolver && boneData.ik ) {

		// @TODO: Updating world matrices every time solving an IK bone is
		// costly. Optimize if possible.
		mesh.updateMatrixWorld( true );
		ikSolver.updateOne( boneData.ik );

		// No confident, but it seems the grant results with ik links should be updated?
		const links = boneData.ik.links;

		for ( let i = 0, il = links.length; i < il; i ++ ) {

			const link = links[ i ];

			if ( link.enabled === false ) continue;

			const linkIndex = link.index;

			if ( _grantResultMap.has( linkIndex ) ) {

				_grantResultMap.set( linkIndex, _grantResultMap.get( linkIndex ).copy( bones[ linkIndex ].quaternion ) );

			}

		}

	}

	// Update with the actual result here
	quaternion.copy( bone.quaternion );

}

//

class AudioManager {

	/**
	 * @param {THREE.Audio} audio
	 * @param {Object} params - (optional)
	 * @param {Nuumber} params.delayTime
	 */
	constructor( audio, params = {} ) {

		this.audio = audio;

		this.elapsedTime = 0.0;
		this.currentTime = 0.0;
		this.delayTime = params.delayTime !== undefined
			? params.delayTime : 0.0;

		this.audioDuration = this.audio.buffer.duration;
		this.duration = this.audioDuration + this.delayTime;

	}

	/**
	 * @param {Number} delta
	 * @return {AudioManager}
	 */
	control( delta ) {

		this.elapsed += delta;
		this.currentTime += delta;

		if ( this._shouldStopAudio() ) this.audio.stop();
		if ( this._shouldStartAudio() ) this.audio.play();

		return this;

	}

	// private methods

	_shouldStartAudio() {

		if ( this.audio.isPlaying ) return false;

		while ( this.currentTime >= this.duration ) {

			this.currentTime -= this.duration;

		}

		if ( this.currentTime < this.delayTime ) return false;

		// 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration
		if ( ( this.currentTime - this.delayTime ) > this.audioDuration ) return false;

		return true;

	}

	_shouldStopAudio() {

		return this.audio.isPlaying &&
			this.currentTime >= this.duration;

	}

}

const _q = new Quaternion();

/**
 * Solver for Grant (Fuyo in Japanese. I just google translated because
 * Fuyo may be MMD specific term and may not be common word in 3D CG terms.)
 * Grant propagates a bone's transform to other bones transforms even if
 * they are not children.
 * @param {THREE.SkinnedMesh} mesh
 * @param {Array<Object>} grants
 */
class GrantSolver {

	constructor( mesh, grants = [] ) {

		this.mesh = mesh;
		this.grants = grants;

	}

	/**
	 * Solve all the grant bones
	 * @return {GrantSolver}
	 */
	update() {

		const grants = this.grants;

		for ( let i = 0, il = grants.length; i < il; i ++ ) {

			this.updateOne( grants[ i ] );

		}

		return this;

	}

	/**
	 * Solve a grant bone
	 * @param {Object} grant - grant parameter
	 * @return {GrantSolver}
	 */
	updateOne( grant ) {

		const bones = this.mesh.skeleton.bones;
		const bone = bones[ grant.index ];
		const parentBone = bones[ grant.parentIndex ];

		if ( grant.isLocal ) {

			// TODO: implement
			if ( grant.affectPosition ) {

			}

			// TODO: implement
			if ( grant.affectRotation ) {

			}

		} else {

			// TODO: implement
			if ( grant.affectPosition ) {

			}

			if ( grant.affectRotation ) {

				this.addGrantRotation( bone, parentBone.quaternion, grant.ratio );

			}

		}

		return this;

	}

	addGrantRotation( bone, q, ratio ) {

		_q.set( 0, 0, 0, 1 );
		_q.slerp( q, ratio );
		bone.quaternion.multiply( _q );

		return this;

	}

}

export { MMDAnimationHelper };