forked from webaverse/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcamera-manager.js
473 lines (414 loc) · 16.2 KB
/
camera-manager.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
import * as THREE from 'three';
import {getRenderer, camera} from './renderer.js';
// import * as notifications from './notifications.js';
import metaversefile from 'metaversefile';
import physicsManager from './physics-manager.js';
import {shakeAnimationSpeed} from './constants.js';
import Simplex from './simplex-noise.js';
// import alea from './alea.js';
import * as sounds from './sounds.js';
import {minFov, maxFov, midFov} from './constants.js';
const localVector = new THREE.Vector3();
const localVector2 = new THREE.Vector3();
const localVector3 = new THREE.Vector3();
const localQuaternion = new THREE.Quaternion();
const localEuler = new THREE.Euler();
const cameraOffset = new THREE.Vector3();
let cameraOffsetTargetZ = cameraOffset.z;
let cameraOffsetZ = cameraOffset.z;
const rayVectorZero = new THREE.Vector3(0,0,0);
const rayVectorUp = new THREE.Vector3(0,1,0);
const rayStartPos = new THREE.Vector3(0,0,0);
const rayDirection = new THREE.Vector3(0,0,0);
const rayOffsetPoint = new THREE.Vector3(0,0,0);
const rayMatrix = new THREE.Matrix4();
const rayQuaternion = new THREE.Quaternion();
const rayOriginArray = [new THREE.Vector3(0,0,0),new THREE.Vector3(0,0,0),new THREE.Vector3(0,0,0),new THREE.Vector3(0,0,0),new THREE.Vector3(0,0,0),new THREE.Vector3(0,0,0)]; // 6 elements
const rayDirectionArray = [new THREE.Quaternion(),new THREE.Quaternion(),new THREE.Quaternion(),new THREE.Quaternion(),new THREE.Quaternion(),new THREE.Quaternion()]; // 6 elements
// const lastCameraQuaternion = new THREE.Quaternion();
// let lastCameraZ = 0;
// let lastCameraValidZ = 0;
const seed = 'camera';
const shakeNoise = new Simplex(seed);
class Shake extends THREE.Object3D {
constructor(intensity, startTime, radius, decay) {
super();
this.intensity = intensity;
this.startTime = startTime;
this.radius = radius;
this.decay = decay;
}
}
function lerpNum(value1, value2, amount) {
amount = amount < 0 ? 0 : amount;
amount = amount > 1 ? 1 : amount;
return value1 + (value2 - value1) * amount;
}
// Raycast from player to camera corner
function initCameraRayParams(arrayIndex,originPoint) {
const localPlayer = metaversefile.useLocalPlayer();
rayDirection.subVectors(localPlayer.position, originPoint).normalize();
rayMatrix.lookAt(rayDirection,rayVectorZero,rayVectorUp);
rayQuaternion.setFromRotationMatrix(rayMatrix);
// Slightly move ray start position towards camera (to avoid hair,hat)
rayStartPos.copy(localPlayer.position);
rayStartPos.add( rayDirection.multiplyScalar(0.1) );
rayOriginArray[arrayIndex].copy(rayStartPos);
rayDirectionArray[arrayIndex].copy(rayQuaternion);
}
// Raycast from player postition with small offset
function initOffsetRayParams(arrayIndex,originPoint) {
const localPlayer = metaversefile.useLocalPlayer();
rayDirection.subVectors(localPlayer.position, camera.position).normalize();
rayMatrix.lookAt(rayDirection,rayVectorZero,rayVectorUp);
rayQuaternion.setFromRotationMatrix(rayMatrix);
rayOriginArray[arrayIndex].copy(originPoint);
rayDirectionArray[arrayIndex].copy(rayQuaternion);
}
class CameraManager extends EventTarget {
constructor() {
super();
this.pointerLockElement = null;
// this.pointerLockEpoch = 0;
this.shakes = [];
this.focus = false;
this.lastFocusChangeTime = 0;
this.fovFactor = 0;
this.lastNonzeroDirectionVector = new THREE.Vector3(0, 0, -1);
this.lastNonzeroDirectionVector = new THREE.Vector3(0, 0, -1);
this.fovFactor = 0;
document.addEventListener('pointerlockchange', e => {
let pointerLockElement = document.pointerLockElement;
const renderer = getRenderer();
if (pointerLockElement !== null && pointerLockElement !== renderer.domElement) {
pointerLockElement = null;
}
this.pointerLockElement = pointerLockElement;
this.dispatchEvent(new MessageEvent('pointerlockchange', {
data: {
pointerLockElement,
},
}));
});
}
focusCamera(position) {
camera.lookAt(position);
camera.updateMatrixWorld();
}
async requestPointerLock() {
// const localPointerLockEpoch = ++this.pointerLockEpoch;
for (const options of [
{
unadjustedMovement: true,
},
undefined
]) {
try {
await new Promise((accept, reject) => {
const renderer = getRenderer();
if (document.pointerLockElement !== renderer.domElement) {
const _pointerlockchange = e => {
// if (localPointerLockEpoch === this.pointerLockEpoch) {
accept();
// }
_cleanup();
};
document.addEventListener('pointerlockchange', _pointerlockchange);
const _pointerlockerror = err => {
reject(err);
_cleanup();
/* notifications.addNotification(`\
<i class="icon fa fa-mouse-pointer"></i>
<div class=wrap>
<div class=label>Whoa there!</div>
<div class=text>
Hold up champ! The browser wants you to slow down.
</div>
<div class=close-button>✕</div>
</div>
`, {
timeout: 3000,
}); */
};
document.addEventListener('pointerlockerror', _pointerlockerror);
const _cleanup = () => {
document.removeEventListener('pointerlockchange', _pointerlockchange);
document.removeEventListener('pointerlockerror', _pointerlockerror);
};
renderer.domElement.requestPointerLock(options)
.catch(_pointerlockerror);
} else {
accept();
}
});
break;
} catch (err) {
console.warn(err);
continue;
}
}
}
exitPointerLock() {
document.exitPointerLock();
}
getMode() {
const f = -cameraOffset.z;
if (f < 0.5) {
return 'firstperson';
} else {
return 'isometric';
}
}
getCameraOffset() {
return cameraOffset;
}
handleWheelEvent(e) {
// e.preventDefault();
cameraOffsetTargetZ = Math.min(cameraOffsetTargetZ - e.deltaY * 0.01, 0);
}
addShake(position, intensity, radius, decay) {
const startTime = performance.now();
const shake = new Shake(intensity, startTime, radius, decay);
shake.position.copy(position);
this.shakes.push(shake);
return shake;
}
flushShakes() {
if (this.shakes.length > 0) {
const now = performance.now();
this.shakes = this.shakes.filter(shake => now < shake.startTime + shake.decay);
}
}
getShakeFactor() {
let result = 0;
if (this.shakes.length > 0) {
const now = performance.now();
for (const shake of this.shakes) {
const distanceFactor = Math.min(Math.max((shake.radius - shake.position.distanceTo(camera.position))/shake.radius, 0), 1);
const timeFactor = Math.min(Math.max(1 - (now - shake.startTime) / shake.decay, 0), 1);
// console.log('get shake factor', shake.intensity * distanceFactor * timeFactor, shake.intensity, distanceFactor, timeFactor);
result += shake.intensity * distanceFactor * timeFactor;
}
}
return result;
}
setFocus(focus) {
if (focus !== this.focus) {
this.focus = focus;
this.lastFocusChangeTime = performance.now();
if (this.focus) {
sounds.playSoundName('zTargetCenter');
}
this.dispatchEvent(new MessageEvent('focuschange', {
data: {
focus,
},
}));
}
}
updatePost(timestamp, timeDiff) {
// console.log('camera manager update post');
const localPlayer = metaversefile.useLocalPlayer();
const renderer = getRenderer();
const session = renderer.xr.getSession();
const startMode = this.getMode();
const _setCameraOffset = () => {
let newVal = cameraOffsetTargetZ;
let hasIntersection = false;
// Camera - Top left
initCameraRayParams(0,rayStartPos.set(-1, 1, ( camera.near + camera.far ) / ( camera.near - camera.far )).unproject( camera ));
// Camera - Bottom left
initCameraRayParams(1,rayStartPos.set(-1, -1, ( camera.near + camera.far ) / ( camera.near - camera.far )).unproject( camera ));
// Camera - Top right
initCameraRayParams(2,rayStartPos.set(1, 1, ( camera.near + camera.far ) / ( camera.near - camera.far )).unproject( camera ));
// Camera - Bottom right
initCameraRayParams(3,rayStartPos.set(1, -1, ( camera.near + camera.far ) / ( camera.near - camera.far )).unproject( camera ));
// Player postition - offset to left
rayStartPos.copy(localPlayer.position);
rayOffsetPoint.set(-1, 0, 0);
rayOffsetPoint.applyQuaternion(camera.quaternion);
rayOffsetPoint.normalize();
rayStartPos.add(rayOffsetPoint);
initOffsetRayParams(4,rayStartPos);
// Player postition - offset to right
rayStartPos.copy(localPlayer.position);
rayOffsetPoint.set(1, 0, 0);
rayOffsetPoint.applyQuaternion(camera.quaternion);
rayOffsetPoint.normalize();
rayStartPos.add(rayOffsetPoint);
initOffsetRayParams(5,rayStartPos);
let collisionArray = physicsManager.raycastArray(rayOriginArray, rayDirectionArray, 6);
// Check collision from player to camera corners
for(let i=0;i<4;i++) {
if ((collisionArray.hit[i] === 1) && (collisionArray.distance[i] <= -1 * newVal)) {
if (newVal < (-1 * (collisionArray.distance[i]-0.15))) {
newVal = (-1 * (collisionArray.distance[i]-0.15));
hasIntersection = true;
//console.log(i + " " + collisionArray.distance[i]+ " " + collisionArray.hit[i]);
}
}
}
// Check collision from player pos and small offset to left and right - to camera center
let offsetCollisionCount = 0;
for(let i=4;i<6;i++) {
if ((collisionArray.hit[i] === 1) && (collisionArray.distance[i] <= (-1 * cameraOffsetTargetZ))) {
offsetCollisionCount++;
}
}
// Discard collision with small objects
if (hasIntersection && (offsetCollisionCount === 0)) {
hasIntersection = false;
newVal = cameraOffsetTargetZ;
}
/* // Remove jitter when there is no movement
if (lastCameraQuaternion.equals(camera.quaternion) && lastCameraZ === cameraOffsetTargetZ) {
if (lastCameraValidZ < newVal) {
lastCameraValidZ = newVal;
}
if (newVal < lastCameraValidZ)
newVal = lastCameraValidZ;
} else { */
// lastCameraQuaternion.copy(camera.quaternion);
// lastCameraZ = cameraOffsetTargetZ;
// lastCameraValidZ = cameraOffsetTargetZ;
// }
// Slow zoom out if there is no intersection
cameraOffsetZ = lerpNum(cameraOffsetZ,newVal, 0.2);
// Fast zoom in to the point of intersection
if (hasIntersection) {
cameraOffsetZ = newVal;
}
const zDiff = Math.abs(cameraOffset.z - cameraOffsetZ);
if (zDiff === 0) {
// nothing
} else {
// camera.position.add(localVector.copy(cameraOffset).applyQuaternion(camera.quaternion));
cameraOffset.z = cameraOffsetZ;
// camera.position.sub(localVector.copy(cameraOffset).applyQuaternion(camera.quaternion));
// camera.updateMatrixWorld();
}
};
_setCameraOffset();
const endMode = this.getMode();
if (endMode !== startMode) {
this.dispatchEvent(new MessageEvent('modechange', {
data: {
mode: endMode,
},
}));
}
const _setCameraToAvatar = () => {
if (!this.focus) {
const avatarCameraOffset = session ? rayVectorZero : this.getCameraOffset();
const avatarHeight = localPlayer.avatar ? localPlayer.avatar.height : 0;
const crouchOffset = avatarHeight * (1 - localPlayer.getCrouchFactor()) * 0.5;
switch (endMode) {
case 'firstperson': {
if (localPlayer.avatar) {
const boneNeck = localPlayer.avatar.foundModelBones['Neck'];
const boneEyeL = localPlayer.avatar.foundModelBones['Eye_L'];
const boneEyeR = localPlayer.avatar.foundModelBones['Eye_R'];
const boneHead = localPlayer.avatar.foundModelBones['Head'];
boneNeck.quaternion.setFromEuler(localEuler.set(Math.min(camera.rotation.x * -0.5, 0.6), 0, 0, 'XYZ'));
boneNeck.updateMatrixWorld();
if (boneEyeL && boneEyeR) {
boneEyeL.matrixWorld.decompose(localVector, localQuaternion, localVector3);
boneEyeR.matrixWorld.decompose(localVector2, localQuaternion, localVector3);
localVector3.copy(localVector.add(localVector2).multiplyScalar(0.5));
} else {
boneHead.matrixWorld.decompose(localVector, localQuaternion, localVector3);
localVector.add(localVector2.set(0, 0, 0.1).applyQuaternion(localQuaternion));
localVector3.copy(localVector);
}
} else {
localVector3.copy(localPlayer.position);
}
camera.position.copy(localVector3)
.sub(localVector.copy(avatarCameraOffset).applyQuaternion(camera.quaternion));
break;
}
case 'isometric': {
camera.position.copy(localPlayer.position)
.sub(
localVector.copy(avatarCameraOffset)
.applyQuaternion(camera.quaternion)
);
break;
}
default: {
throw new Error('invalid camera mode: ' + cameraMode);
}
}
camera.position.y -= crouchOffset;
} else {
cameraOffsetTargetZ = -1;
const targetPosition = localVector.copy(localPlayer.position)
.add(localVector2.set(0, 0, -cameraOffsetTargetZ).applyQuaternion(localPlayer.quaternion));
const targetQuaternion = localPlayer.quaternion;
camera.position.lerp(targetPosition, 0.2);
camera.quaternion.slerp(targetQuaternion, 0.2);
// camera.updateMatrixWorld();
}
};
_setCameraToAvatar();
const _setCameraFov = () => {
if (!renderer.xr.getSession()) {
const focusTime = (timestamp - this.lastFocusChangeTime) / 300;
if (focusTime < 1) {
// const fovInTime = 3;
// const fovOutTime = 0.3;
this.fovFactor = 0;
const a = this.focus ? minFov : midFov;
const b = this.focus ? midFov : minFov;
camera.fov = a * (1 - focusTime) + focusTime * b;
camera.updateProjectionMatrix();
} else if (this.focus) {
this.fovFactor = 0;
camera.fov = midFov;
camera.updateProjectionMatrix();
} else {
const fovInTime = 3;
const fovOutTime = 0.3;
const narutoRun = localPlayer.getAction('narutoRun');
if (narutoRun) {
if (this.lastNonzeroDirectionVector.z < 0) {
this.fovFactor += timeDiff / 1000 / fovInTime;
} else {
this.fovFactor -= timeDiff / 1000 / fovInTime;
}
} else {
this.fovFactor -= timeDiff / 1000 / fovOutTime;
}
this.fovFactor = Math.min(Math.max(this.fovFactor, 0), 1);
camera.fov = minFov + Math.pow(this.fovFactor, 0.75) * (maxFov - minFov);
camera.updateProjectionMatrix();
}
}
};
_setCameraFov();
const _shakeCamera = () => {
this.flushShakes();
const shakeFactor = this.getShakeFactor();
if (shakeFactor > 0) {
const baseTime = timestamp/1000 * shakeAnimationSpeed;
const timeOffset = 1000;
const ndc = f => (-0.5 + f) * 2;
let index = 0;
const randomValue = () => ndc(shakeNoise.noise1D(baseTime + timeOffset * index++));
localVector.set(
randomValue(),
randomValue(),
randomValue()
)
.normalize()
.multiplyScalar(shakeFactor * randomValue());
camera.position.add(localVector);
// camera.updateMatrixWorld();
}
};
_shakeCamera();
camera.updateMatrixWorld();
}
};
const cameraManager = new CameraManager();
export default cameraManager;