-
Notifications
You must be signed in to change notification settings - Fork 209
/
character-controller.js
1483 lines (1370 loc) · 51.1 KB
/
character-controller.js
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
/*
this file is responisible for maintaining player state that is network-replicated.
*/
import {murmurhash3} from './procgen/murmurhash3.js';
import {WsAudioDecoder} from 'wsrtc/ws-codec.js';
import {ensureAudioContext, getAudioContext} from 'wsrtc/ws-audio-context.js';
import {getAudioDataBuffer} from 'wsrtc/ws-util.js';
import * as THREE from 'three';
import * as Z from 'zjs';
import {getRenderer, scene, camera, dolly} from './renderer.js';
import physicsManager from './physics-manager.js';
import {world} from './world.js';
// import cameraManager from './camera-manager.js';
import physx from './physx.js';
import audioManager from './audio-manager.js';
import metaversefile from 'metaversefile';
import {
actionsMapName,
appsMapName,
playersMapName,
crouchMaxTime,
activateMaxTime,
// useMaxTime,
aimTransitionMaxTime,
avatarInterpolationFrameRate,
avatarInterpolationTimeDelay,
avatarInterpolationNumFrames,
// groundFriction,
// defaultVoicePackName,
voiceEndpointBaseUrl,
numLoadoutSlots,
} from './constants.js';
import {AppManager} from './app-manager.js';
import {CharacterPhysics} from './character-physics.js';
import {CharacterHups} from './character-hups.js';
import {CharacterSfx} from './character-sfx.js';
import {CharacterHitter} from './character-hitter.js';
import {CharacterBehavior} from './character-behavior.js';
import {CharacterFx} from './character-fx.js';
import {VoicePack, VoicePackVoicer} from './voice-output/voice-pack-voicer.js';
import {VoiceEndpoint, VoiceEndpointVoicer} from './voice-output/voice-endpoint-voicer.js';
import {BinaryInterpolant, BiActionInterpolant, UniActionInterpolant, InfiniteActionInterpolant, PositionInterpolant, QuaternionInterpolant} from './interpolants.js';
import {applyPlayerToAvatar, switchAvatar} from './player-avatar-binding.js';
import {
defaultPlayerName,
defaultPlayerBio,
} from './ai/lore/lore-model.js';
// import * as sounds from './sounds.js';
import musicManager from './music-manager.js';
import {makeId, clone, unFrustumCull, enableShadows} from './util.js';
import overrides from './overrides.js';
// import * as voices from './voices.js';
const localVector = new THREE.Vector3();
const localVector2 = new THREE.Vector3();
// const localQuaternion = new THREE.Quaternion();
// const localQuaternion2 = new THREE.Quaternion();
const localMatrix = new THREE.Matrix4();
const localMatrix2 = new THREE.Matrix4();
const localArray3 = [0, 0, 0];
const localArray4 = [0, 0, 0, 0];
const zeroVector = new THREE.Vector3(0, 0, 0);
const upVector = new THREE.Vector3(0, 1, 0);
const _getSession = () => {
const renderer = getRenderer();
const session = renderer.xr.getSession();
return session;
};
const physicsScene = physicsManager.getScene();
function makeCancelFn() {
let live = true;
return {
isLive() {
return live;
},
cancel() {
live = false;
},
};
}
/* function loadPhysxAuxCharacterCapsule() {
const avatarHeight = this.avatar.height;
const radius = baseRadius/heightFactor * avatarHeight;
const height = avatarHeight - radius*2;
const halfHeight = height/2;
const position = this.position.clone()
.add(new THREE.Vector3(0, -avatarHeight/2, 0));
const physicsMaterial = new THREE.Vector3(0, 0, 0);
const physicsObject = physicsScene.addCapsuleGeometry(
position,
localQuaternion.copy(this.quaternion)
.premultiply(
localQuaternion2.setFromAxisAngle(
localVector.set(0, 0, 1),
Math.PI/2
)
),
radius,
halfHeight,
physicsMaterial,
true
);
physicsObject.name = 'characterCapsuleAux';
physicsScene.setGravityEnabled(physicsObject, false);
physicsScene.setLinearLockFlags(physicsObject.physicsId, false, false, false);
physicsScene.setAngularLockFlags(physicsObject.physicsId, false, false, false);
this.physicsObject = physicsObject;
} */
class PlayerHand extends THREE.Object3D {
constructor() {
super();
this.pointer = 0;
this.grab = 0;
this.enabled = false;
}
}
class PlayerBase extends THREE.Object3D {
constructor() {
super();
this.name = defaultPlayerName;
this.bio = defaultPlayerBio;
this.characterHups = new CharacterHups(this);
this.characterSfx = new CharacterSfx(this);
this.characterFx = new CharacterFx(this);
this.characterHitter = new CharacterHitter(this);
this.characterBehavior = new CharacterBehavior(this);
this.leftHand = new PlayerHand();
this.rightHand = new PlayerHand();
this.hands = [
this.leftHand,
this.rightHand,
];
this.detached = false;
this.avatar = null;
this.appManager = new AppManager({
appsMap: null,
});
this.appManager.addEventListener('appadd', e => {
if (!this.detached) {
const app = e.data;
scene.add(app);
}
});
this.appManager.addEventListener('appremove', e => {
if (!this.detached) {
const app = e.data;
app.parent && app.parent.remove(app);
}
});
this.headTarget = new THREE.Vector3();
this.headTargetInverted = false;
this.headTargetEnabled = false;
this.eyeballTarget = new THREE.Vector3();
this.eyeballTargetEnabled = false;
this.voicePack = null;
this.voiceEndpoint = null;
}
findAction(fn) {
const actions = this.getActionsState();
for (const action of actions) {
if (fn(action)) {
return action;
}
}
return null;
}
findActionIndex(fn) {
const actions = this.getActionsState();
let i = 0;
for (const action of actions) {
if (fn(action)) {
return i;
}
i++
}
return -1;
}
getAction(type) {
const actions = this.getActionsState();
for (const action of actions) {
if (action.type === type) {
return action;
}
}
return null;
}
getActionByActionId(actionId) {
const actions = this.getActionsState();
for (const action of actions) {
if (action.actionId === actionId) {
return action;
}
}
return null;
}
getActionIndex(type) {
const actions = this.getActionsState();
let i = 0;
for (const action of actions) {
if (action.type === type) {
return i;
}
i++;
}
return -1;
}
indexOfAction(action) {
const actions = this.getActionsState();
let i = 0;
for (const a of actions) {
if (a === action) {
return i;
}
i++;
}
return -1;
}
hasAction(type) {
const actions = this.getActionsState();
for (const action of actions) {
if (action.type === type) {
return true;
}
}
return false;
}
async setVoicePack({audioUrl, indexUrl}) {
const self = this;
// this.playersArray.doc.transact(function tx() {
const voiceSpec = JSON.stringify({audioUrl, indexUrl, endpointUrl: self.voiceEndpoint ? self.voiceEndpoint.url : ''});
self.playerMap.set('voiceSpec', voiceSpec);
// });
await this.loadVoicePack({audioUrl, indexUrl})
}
async loadVoicePack({audioUrl, indexUrl}) {
this.voicePack = await VoicePack.load({
audioUrl,
indexUrl,
});
this.updateVoicer();
}
setVoiceEndpoint(voiceId) {
if (!voiceId) throw new Error('voice Id is null')
const self = this;
const url = `${voiceEndpointBaseUrl}?voice=${encodeURIComponent(voiceId)}`;
this.playersArray.doc.transact(function tx() {
let oldVoiceSpec = self.playerMap.get('voiceSpec');
if (oldVoiceSpec) {
oldVoiceSpec = JSON.parse(oldVoiceSpec);
const voiceSpec = JSON.stringify({audioUrl: oldVoiceSpec.audioUrl, indexUrl: oldVoiceSpec.indexUrl, endpointUrl: url});
self.playerMap.set('voiceSpec', voiceSpec);
} else {
const voiceSpec = JSON.stringify({audioUrl: self.voicePack?.audioUrl, indexUrl: self.voicePack?.indexUrl, endpointUrl: url})
self.playerMap.set('voiceSpec', voiceSpec);
}
});
this.loadVoiceEndpoint(url)
}
loadVoiceEndpoint(url) {
if (url) {
this.voiceEndpoint = new VoiceEndpoint(url);
} else {
this.voiceEndpoint = null;
}
this.updateVoicer();
}
getVoice() {
return this.voiceEndpoint || this.voicePack;
}
updateVoicer() {
const voice = this.getVoice();
if (voice instanceof VoicePack) {
const {syllableFiles, audioBuffer} = voice;
this.voicer = new VoicePackVoicer(syllableFiles, audioBuffer, this);
} else if (voice instanceof VoiceEndpoint) {
this.voicer = new VoiceEndpointVoicer(voice, this);
} else if (voice === null) {
this.voicer = null;
} else {
throw new Error('invalid voice');
}
}
async fetchThemeSong() {
const avatarApp = this.getAvatarApp();
const npcComponent = avatarApp.getComponent('npc');
const npcThemeSongUrl = npcComponent?.themeSongUrl;
return await PlayerBase.fetchThemeSong(npcThemeSongUrl);
}
static async fetchThemeSong(npcThemeSongUrl) {
if (npcThemeSongUrl) {
return await musicManager.fetchMusic(npcThemeSongUrl);
} else {
return null;
}
}
getCrouchFactor() {
return 1 - 0.4 * this.actionInterpolants.crouch.getNormalized();
/* let factor = 1;
factor *= 1 - 0.4 * this.actionInterpolants.crouch.getNormalized();
return factor; */
}
wear(app, {
loadoutIndex = -1,
} = {}) {
const _getNextLoadoutIndex = () => {
let loadoutIndex = -1;
const usedIndexes = Array(8).fill(false);
for (const action of this.getActionsState()) {
if (action.type === 'wear') {
usedIndexes[action.loadoutIndex] = true;
}
}
for (let i = 0; i < usedIndexes.length; i++) {
if (!usedIndexes[i]) {
loadoutIndex = i;
break;
}
}
return loadoutIndex;
};
if (loadoutIndex === -1) {
loadoutIndex = _getNextLoadoutIndex();
}
if (loadoutIndex >= 0 && loadoutIndex < numLoadoutSlots) {
const _removeOldApp = () => {
const actions = this.getActionsState();
let oldLoadoutAction = null;
for (let i = 0; i < actions.length; i++) {
const action = actions.get(i);
if (action.type === 'wear' && action.loadoutIndex === loadoutIndex) {
oldLoadoutAction = action;
break;
}
}
if (oldLoadoutAction) {
const app = this.appManager.getAppByInstanceId(oldLoadoutAction.instanceId);
this.unwear(app, {
destroy: true,
});
}
};
_removeOldApp();
const _transplantNewApp = () => {
if (world.appManager.hasTrackedApp(app.instanceId)) {
world.appManager.transplantApp(app, this.appManager);
} else {
// console.warn('need to transplant unowned app', app, world.appManager, this.appManager);
// debugger;
}
};
_transplantNewApp();
const _disableAppPhysics = () => {
// don't disable physics if the app is a pet
if (!app.hasComponent('pet')) {
const physicsObjects = app.getPhysicsObjects();
for (const physicsObject of physicsObjects) {
physicsScene.disableGeometryQueries(physicsObject);
physicsScene.disableGeometry(physicsObject);
}
}
};
_disableAppPhysics();
const wearComponent = app.getComponent('wear');
const holdAnimation = wearComponent? wearComponent.holdAnimation : null;
const _addAction = () => {
this.addAction({
type: 'wear',
instanceId: app.instanceId,
loadoutIndex,
holdAnimation,
});
};
_addAction();
const _emitEvents = () => {
app.dispatchEvent({
type: 'wearupdate',
player: this,
wear: true,
loadoutIndex,
holdAnimation,
});
this.dispatchEvent({
type: 'wearupdate',
app,
wear: true,
loadoutIndex,
holdAnimation,
});
};
_emitEvents();
}
}
unwear(app, {
destroy = false,
dropStartPosition = null,
dropDirection = null,
} = {}) {
const wearActionIndex = this.findActionIndex(({type, instanceId}) => {
return type === 'wear' && instanceId === app.instanceId;
});
if (wearActionIndex !== -1) {
const wearAction = this.getActionsState().get(wearActionIndex);
const loadoutIndex = wearAction.loadoutIndex;
const _setAppTransform = () => {
if (dropStartPosition && dropDirection) {
const physicsObjects = app.getPhysicsObjects();
if (physicsObjects.length > 0) {
const physicsObject = physicsObjects[0];
physicsObject.position.copy(dropStartPosition);
physicsObject.quaternion.copy(this.quaternion);
physicsObject.updateMatrixWorld();
physicsScene.setTransform(physicsObject, true);
physicsScene.setVelocity(physicsObject, localVector.copy(dropDirection).multiplyScalar(5)/*.add(this.characterPhysics.velocity)*/, true);
physicsScene.setAngularVelocity(physicsObject, zeroVector, true);
app.position.copy(physicsObject.position);
app.quaternion.copy(physicsObject.quaternion);
app.scale.copy(physicsObject.scale);
app.matrix.copy(physicsObject.matrix);
app.matrixWorld.copy(physicsObject.matrixWorld);
} else {
app.position.copy(dropStartPosition);
app.quaternion.setFromRotationMatrix(
localMatrix.lookAt(
localVector.set(0, 0, 0),
localVector2.set(dropDirection.x, 0, dropDirection.z).normalize(),
upVector
)
);
app.scale.set(1, 1, 1);
app.updateMatrixWorld();
}
app.lastMatrix.copy(app.matrixWorld);
} else {
const avatarHeight = this.avatar ? this.avatar.height : 0;
app.position.copy(this.position)
.add(localVector.set(0, -avatarHeight + 0.5, -0.5).applyQuaternion(this.quaternion));
app.quaternion.identity();
app.scale.set(1, 1, 1);
app.updateMatrixWorld();
}
};
if(!app.getComponent('sit') && !app.getComponent('pet')){
_setAppTransform();
}
const _enableAppPhysics = () => {
if (!app.hasComponent('pet')) {
const physicsObjects = app.getPhysicsObjects();
for (const physicsObject of physicsObjects) {
physicsScene.enableGeometryQueries(physicsObject);
physicsScene.enableGeometry(physicsObject);
}
}
};
_enableAppPhysics();
const _removeApp = () => {
this.removeActionIndex(wearActionIndex);
if (this.appManager.hasTrackedApp(app.instanceId)) {
if (destroy) {
this.appManager.removeApp(app);
app.destroy();
} else {
this.appManager.transplantApp(app, world.appManager);
}
} else {
// console.warn('need to transplant unowned app', app, this.appManager, world.appManager);
// debugger;
}
};
_removeApp();
const _emitEvents = () => {
app.dispatchEvent({
type: 'wearupdate',
player: this,
wear: false,
loadoutIndex,
});
this.dispatchEvent({
type: 'wearupdate',
app,
wear: false,
loadoutIndex,
});
};
_emitEvents();
}
}
setTarget(target) { // set both head and eyeball target;
if (target) {
this.headTarget.copy(target);
this.headTargetInverted = true;
this.headTargetEnabled = true;
this.eyeballTarget.copy(target);
this.eyeballTargetEnabled = true;
} else {
this.headTargetEnabled = false;
this.eyeballTargetEnabled = false;
}
}
destroy() {
this.characterHups.destroy();
this.characterSfx.destroy();
this.characterFx.destroy();
this.characterBehavior.destroy();
}
}
const controlActionTypes = [
'jump',
'fallLoop',
'land',
'crouch',
'fly',
'sit',
'swim',
];
class StatePlayer extends PlayerBase {
constructor({
playerId = makeId(5),
playersArray = new Z.Doc().getArray(playersMapName),
} = {}) {
super();
this.playerId = playerId;
this.playerIdInt = murmurhash3(playerId);
this.playersArray = null;
this.playerMap = null;
this.microphoneMediaStream = null;
this.characterPhysics = new CharacterPhysics(this);
this.avatarEpoch = 0;
this.syncAvatarCancelFn = null;
this.unbindFns = [];
this.transform = new Float32Array(7);
this.bindState(playersArray);
}
isBound() {
return !!this.playersArray;
}
unbindState() {
if (this.isBound()) {
this.playersArray = null;
this.playerMap = null;
}
}
detachState() {
throw new Error('called abstract method');
}
attachState(oldState) {
throw new Error('called abstract method');
}
bindCommonObservers() {
const actions = this.getActionsState();
let lastActions = actions.toJSON();
const observeActionsFn = () => {
const nextActions = Array.from(this.getActionsState());
for (const nextAction of nextActions) {
if (!lastActions.some(lastAction => lastAction.actionId === nextAction.actionId)) {
this.dispatchEvent({
type: 'actionadd',
action: nextAction,
});
// console.log('add action', nextAction);
}
}
for (const lastAction of lastActions) {
if (!nextActions.some(nextAction => nextAction.actionId === lastAction.actionId)) {
this.dispatchEvent({
type: 'actionremove',
action: lastAction,
});
// console.log('remove action', lastAction);
}
}
// console.log('actions changed');
lastActions = nextActions;
};
actions.observe(observeActionsFn);
this.unbindFns.push(actions.unobserve.bind(actions, observeActionsFn));
}
unbindCommonObservers() {
for (const unbindFn of this.unbindFns) {
unbindFn();
}
this.unbindFns.length = 0;
}
bindState(nextPlayersArray) {
// latch old state
const oldState = this.detachState();
// unbind
this.unbindState();
this.appManager.unbindState();
this.unbindCommonObservers();
// note: leave the old state as is. it is the host's responsibility to garbage collect us when we disconnect.
// blindly add to new state
this.playersArray = nextPlayersArray;
this.attachState(oldState);
this.bindCommonObservers();
}
getAvatarInstanceId() {
return this.playerMap.get('avatar');
}
// serializers
getPosition() {
return this.position.toArray(localArray3) ?? [0, 0, 0];
}
getQuaternion() {
return this.quaternion.toArray(localArray4) ?? [0, 0, 0, 1];
}
async syncAvatar() {
if (this.syncAvatarCancelFn) {
this.syncAvatarCancelFn.cancel();
this.syncAvatarCancelFn = null;
}
const cancelFn = makeCancelFn();
this.syncAvatarCancelFn = cancelFn;
const instanceId = this.getAvatarInstanceId();
// remove last app
if (this.avatar) {
const oldPeerOwnerAppManager = this.appManager.getPeerOwnerAppManager(this.avatar.app.instanceId);
if (oldPeerOwnerAppManager) {
// console.log('transplant last app');
this.appManager.transplantApp(this.avatar.app, oldPeerOwnerAppManager);
} else {
// console.log('remove last app', this.avatar.app);
// this.appManager.removeTrackedApp(this.avatar.app.instanceId);
}
}
const _setNextAvatarApp = app => {
(() => {
const avatar = switchAvatar(this.avatar, app);
if (!cancelFn.isLive()) return;
this.avatar = avatar;
this.dispatchEvent({
type: 'avatarchange',
app,
avatar,
});
this.characterPhysics.loadCharacterController(this.avatar.width, this.avatar.height);
if (this.isLocalPlayer) {
physicsScene.disableGeometryQueries(this.characterPhysics.characterController);
}
})();
this.dispatchEvent({
type: 'avatarupdate',
app,
});
};
if (instanceId) {
// add next app from player app manager
const nextAvatarApp = this.appManager.getAppByInstanceId(instanceId);
// console.log('add next avatar local', nextAvatarApp);
if (nextAvatarApp) {
_setNextAvatarApp(nextAvatarApp);
} else {
// add next app from world app manager
const nextAvatarApp = world.appManager.getAppByInstanceId(instanceId);
// console.log('add next avatar world', nextAvatarApp);
if (nextAvatarApp) {
world.appManager.transplantApp(nextAvatarApp, this.appManager);
_setNextAvatarApp(nextAvatarApp);
} else {
// add next app from currently loading apps
const addPromise = this.appManager.pendingAddPromises.get(instanceId);
if (addPromise) {
const nextAvatarApp = await addPromise;
if (!cancelFn.isLive()) return;
_setNextAvatarApp(nextAvatarApp);
} else {
console.warn('switching avatar to instanceId that does not exist in any app manager', instanceId);
}
}
}
}
this.syncAvatarCancelFn = null;
}
setSpawnPoint(position, quaternion) {
this.position.copy(position);
this.quaternion.copy(quaternion);
camera.position.copy(position);
camera.quaternion.copy(quaternion);
camera.updateMatrixWorld();
if (this.characterPhysics.characterController) {
this.characterPhysics.setPosition(position);
}
}
getActionsByType(type) {
const actions = this.getActionsState();
const typedActions = Array.from(actions).filter(action => action.type === type);
return typedActions;
}
getActions() {
return this.getActionsState();
}
getActionsState() {
let actionsArray = this.playerMap.has(actionsMapName) ? this.playerMap.get(actionsMapName, Z.Array) : null;
if (!actionsArray) {
actionsArray = new Z.Array();
this.playerMap.set(actionsMapName, actionsArray);
}
return actionsArray;
}
getActionsArray() {
return this.isBound() ? Array.from(this.getActionsState()) : [];
}
getAppsState() {
let appsArray = this.playerMap.has(appsMapName) ? this.playerMap.get(appsMapName, Z.Array) : null;
if (!appsArray) {
appsArray = new Z.Array();
this.playerMap.set(appsMapName, appsArray);
}
return appsArray;
}
getAppsArray() {
return this.isBound() ? Array.from(this.getAppsState()) : [];
}
addAction(action) {
action = clone(action);
action.actionId = makeId(5);
this.getActionsState().push([action]);
return action;
}
removeAction(type) {
const actions = this.getActionsState();
let i = 0;
for (const action of actions) {
if (action.type === type) {
actions.delete(i);
break;
}
i++;
}
}
removeActionIndex(index) {
this.getActionsState().delete(index);
}
clearActions() {
const actionsState = this.getActionsState();
const numActions = actionsState.length;
for (let i = numActions - 1; i >= 0; i--) {
this.removeActionIndex(i);
}
}
setControlAction(action) {
const actions = this.getActionsState();
for (let i = 0; i < actions.length; i++) {
const action = actions.get(i);
const isControlAction = controlActionTypes.includes(action.type);
if (isControlAction) {
actions.delete(i);
i--;
}
}
actions.push([action]);
}
new() {
const self = this;
this.playersArray.doc.transact(function tx() {
const actions = self.getActionsState();
while (actions.length > 0) {
actions.delete(actions.length - 1);
}
this.playerMap.delete('avatar');
const apps = self.getAppsState();
while (apps.length > 0) {
apps.delete(apps.length - 1);
}
});
}
save() {
const actions = this.getActionsState();
const apps = this.getAppsState();
return JSON.stringify({
// actions: actions.toJSON(),
avatar: this.getAvatarInstanceId(),
apps: apps.toJSON(),
});
}
load(s) {
const j = JSON.parse(s);
// console.log('load', j);
const self = this;
this.playersArray.doc.transact(function tx() {
const actions = self.getActionsState();
while (actions.length > 0) {
actions.delete(actions.length - 1);
}
const avatar = self.getAvatarInstanceId();
if (avatar) {
this.playerMap.set('avatar', avatar);
}
const apps = self.getAppsState();
if (Array.isArray(j?.apps)) {
for (const app of j.apps) {
apps.push([app]);
}
}
});
}
destroy() {
this.unbindState();
this.appManager.unbindState();
this.appManager.destroy();
super.destroy();
}
}
class InterpolatedPlayer extends StatePlayer {
constructor(opts) {
super(opts);
this.positionInterpolant = new PositionInterpolant(() => this.getPosition(), avatarInterpolationTimeDelay, avatarInterpolationNumFrames);
this.quaternionInterpolant = new QuaternionInterpolant(() => this.getQuaternion(), avatarInterpolationTimeDelay, avatarInterpolationNumFrames);
this.actionBinaryInterpolants = {
crouch: new BinaryInterpolant(() => this.hasAction('crouch'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
activate: new BinaryInterpolant(() => this.hasAction('activate'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
use: new BinaryInterpolant(() => this.hasAction('use'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
pickUp: new BinaryInterpolant(() => this.hasAction('pickUp'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
aim: new BinaryInterpolant(() => this.hasAction('aim'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
narutoRun: new BinaryInterpolant(() => this.hasAction('narutoRun'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
fly: new BinaryInterpolant(() => this.hasAction('fly'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
jump: new BinaryInterpolant(() => this.hasAction('jump'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
doubleJump: new BinaryInterpolant(() => this.hasAction('doubleJump'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
land: new BinaryInterpolant(() => this.hasAction('land'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
dance: new BinaryInterpolant(() => this.hasAction('dance'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
emote: new BinaryInterpolant(() => this.hasAction('emote'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
// throw: new BinaryInterpolant(() => this.hasAction('throw'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
// chargeJump: new BinaryInterpolant(() => this.hasAction('chargeJump'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
// standCharge: new BinaryInterpolant(() => this.hasAction('standCharge'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
fallLoop: new BinaryInterpolant(() => this.hasAction('fallLoop'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
// swordSideSlash: new BinaryInterpolant(() => this.hasAction('swordSideSlash'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
// swordTopDownSlash: new BinaryInterpolant(() => this.hasAction('swordTopDownSlash'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
hurt: new BinaryInterpolant(() => this.hasAction('hurt'), avatarInterpolationTimeDelay, avatarInterpolationNumFrames),
};
this.actionBinaryInterpolantsArray = Object.keys(this.actionBinaryInterpolants).map(k => this.actionBinaryInterpolants[k]);
this.actionInterpolants = {
crouch: new BiActionInterpolant(() => this.actionBinaryInterpolants.crouch.get(), 0, crouchMaxTime),
activate: new UniActionInterpolant(() => this.actionBinaryInterpolants.activate.get(), 0, activateMaxTime),
use: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.use.get(), 0),
pickUp: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.pickUp.get(), 0),
unuse: new InfiniteActionInterpolant(() => !this.actionBinaryInterpolants.use.get(), 0),
aim: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.aim.get(), 0),
aimRightTransition: new BiActionInterpolant(() => this.hasAction('aim') && this.hands[0].enabled, 0, aimTransitionMaxTime),
aimLeftTransition: new BiActionInterpolant(() => this.hasAction('aim') && this.hands[1].enabled, 0, aimTransitionMaxTime),
narutoRun: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.narutoRun.get(), 0),
fly: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.fly.get(), 0),
jump: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.jump.get(), 0),
doubleJump: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.doubleJump.get(), 0),
land: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.land.get(), 0),
fallLoop: new InfiniteActionInterpolant(() => this.hasAction('fallLoop'), 0),
fallLoopTransition: new BiActionInterpolant(() => this.actionBinaryInterpolants.fallLoop.get(), 0, 300),
dance: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.dance.get(), 0),
emote: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.emote.get(), 0),
// throw: new UniActionInterpolant(() => this.actionBinaryInterpolants.throw.get(), 0, throwMaxTime),
// chargeJump: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.chargeJump.get(), 0),
// standCharge: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.standCharge.get(), 0),
// fallLoop: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.fallLoop.get(), 0),
// swordSideSlash: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.swordSideSlash.get(), 0),
// swordTopDownSlash: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.swordTopDownSlash.get(), 0),
hurt: new InfiniteActionInterpolant(() => this.actionBinaryInterpolants.hurt.get(), 0),
movements: new InfiniteActionInterpolant(() => {
const ioManager = metaversefile.useIoManager();
return ioManager.keys.up || ioManager.keys.down || ioManager.keys.left || ioManager.keys.right;
}, 0),
movementsTransition: new BiActionInterpolant(() => {
const ioManager = metaversefile.useIoManager();
return ioManager.keys.up || ioManager.keys.down || ioManager.keys.left || ioManager.keys.right;
}, 0, crouchMaxTime),
sprint: new BiActionInterpolant(() => {
const ioManager = metaversefile.useIoManager();
return ioManager.keys.shift;
}, 0, crouchMaxTime),
};
this.actionInterpolantsArray = Object.keys(this.actionInterpolants).map(k => this.actionInterpolants[k]);
this.avatarBinding = {
position: this.positionInterpolant.get(),
quaternion: this.quaternionInterpolant.get(),
};
}
/* update(timestamp, timeDiff) {
if (!this.avatar) return; // avatar takes time to load, ignore until it does
this.updateInterpolation(timeDiff);
const mirrors = metaversefile.getMirrors();
applyPlayerToAvatar(this, null, this.avatar, mirrors);
const timeDiffS = timeDiff / 1000;
this.characterSfx.update(timestamp, timeDiffS);
this.characterFx.update(timestamp, timeDiffS);
this.characterPhysics.update(timestamp, timeDiffS);
this.characterHitter.update(timestamp, timeDiffS);
this.characterBehavior.update(timestamp, timeDiffS);
this.avatar.update(timestamp, timeDiff);
} */
updateInterpolation(timeDiff) {
this.positionInterpolant.update(timeDiff);
this.quaternionInterpolant.update(timeDiff);
for (const actionBinaryInterpolant of this.actionBinaryInterpolantsArray) {
actionBinaryInterpolant.update(timeDiff);
}
for (const actionInterpolant of this.actionInterpolantsArray) {
actionInterpolant.update(timeDiff);
}
}
}
class UninterpolatedPlayer extends StatePlayer {
constructor(opts) {
super(opts);
UninterpolatedPlayer.init.apply(this, arguments)
}
static init() {
this.actionInterpolants = {
crouch: new BiActionInterpolant(() => this.hasAction('crouch'), 0, crouchMaxTime),
activate: new UniActionInterpolant(() => this.hasAction('activate'), 0, activateMaxTime),
use: new InfiniteActionInterpolant(() => this.hasAction('use'), 0),
pickUp: new InfiniteActionInterpolant(() => this.hasAction('pickUp'), 0),
unuse: new InfiniteActionInterpolant(() => !this.hasAction('use'), 0),
aim: new InfiniteActionInterpolant(() => this.hasAction('aim'), 0),
aimRightTransition: new BiActionInterpolant(() => this.hasAction('aim') && this.hands[0].enabled, 0, aimTransitionMaxTime),
aimLeftTransition: new BiActionInterpolant(() => this.hasAction('aim') && this.hands[1].enabled, 0, aimTransitionMaxTime),
narutoRun: new InfiniteActionInterpolant(() => this.hasAction('narutoRun'), 0),
fly: new InfiniteActionInterpolant(() => this.hasAction('fly'), 0),
swim: new InfiniteActionInterpolant(() => this.hasAction('swim'), 0),
jump: new InfiniteActionInterpolant(() => this.hasAction('jump'), 0),
doubleJump: new InfiniteActionInterpolant(() => this.hasAction('doubleJump'), 0),
land: new InfiniteActionInterpolant(() => !this.hasAction('jump') && !this.hasAction('fallLoop') && !this.hasAction('fly'), 0),
dance: new BiActionInterpolant(() => this.hasAction('dance'), 0, crouchMaxTime),
emote: new BiActionInterpolant(() => this.hasAction('emote'), 0, crouchMaxTime),
movements: new InfiniteActionInterpolant(() => {
const ioManager = metaversefile.useIoManager();
return ioManager.keys.up || ioManager.keys.down || ioManager.keys.left || ioManager.keys.right;
}, 0),
movementsTransition: new BiActionInterpolant(() => {
const ioManager = metaversefile.useIoManager();
return ioManager.keys.up || ioManager.keys.down || ioManager.keys.left || ioManager.keys.right;
}, 0, crouchMaxTime),
sprint: new BiActionInterpolant(() => {
const ioManager = metaversefile.useIoManager();
return ioManager.keys.shift;
}, 0, crouchMaxTime),
// throw: new UniActionInterpolant(() => this.hasAction('throw'), 0, throwMaxTime),
// chargeJump: new InfiniteActionInterpolant(() => this.hasAction('chargeJump'), 0),
// standCharge: new InfiniteActionInterpolant(() => this.hasAction('standCharge'), 0),
fallLoop: new InfiniteActionInterpolant(() => this.hasAction('fallLoop'), 0),
fallLoopTransition: new BiActionInterpolant(() => this.hasAction('fallLoop'), 0, 300),
// swordSideSlash: new InfiniteActionInterpolant(() => this.hasAction('swordSideSlash'), 0),