@playcanvas/supersplat-viewer 1.21.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/index.js CHANGED
@@ -19534,7 +19534,7 @@ const tmpMat4 = new Mat4();
19534
19534
  const tmpQuat = new Quat();
19535
19535
  const position = new Vec3();
19536
19536
  const invParentWtm = new Mat4();
19537
- const rotation$5 = new Quat();
19537
+ const rotation$4 = new Quat();
19538
19538
  const invParentRot = new Quat();
19539
19539
  const matrix = new Mat4();
19540
19540
  const target = new Vec3();
@@ -19908,16 +19908,16 @@ class GraphNode extends EventHandler {
19908
19908
  }
19909
19909
  setRotation(x, y, z, w) {
19910
19910
  if (x instanceof Quat) {
19911
- rotation$5.copy(x);
19911
+ rotation$4.copy(x);
19912
19912
  } else {
19913
- rotation$5.set(x, y, z, w);
19913
+ rotation$4.set(x, y, z, w);
19914
19914
  }
19915
19915
  if (this._parent === null) {
19916
- this.localRotation.copy(rotation$5);
19916
+ this.localRotation.copy(rotation$4);
19917
19917
  } else {
19918
19918
  const parentRot = this._parent.getRotation();
19919
19919
  invParentRot.copy(parentRot).invert();
19920
- this.localRotation.copy(invParentRot).mul(rotation$5);
19920
+ this.localRotation.copy(invParentRot).mul(rotation$4);
19921
19921
  }
19922
19922
  if (!this._dirtyLocal) {
19923
19923
  this._dirtifyLocal();
@@ -20082,8 +20082,8 @@ class GraphNode extends EventHandler {
20082
20082
  up$2.set(ux, uy, uz);
20083
20083
  }
20084
20084
  matrix.setLookAt(this.getPosition(), target, up$2);
20085
- rotation$5.setFromMat4(matrix);
20086
- this.setRotation(rotation$5);
20085
+ rotation$4.setFromMat4(matrix);
20086
+ this.setRotation(rotation$4);
20087
20087
  }
20088
20088
  translate(x, y, z) {
20089
20089
  if (x instanceof Vec3) {
@@ -20107,23 +20107,23 @@ class GraphNode extends EventHandler {
20107
20107
  }
20108
20108
  }
20109
20109
  rotate(x, y, z) {
20110
- rotation$5.setFromEulerAngles(x, y, z);
20110
+ rotation$4.setFromEulerAngles(x, y, z);
20111
20111
  if (this._parent === null) {
20112
- this.localRotation.mul2(rotation$5, this.localRotation);
20112
+ this.localRotation.mul2(rotation$4, this.localRotation);
20113
20113
  } else {
20114
20114
  const rot = this.getRotation();
20115
20115
  const parentRot = this._parent.getRotation();
20116
20116
  invParentRot.copy(parentRot).invert();
20117
- rotation$5.mul2(invParentRot, rotation$5);
20118
- this.localRotation.mul2(rotation$5, rot);
20117
+ rotation$4.mul2(invParentRot, rotation$4);
20118
+ this.localRotation.mul2(rotation$4, rot);
20119
20119
  }
20120
20120
  if (!this._dirtyLocal) {
20121
20121
  this._dirtifyLocal();
20122
20122
  }
20123
20123
  }
20124
20124
  rotateLocal(x, y, z) {
20125
- rotation$5.setFromEulerAngles(x, y, z);
20126
- this.localRotation.mul(rotation$5);
20125
+ rotation$4.setFromEulerAngles(x, y, z);
20126
+ this.localRotation.mul(rotation$4);
20127
20127
  if (!this._dirtyLocal) {
20128
20128
  this._dirtifyLocal();
20129
20129
  }
@@ -73164,7 +73164,7 @@ class CameraFrame {
73164
73164
  }
73165
73165
 
73166
73166
  const tmpV1$1 = new Vec3();
73167
- const rotation$4 = new Quat();
73167
+ const rotation$3 = new Quat();
73168
73168
  class Pose {
73169
73169
  copy(other) {
73170
73170
  return this.set(other.position, other.angles, other.distance);
@@ -73215,7 +73215,7 @@ class Pose {
73215
73215
  return this;
73216
73216
  }
73217
73217
  getFocus(out) {
73218
- return rotation$4.setFromEulerAngles(this.angles).transformVector(Vec3.FORWARD, out).mulScalar(this.distance).add(this.position);
73218
+ return rotation$3.setFromEulerAngles(this.angles).transformVector(Vec3.FORWARD, out).mulScalar(this.distance).add(this.position);
73219
73219
  }
73220
73220
  constructor(position = Vec3.ZERO, angles = Vec3.ZERO, distance = 0){
73221
73221
  this.position = new Vec3();
@@ -73369,58 +73369,6 @@ const movementState = ()=>{
73369
73369
 
73370
73370
  const damp$1 = (damping, dt)=>1 - Math.pow(damping, dt * 1000);
73371
73371
 
73372
- const offset$2 = new Vec3();
73373
- const angles$1 = new Vec3();
73374
- const forward$1 = new Vec3();
73375
- const right$2 = new Vec3();
73376
- const up$1 = new Vec3();
73377
- const rotation$3 = new Quat();
73378
- let FlyController$1 = class FlyController extends InputController$1 {
73379
- set pitchRange(value) {
73380
- this._targetPose.pitchRange.copy(value);
73381
- this._pose.copy(this._targetPose.rotate(Vec3.ZERO));
73382
- }
73383
- get pitchRange() {
73384
- return this._targetPose.pitchRange;
73385
- }
73386
- set yawRange(value) {
73387
- this._targetPose.yawRange.copy(value);
73388
- this._pose.copy(this._targetPose.rotate(Vec3.ZERO));
73389
- }
73390
- get yawRange() {
73391
- return this._targetPose.yawRange;
73392
- }
73393
- attach(pose, smooth = true) {
73394
- this._targetPose.copy(pose);
73395
- if (!smooth) {
73396
- this._pose.copy(this._targetPose);
73397
- }
73398
- }
73399
- detach() {
73400
- this._targetPose.copy(this._pose);
73401
- }
73402
- update(frame, dt) {
73403
- const { move, rotate } = frame.read();
73404
- this._targetPose.rotate(angles$1.set(-rotate[1], -rotate[0], 0));
73405
- rotation$3.setFromEulerAngles(this._pose.angles);
73406
- rotation$3.transformVector(Vec3.FORWARD, forward$1);
73407
- rotation$3.transformVector(Vec3.RIGHT, right$2);
73408
- rotation$3.transformVector(Vec3.UP, up$1);
73409
- offset$2.set(0, 0, 0);
73410
- offset$2.add(forward$1.mulScalar(move[2]));
73411
- offset$2.add(right$2.mulScalar(move[0]));
73412
- offset$2.add(up$1.mulScalar(move[1]));
73413
- this._targetPose.move(offset$2);
73414
- return this._pose.lerp(this._pose, this._targetPose, damp$1(this.moveDamping, dt), damp$1(this.rotateDamping, dt));
73415
- }
73416
- destroy() {
73417
- this.detach();
73418
- }
73419
- constructor(...args){
73420
- super(...args), this._targetPose = new Pose(), this.rotateDamping = 0.98, this.moveDamping = 0.98;
73421
- }
73422
- };
73423
-
73424
73372
  const BUTTON_CODES = {
73425
73373
  A: 0,
73426
73374
  B: 1,
@@ -74877,7 +74825,7 @@ class MultiTouchSource extends InputSource {
74877
74825
  }
74878
74826
 
74879
74827
  const dir = new Vec3();
74880
- const offset$1 = new Vec3();
74828
+ const offset$2 = new Vec3();
74881
74829
  const angles = new Vec3();
74882
74830
  const rotation$2 = new Quat();
74883
74831
  let OrbitController$1 = class OrbitController extends InputController$1 {
@@ -74916,16 +74864,16 @@ let OrbitController$1 = class OrbitController extends InputController$1 {
74916
74864
  }
74917
74865
  update(frame, dt) {
74918
74866
  const { move, rotate } = frame.read();
74919
- offset$1.set(move[0], move[1], 0);
74920
- rotation$2.setFromEulerAngles(this._rootPose.angles).transformVector(offset$1, offset$1);
74921
- this._targetRootPose.move(offset$1);
74867
+ offset$2.set(move[0], move[1], 0);
74868
+ rotation$2.setFromEulerAngles(this._rootPose.angles).transformVector(offset$2, offset$2);
74869
+ this._targetRootPose.move(offset$2);
74922
74870
  const { z: dist } = this._targetChildPose.position;
74923
- this._targetChildPose.move(offset$1.set(0, 0, dist * (1 + move[2]) - dist));
74871
+ this._targetChildPose.move(offset$2.set(0, 0, dist * (1 + move[2]) - dist));
74924
74872
  this._targetRootPose.rotate(angles.set(-rotate[1], -rotate[0], 0));
74925
74873
  this._rootPose.lerp(this._rootPose, this._targetRootPose, damp$1(this.moveDamping, dt), damp$1(this.rotateDamping, dt), 1);
74926
74874
  this._childPose.lerp(this._childPose, this._targetChildPose, damp$1(this.zoomDamping, dt), 1, 1);
74927
- rotation$2.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position, offset$1).add(this._rootPose.position);
74928
- return this._pose.set(offset$1, this._rootPose.angles, this._childPose.position.z);
74875
+ rotation$2.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position, offset$2).add(this._rootPose.position);
74876
+ return this._pose.set(offset$2, this._rootPose.angles, this._childPose.position.z);
74929
74877
  }
74930
74878
  destroy() {
74931
74879
  this.detach();
@@ -75703,7 +75651,7 @@ const SOLID_LEAF_MARKER = 0xFF000000 >>> 0;
75703
75651
  /** Half-extent of the flatness sampling patch (5x5 when R=2). */
75704
75652
  const FLAT_R = 2;
75705
75653
  /** 1/sqrt(2), used to normalise 45-degree diagonal normals. */
75706
- const INV_SQRT2 = 1 / Math.sqrt(2);
75654
+ const INV_SQRT2$1 = 1 / Math.sqrt(2);
75707
75655
  /**
75708
75656
  * Surface normal candidate directions for querySurfaceNormal.
75709
75657
  * Each entry: [dx, dy, dz, t1x, t1y, t1z, t2x, t2y, t2z]
@@ -75947,7 +75895,7 @@ class VoxelCollision {
75947
75895
  const score = scoreSurfaceCandidate(this, ix, iy, iz, sx, sy, sz, cand[3], cand[4], cand[5], cand[6], cand[7], cand[8]);
75948
75896
  if (score > bestScore) {
75949
75897
  bestScore = score;
75950
- const mag = (Math.abs(dx) + Math.abs(dy) + Math.abs(dz)) > 1 ? INV_SQRT2 : 1;
75898
+ const mag = (Math.abs(dx) + Math.abs(dy) + Math.abs(dz)) > 1 ? INV_SQRT2$1 : 1;
75951
75899
  bestNx = sx * mag;
75952
75900
  bestNy = sy * mag;
75953
75901
  bestNz = sz * mag;
@@ -76913,7 +76861,7 @@ const initUI = (global) => {
76913
76861
  'orbitCamera', 'flyCamera', 'fpsCamera',
76914
76862
  'performanceModeRow', 'performanceModeCheck', 'performanceModeOption',
76915
76863
  'gamingControlsDivider', 'gamingControlsRow', 'gamingControlsCheck', 'gamingControlsOption',
76916
- 'desktopClickToWalk', 'desktopGamingControls',
76864
+ 'desktopFlyClickToFly', 'desktopClickToWalk', 'desktopGamingControls',
76917
76865
  'touchFlyClickToWalk', 'touchFlyGamingControls',
76918
76866
  'touchClickToWalk', 'touchGamingControls',
76919
76867
  'walkHint',
@@ -77031,10 +76979,9 @@ const initUI = (global) => {
77031
76979
  updateGamingSettingsVisibility();
77032
76980
  const updateGamingControls = () => {
77033
76981
  dom.gamingControlsCheck.classList.toggle('active', state.gamingControls);
77034
- if (state.inputMode !== 'desktop') {
77035
- dom.desktopClickToWalk.classList.toggle('hidden', state.gamingControls);
77036
- dom.desktopGamingControls.classList.toggle('hidden', !state.gamingControls);
77037
- }
76982
+ dom.desktopFlyClickToFly.classList.toggle('hidden', state.gamingControls);
76983
+ dom.desktopClickToWalk.classList.toggle('hidden', state.gamingControls);
76984
+ dom.desktopGamingControls.classList.toggle('hidden', !state.gamingControls);
77038
76985
  dom.touchFlyClickToWalk.classList.toggle('hidden', state.gamingControls);
77039
76986
  dom.touchFlyGamingControls.classList.toggle('hidden', !state.gamingControls);
77040
76987
  dom.touchClickToWalk.classList.toggle('hidden', state.gamingControls);
@@ -77042,6 +76989,7 @@ const initUI = (global) => {
77042
76989
  localStorage.setItem('gamingControls', String(state.gamingControls));
77043
76990
  };
77044
76991
  events.on('gamingControls:changed', updateGamingControls);
76992
+ events.on('inputMode:changed', updateGamingControls);
77045
76993
  updateGamingControls();
77046
76994
  // AR/VR
77047
76995
  const arChanged = () => dom.arMode.classList[state.hasAR ? 'remove' : 'add']('hidden');
@@ -77106,7 +77054,24 @@ const initUI = (global) => {
77106
77054
  // show the ui and start a timer to hide it again
77107
77055
  let uiTimeout = null;
77108
77056
  let annotationVisible = false;
77057
+ const isPointerCapturedMode = () => (state.inputMode === 'desktop' &&
77058
+ state.gamingControls &&
77059
+ (state.cameraMode === 'walk' || state.cameraMode === 'fly'));
77060
+ const hideUI = () => {
77061
+ if (uiTimeout) {
77062
+ clearTimeout(uiTimeout);
77063
+ uiTimeout = null;
77064
+ }
77065
+ dom.infoPanel.classList.add('hidden');
77066
+ dom.settingsPanel.classList.add('hidden');
77067
+ dom.walkHint.classList.add('hidden');
77068
+ state.controlsHidden = true;
77069
+ };
77109
77070
  const showUI = () => {
77071
+ if (isPointerCapturedMode()) {
77072
+ hideUI();
77073
+ return;
77074
+ }
77110
77075
  if (uiTimeout) {
77111
77076
  clearTimeout(uiTimeout);
77112
77077
  }
@@ -77124,6 +77089,17 @@ const initUI = (global) => {
77124
77089
  showUI();
77125
77090
  });
77126
77091
  events.on('inputEvent', showUI);
77092
+ const updateCapturedUI = () => {
77093
+ if (isPointerCapturedMode()) {
77094
+ hideUI();
77095
+ }
77096
+ else {
77097
+ showUI();
77098
+ }
77099
+ };
77100
+ events.on('cameraMode:changed', updateCapturedUI);
77101
+ events.on('inputMode:changed', updateCapturedUI);
77102
+ events.on('gamingControls:changed', updateCapturedUI);
77127
77103
  // keep UI visible while an annotation tooltip is shown
77128
77104
  events.on('annotation.activate', () => {
77129
77105
  annotationVisible = true;
@@ -77220,7 +77196,7 @@ const initUI = (global) => {
77220
77196
  'Tap to walk. Drag to look around.';
77221
77197
  };
77222
77198
  events.on('cameraMode:changed', (value) => {
77223
- if (value === 'walk' && !walkHintShown) {
77199
+ if (value === 'walk' && !walkHintShown && !isPointerCapturedMode()) {
77224
77200
  walkHintShown = true;
77225
77201
  dom.walkHint.textContent = getWalkHintText();
77226
77202
  dom.walkHint.classList.remove('hidden');
@@ -77849,7 +77825,9 @@ class Annotations {
77849
77825
  this.parentDom = parentDom;
77850
77826
  const { state } = global;
77851
77827
  const updateVisibility = () => {
77852
- const hidden = state.controlsHidden || (state.cameraMode === 'walk' && state.gamingControls);
77828
+ const firstPersonGamingControls = ((state.cameraMode === 'walk' || state.cameraMode === 'fly') &&
77829
+ state.gamingControls);
77830
+ const hidden = state.controlsHidden || firstPersonGamingControls;
77853
77831
  parentDom.style.display = hidden ? 'none' : 'block';
77854
77832
  Annotation.opacity = hidden ? 0.0 : 1.0;
77855
77833
  if (this.annotations.length > 0) {
@@ -78316,56 +78294,558 @@ class Camera {
78316
78294
  }
78317
78295
  }
78318
78296
 
78319
- /** Radius of the camera collision sphere (meters) */
78320
- const CAMERA_RADIUS = 0.2;
78321
- const p$1 = new Pose();
78297
+ const rotation = new Quat();
78298
+ /**
78299
+ * Apply a CameraFrame rotate delta to camera Euler angles.
78300
+ *
78301
+ * CameraFrame rotate uses [yaw, pitch, roll]-style input deltas, while camera
78302
+ * angles are stored as [pitch, yaw, roll].
78303
+ *
78304
+ * @param angles - Camera Euler angles to mutate.
78305
+ * @param rotate - Frame rotate delta.
78306
+ * @param minPitch - Minimum pitch angle in degrees.
78307
+ * @param maxPitch - Maximum pitch angle in degrees.
78308
+ * @returns The mutated angles.
78309
+ */
78310
+ const applyFrameRotation = (angles, rotate, minPitch = -90, maxPitch = 90) => {
78311
+ angles.x -= rotate[1];
78312
+ angles.y -= rotate[0];
78313
+ angles.z = 0;
78314
+ angles.x = math.clamp(angles.x, minPitch, maxPitch);
78315
+ return angles;
78316
+ };
78317
+ /**
78318
+ * Calculate camera-relative basis vectors from Euler angles.
78319
+ *
78320
+ * @param angles - Camera Euler angles in degrees.
78321
+ * @param forward - Receives the forward vector.
78322
+ * @param right - Receives the right vector.
78323
+ * @param up - Receives the up vector.
78324
+ */
78325
+ const setCameraBasis = (angles, forward, right, up) => {
78326
+ rotation.setFromEulerAngles(angles);
78327
+ rotation.transformVector(Vec3.FORWARD, forward);
78328
+ rotation.transformVector(Vec3.RIGHT, right);
78329
+ rotation.transformVector(Vec3.UP, up);
78330
+ };
78331
+ /**
78332
+ * Calculate a camera forward vector from Euler angles.
78333
+ *
78334
+ * @param angles - Camera Euler angles in degrees.
78335
+ * @param forward - Receives the forward vector.
78336
+ */
78337
+ const setCameraForward = (angles, forward) => {
78338
+ rotation.setFromEulerAngles(angles);
78339
+ rotation.transformVector(Vec3.FORWARD, forward);
78340
+ };
78341
+ /**
78342
+ * Calculate yaw-only movement basis vectors.
78343
+ *
78344
+ * @param yaw - Camera yaw angle in degrees.
78345
+ * @param forward - Receives the horizontal forward vector.
78346
+ * @param right - Receives the horizontal right vector.
78347
+ */
78348
+ const setYawBasis = (yaw, forward, right) => {
78349
+ rotation.setFromEulerAngles(0, yaw, 0);
78350
+ rotation.transformVector(Vec3.FORWARD, forward);
78351
+ rotation.transformVector(Vec3.RIGHT, right);
78352
+ };
78353
+ /**
78354
+ * Build a world-space offset from local movement along camera basis vectors.
78355
+ *
78356
+ * @param out - Receives the world-space offset.
78357
+ * @param x - Local right movement.
78358
+ * @param y - Local up movement.
78359
+ * @param z - Local forward movement.
78360
+ * @param forward - Forward basis vector.
78361
+ * @param right - Right basis vector.
78362
+ * @param up - Up basis vector.
78363
+ * @returns The mutated output vector.
78364
+ */
78365
+ const setBasisOffset = (out, x, y, z, forward, right, up) => {
78366
+ out.set(right.x * x + up.x * y + forward.x * z, right.y * x + up.y * y + forward.y * z, right.z * x + up.z * y + forward.z * z);
78367
+ return out;
78368
+ };
78369
+
78370
+ /** Extra resolve passes above the collider's internal iteration for tight corners */
78371
+ const MAX_COLLISION_PASSES = 4;
78372
+ /** Small clearance that keeps the sphere from resting exactly on a collision surface */
78373
+ const COLLISION_SKIN = 1e-3;
78374
+ /** Maximum surface planes to slide along in a single frame */
78375
+ const MAX_SLIDE_ITERATIONS = 3;
78376
+ const MIN_MOVE_SQ = 1e-10;
78377
+ const INV_SQRT2 = 1 / Math.sqrt(2);
78378
+ const SWEEP_RAY_OFFSETS = [
78379
+ [0, 0, true],
78380
+ [1, 0, false],
78381
+ [-1, 0, false],
78382
+ [0, 1, false],
78383
+ [0, -1, false],
78384
+ [INV_SQRT2, INV_SQRT2, false],
78385
+ [-INV_SQRT2, INV_SQRT2, false],
78386
+ [-INV_SQRT2, -INV_SQRT2, false],
78387
+ [INV_SQRT2, -INV_SQRT2, false]
78388
+ ];
78389
+ const v$2 = new Vec3();
78390
+ const remainingMove = new Vec3();
78391
+ const collisionPush = new Vec3();
78392
+ const sweepDir = new Vec3();
78393
+ const sweepNormal = new Vec3();
78394
+ const sweepTangent = new Vec3();
78395
+ const sweepBitangent = new Vec3();
78396
+ const sweepOrigin = new Vec3();
78397
+ const worldUp = new Vec3(0, 1, 0);
78398
+ const worldRight = new Vec3(1, 0, 0);
78322
78399
  /** Pre-allocated push-out vector for sphere collision */
78323
78400
  const pushOut = { x: 0, y: 0, z: 0 };
78401
+ const sweepHit = {
78402
+ x: 0,
78403
+ y: 0,
78404
+ z: 0,
78405
+ nx: 0,
78406
+ ny: 1,
78407
+ nz: 0,
78408
+ travel: 0
78409
+ };
78410
+ class SphereMover {
78411
+ collision = null;
78412
+ radius;
78413
+ _lastClearPosition = new Vec3();
78414
+ _hasLastClearPosition = false;
78415
+ constructor(radius) {
78416
+ this.radius = radius;
78417
+ }
78418
+ reset(position) {
78419
+ this._setLastClearPosition(position);
78420
+ }
78421
+ move(position, move) {
78422
+ if (!this.collision) {
78423
+ position.add(move);
78424
+ this._setLastClearPosition(position);
78425
+ return;
78426
+ }
78427
+ remainingMove.copy(move);
78428
+ if (this._isMoveComplete(remainingMove)) {
78429
+ this.resolve(position);
78430
+ return;
78431
+ }
78432
+ for (let i = 0; i < MAX_SLIDE_ITERATIONS; i++) {
78433
+ if (this._isMoveComplete(remainingMove)) {
78434
+ break;
78435
+ }
78436
+ if (!this._moveAndSlide(position, remainingMove)) {
78437
+ break;
78438
+ }
78439
+ }
78440
+ }
78441
+ resolve(position) {
78442
+ if (!this.collision) {
78443
+ this._setLastClearPosition(position);
78444
+ return;
78445
+ }
78446
+ this._resolveSphere(position, collisionPush);
78447
+ if (!this._isSphereClear(position) && this._hasLastClearPosition) {
78448
+ position.copy(this._lastClearPosition);
78449
+ }
78450
+ if (this._isSphereClear(position)) {
78451
+ this._setLastClearPosition(position);
78452
+ }
78453
+ }
78454
+ _moveAndSlide(position, move) {
78455
+ const moveSq = move.x * move.x + move.y * move.y + move.z * move.z;
78456
+ const distance = Math.sqrt(moveSq);
78457
+ sweepDir.copy(move).mulScalar(1 / distance);
78458
+ if (!this._querySweep(position, sweepDir, distance, sweepHit)) {
78459
+ position.add(move);
78460
+ this.resolve(position);
78461
+ return false;
78462
+ }
78463
+ position.add(v$2.copy(sweepDir).mulScalar(sweepHit.travel));
78464
+ this.resolve(position);
78465
+ sweepNormal.set(sweepHit.nx, sweepHit.ny, sweepHit.nz);
78466
+ move.add(v$2.copy(sweepDir).mulScalar(-sweepHit.travel));
78467
+ this._clipMove(move, sweepNormal);
78468
+ return true;
78469
+ }
78470
+ _querySweep(position, dir, distance, out) {
78471
+ if (Math.abs(dir.y) < 0.99) {
78472
+ sweepTangent.cross(dir, worldUp).normalize();
78473
+ }
78474
+ else {
78475
+ sweepTangent.cross(dir, worldRight).normalize();
78476
+ }
78477
+ sweepBitangent.cross(dir, sweepTangent).normalize();
78478
+ let found = false;
78479
+ let bestTravel = Infinity;
78480
+ for (let i = 0; i < SWEEP_RAY_OFFSETS.length; i++) {
78481
+ const [tx, ty, centerRay] = SWEEP_RAY_OFFSETS[i];
78482
+ const radiusOffset = centerRay ? 0 : this.radius;
78483
+ const rayExtension = centerRay ? this.radius : 0;
78484
+ sweepOrigin.copy(position);
78485
+ if (!centerRay) {
78486
+ sweepOrigin.add(v$2.copy(sweepTangent).mulScalar(tx * radiusOffset));
78487
+ sweepOrigin.add(v$2.copy(sweepBitangent).mulScalar(ty * radiusOffset));
78488
+ }
78489
+ const hit = this.collision.queryRay(sweepOrigin.x, sweepOrigin.y, sweepOrigin.z, dir.x, dir.y, dir.z, distance + rayExtension + COLLISION_SKIN);
78490
+ if (!hit) {
78491
+ continue;
78492
+ }
78493
+ const hx = hit.x - sweepOrigin.x;
78494
+ const hy = hit.y - sweepOrigin.y;
78495
+ const hz = hit.z - sweepOrigin.z;
78496
+ const hitDistance = Math.max(0, hx * dir.x + hy * dir.y + hz * dir.z);
78497
+ const clearance = centerRay ? this.radius : 0;
78498
+ const travel = math.clamp(hitDistance - clearance - COLLISION_SKIN, 0, distance);
78499
+ if (travel >= bestTravel) {
78500
+ continue;
78501
+ }
78502
+ const surfaceNormal = this.collision.querySurfaceNormal(hit.x, hit.y, hit.z, dir.x, dir.y, dir.z);
78503
+ found = true;
78504
+ bestTravel = travel;
78505
+ out.x = hit.x;
78506
+ out.y = hit.y;
78507
+ out.z = hit.z;
78508
+ out.nx = surfaceNormal.nx;
78509
+ out.ny = surfaceNormal.ny;
78510
+ out.nz = surfaceNormal.nz;
78511
+ out.travel = travel;
78512
+ }
78513
+ return found;
78514
+ }
78515
+ _resolveSphere(position, push) {
78516
+ let collided = false;
78517
+ push.set(0, 0, 0);
78518
+ for (let i = 0; i < MAX_COLLISION_PASSES; i++) {
78519
+ if (!this.collision.querySphere(position.x, position.y, position.z, this.radius, pushOut)) {
78520
+ break;
78521
+ }
78522
+ position.x += pushOut.x;
78523
+ position.y += pushOut.y;
78524
+ position.z += pushOut.z;
78525
+ push.x += pushOut.x;
78526
+ push.y += pushOut.y;
78527
+ push.z += pushOut.z;
78528
+ collided = true;
78529
+ }
78530
+ return collided;
78531
+ }
78532
+ _clipMove(move, push) {
78533
+ const normalSq = push.x * push.x + push.y * push.y + push.z * push.z;
78534
+ if (normalSq <= MIN_MOVE_SQ) {
78535
+ return;
78536
+ }
78537
+ const invPushLen = 1 / Math.sqrt(normalSq);
78538
+ const nx = push.x * invPushLen;
78539
+ const ny = push.y * invPushLen;
78540
+ const nz = push.z * invPushLen;
78541
+ const dot = move.x * nx + move.y * ny + move.z * nz;
78542
+ if (dot < 0) {
78543
+ move.x -= dot * nx;
78544
+ move.y -= dot * ny;
78545
+ move.z -= dot * nz;
78546
+ }
78547
+ }
78548
+ _isMoveComplete(move) {
78549
+ return move.x * move.x + move.y * move.y + move.z * move.z <= MIN_MOVE_SQ;
78550
+ }
78551
+ _isSphereClear(position) {
78552
+ return !this.collision.querySphere(position.x, position.y, position.z, this.radius, pushOut);
78553
+ }
78554
+ _setLastClearPosition(position) {
78555
+ this._lastClearPosition.copy(position);
78556
+ this._hasLastClearPosition = !this.collision || this._isSphereClear(position);
78557
+ }
78558
+ }
78559
+
78560
+ /** Radius of the camera collision sphere (meters) */
78561
+ const CAMERA_RADIUS = 0.2;
78562
+ const forward$2 = new Vec3();
78563
+ const right$2 = new Vec3();
78564
+ const up$1 = new Vec3();
78565
+ const offset$1 = new Vec3();
78324
78566
  class FlyController {
78325
- controller;
78326
78567
  fov = 90;
78568
+ _position = new Vec3();
78569
+ _angles = new Vec3();
78570
+ _distance = 1;
78571
+ _spawnPosition = new Vec3();
78572
+ _spawnAngles = new Vec3();
78573
+ _spawnDistance = 1;
78574
+ _mover = new SphereMover(CAMERA_RADIUS);
78327
78575
  /** Optional collision for sphere collision with sliding */
78328
- collision = null;
78329
- constructor() {
78330
- this.controller = new FlyController$1();
78331
- this.controller.pitchRange = new Vec2(-90, 90);
78332
- this.controller.rotateDamping = 0.97;
78333
- this.controller.moveDamping = 0.97;
78576
+ set collision(value) {
78577
+ this._mover.collision = value;
78578
+ this._mover.reset(this._position);
78579
+ }
78580
+ get collision() {
78581
+ return this._mover.collision;
78334
78582
  }
78583
+ _hasSpawn = false;
78335
78584
  onEnter(camera) {
78336
- p$1.position.copy(camera.position);
78337
- p$1.angles.copy(camera.angles);
78338
- p$1.distance = camera.distance;
78339
- this.controller.attach(p$1, false);
78585
+ this.goto(camera);
78586
+ this._mover.resolve(this._position);
78587
+ this._storeSpawn();
78340
78588
  }
78341
78589
  update(deltaTime, inputFrame, camera) {
78342
- const pose = this.controller.update(inputFrame, deltaTime);
78343
- camera.angles.copy(pose.angles);
78344
- camera.distance = pose.distance;
78345
- if (this.collision) {
78346
- // Resolve collision on _targetPose first. The engine's update() already
78347
- // applied input to _targetPose and lerped _pose toward it. By correcting
78348
- // _targetPose now, we ensure next frame's lerp interpolates toward a safe
78349
- // position, preventing the camera from overshooting into the wall.
78350
- const target = this.controller._targetPose;
78351
- if (this.collision.querySphere(target.position.x, target.position.y, target.position.z, CAMERA_RADIUS, pushOut)) {
78352
- target.position.x += pushOut.x;
78353
- target.position.y += pushOut.y;
78354
- target.position.z += pushOut.z;
78590
+ const { move, rotate } = inputFrame.read();
78591
+ applyFrameRotation(this._angles, rotate);
78592
+ this._step(move);
78593
+ camera.position.copy(this._position);
78594
+ camera.angles.set(this._angles.x, this._angles.y, 0);
78595
+ camera.distance = this._distance;
78596
+ camera.fov = this.fov;
78597
+ }
78598
+ onExit(_camera) {
78599
+ }
78600
+ goto(camera) {
78601
+ this._position.copy(camera.position);
78602
+ this._angles.set(camera.angles.x, camera.angles.y, 0);
78603
+ this._distance = camera.distance;
78604
+ this._mover.reset(this._position);
78605
+ }
78606
+ resetToSpawn(camera) {
78607
+ if (!this._hasSpawn) {
78608
+ return false;
78609
+ }
78610
+ this._position.copy(this._spawnPosition);
78611
+ this._angles.copy(this._spawnAngles);
78612
+ this._distance = this._spawnDistance;
78613
+ this._mover.reset(this._position);
78614
+ camera.position.copy(this._position);
78615
+ camera.angles.copy(this._angles);
78616
+ camera.distance = this._distance;
78617
+ camera.fov = this.fov;
78618
+ return true;
78619
+ }
78620
+ _storeSpawn() {
78621
+ this._spawnPosition.copy(this._position);
78622
+ this._spawnAngles.copy(this._angles);
78623
+ this._spawnDistance = this._distance;
78624
+ this._hasSpawn = true;
78625
+ }
78626
+ _step(move) {
78627
+ setCameraBasis(this._angles, forward$2, right$2, up$1);
78628
+ setBasisOffset(offset$1, move[0], move[1], move[2], forward$2, right$2, up$1);
78629
+ this._mover.move(this._position, offset$1);
78630
+ }
78631
+ }
78632
+
78633
+ const RAD_TO_DEG = 180 / Math.PI;
78634
+ const shortestAngle = (angle) => ((angle % 360) + 540) % 360 - 180;
78635
+ const smoothstep = (edge0, edge1, value) => {
78636
+ const t = math.clamp((value - edge0) / (edge1 - edge0), 0, 1);
78637
+ return t * t * (3 - 2 * t);
78638
+ };
78639
+ const approach = (value, target, maxDelta) => {
78640
+ if (value < target) {
78641
+ return Math.min(target, value + maxDelta);
78642
+ }
78643
+ return Math.max(target, value - maxDelta);
78644
+ };
78645
+ const smoothTurnRate = (currentRate, angleDiff, maxTurnRate, turnGain, dt) => {
78646
+ if (dt <= 0) {
78647
+ return currentRate;
78648
+ }
78649
+ const desiredRate = math.clamp(angleDiff * turnGain, -maxTurnRate, maxTurnRate);
78650
+ const smoothing = 1 - Math.exp(-4 * turnGain * dt);
78651
+ return currentRate + (desiredRate - currentRate) * smoothing;
78652
+ };
78653
+ const clampTurnStep = (rate, remaining, dt) => {
78654
+ const step = rate * dt;
78655
+ if (Math.abs(remaining) < 1e-4) {
78656
+ return 0;
78657
+ }
78658
+ return Math.sign(step) === Math.sign(remaining) && Math.abs(step) > Math.abs(remaining) ?
78659
+ remaining :
78660
+ step;
78661
+ };
78662
+ const getYawToTarget = (dx, dz) => Math.atan2(-dx, -dz) * RAD_TO_DEG;
78663
+ const getYawDiffToTarget = (dx, dz, yaw) => {
78664
+ return shortestAngle(getYawToTarget(dx, dz) - yaw);
78665
+ };
78666
+ const getPitchToDirection = (dirY) => {
78667
+ return Math.asin(math.clamp(dirY, -1, 1)) * RAD_TO_DEG;
78668
+ };
78669
+ class ProgressTracker {
78670
+ _blockedTime = 0;
78671
+ _prevDist = Infinity;
78672
+ reset() {
78673
+ this._blockedTime = 0;
78674
+ this._prevDist = Infinity;
78675
+ }
78676
+ update(distance, dt, blockedSpeed, blockedDuration, active = true) {
78677
+ if (active && this._prevDist !== Infinity && dt > 0) {
78678
+ const speed = (this._prevDist - distance) / dt;
78679
+ if (speed < blockedSpeed) {
78680
+ this._blockedTime += dt;
78681
+ if (this._blockedTime >= blockedDuration) {
78682
+ this._prevDist = distance;
78683
+ return true;
78684
+ }
78355
78685
  }
78356
- if (this.collision.querySphere(pose.position.x, pose.position.y, pose.position.z, CAMERA_RADIUS, pushOut)) {
78357
- pose.position.x += pushOut.x;
78358
- pose.position.y += pushOut.y;
78359
- pose.position.z += pushOut.z;
78686
+ else {
78687
+ this._blockedTime = 0;
78360
78688
  }
78361
78689
  }
78362
- camera.position.copy(pose.position);
78363
- camera.fov = this.fov;
78690
+ this._prevDist = distance;
78691
+ return false;
78364
78692
  }
78365
- onExit(camera) {
78693
+ }
78694
+
78695
+ const DEG_TO_RAD = Math.PI / 180;
78696
+ /** Target-space radius to keep visible at the stopping distance */
78697
+ const STOP_VIEW_RADIUS = 0.75;
78698
+ /** Minimum standoff from the target */
78699
+ const MIN_STOP_DIST = 0.75;
78700
+ /** Maximum standoff from the target */
78701
+ const MAX_STOP_DIST = 4.0;
78702
+ /** Distance from the standoff point below which arrival can complete */
78703
+ const ARRIVAL_EPSILON = 0.03;
78704
+ /** Forward speed below which arrival can complete */
78705
+ const ARRIVAL_SPEED = 0.05;
78706
+ /** Converts remaining standoff distance to final approach speed */
78707
+ const ARRIVAL_RATE = 1.75;
78708
+ /** Minimum progress speed (m/s) to not count as blocked */
78709
+ const BLOCKED_SPEED$1 = 0.25;
78710
+ /** Seconds of continuous low-progress before stopping the flight */
78711
+ const BLOCKED_DURATION$1 = 0.5;
78712
+ const toTarget = new Vec3();
78713
+ const forward$1 = new Vec3();
78714
+ const postTurnAngles = new Vec3();
78715
+ const getStopDistance = (fov) => {
78716
+ const halfFov = math.clamp(fov, 15, 120) * DEG_TO_RAD * 0.5;
78717
+ return math.clamp(STOP_VIEW_RADIUS / Math.tan(halfFov), MIN_STOP_DIST, MAX_STOP_DIST);
78718
+ };
78719
+ /**
78720
+ * Generates synthetic move/rotate input to auto-fly toward a target position.
78721
+ */
78722
+ class FlySource {
78723
+ /**
78724
+ * Forward input scale (matches InputController.moveSpeed).
78725
+ */
78726
+ flySpeed = 4;
78727
+ /**
78728
+ * Maximum pitch/yaw turn rate in degrees per second.
78729
+ */
78730
+ maxTurnRate = 180;
78731
+ /**
78732
+ * Proportional gain mapping angular error (degrees) to desired turn rate.
78733
+ */
78734
+ turnGain = 4;
78735
+ /**
78736
+ * Maximum forward acceleration in meters per second squared.
78737
+ */
78738
+ moveAcceleration = 6;
78739
+ /**
78740
+ * Maximum forward braking in meters per second squared.
78741
+ */
78742
+ moveDeceleration = 8;
78743
+ /**
78744
+ * Callback fired when an auto-flight completes or is cancelled.
78745
+ */
78746
+ onComplete = null;
78747
+ _target = null;
78748
+ _yawRate = 0;
78749
+ _pitchRate = 0;
78750
+ _speed = 0;
78751
+ _progress = new ProgressTracker();
78752
+ get isActive() {
78753
+ return this._target !== null;
78366
78754
  }
78367
- goto(pose) {
78368
- this.controller.attach(pose, true);
78755
+ /**
78756
+ * Begin auto-flying toward a world-space target position.
78757
+ *
78758
+ * @param target - The destination.
78759
+ */
78760
+ navigateTo(target) {
78761
+ const wasFlying = this._target !== null;
78762
+ if (!this._target) {
78763
+ this._target = new Vec3();
78764
+ }
78765
+ this._target.copy(target);
78766
+ if (!wasFlying) {
78767
+ this._yawRate = 0;
78768
+ this._pitchRate = 0;
78769
+ this._speed = 0;
78770
+ }
78771
+ this._progress.reset();
78772
+ }
78773
+ /**
78774
+ * Cancel any active auto-flight.
78775
+ */
78776
+ cancel() {
78777
+ if (this._target) {
78778
+ this._target = null;
78779
+ this._yawRate = 0;
78780
+ this._pitchRate = 0;
78781
+ this._speed = 0;
78782
+ this._progress.reset();
78783
+ this.onComplete?.();
78784
+ }
78785
+ }
78786
+ /**
78787
+ * Compute fly deltas and append them to the frame. Must be called before
78788
+ * the camera controller reads the frame.
78789
+ *
78790
+ * @param dt - Frame delta time in seconds.
78791
+ * @param camera - The current camera state (read-only).
78792
+ * @param frame - The shared CameraFrame to append deltas to.
78793
+ */
78794
+ update(dt, camera, frame) {
78795
+ if (!this._target)
78796
+ return;
78797
+ const target = this._target;
78798
+ const cameraPosition = camera.position;
78799
+ const cameraAngles = camera.angles;
78800
+ toTarget.sub2(target, cameraPosition);
78801
+ const dist = toTarget.length();
78802
+ const stopDistance = getStopDistance(camera.fov);
78803
+ const remainingDist = dist - stopDistance;
78804
+ const activeRemainingDist = Math.max(0, remainingDist);
78805
+ if (activeRemainingDist <= ARRIVAL_EPSILON && this._speed <= ARRIVAL_SPEED) {
78806
+ this.cancel();
78807
+ return;
78808
+ }
78809
+ if (dt <= 0) {
78810
+ return;
78811
+ }
78812
+ const invDist = 1 / dist;
78813
+ const dirX = toTarget.x * invDist;
78814
+ const dirY = toTarget.y * invDist;
78815
+ const dirZ = toTarget.z * invDist;
78816
+ const yawDiff = getYawDiffToTarget(toTarget.x, toTarget.z, cameraAngles.y);
78817
+ const pitchDiff = getPitchToDirection(dirY) - cameraAngles.x;
78818
+ this._yawRate = smoothTurnRate(this._yawRate, yawDiff, this.maxTurnRate, this.turnGain, dt);
78819
+ this._pitchRate = smoothTurnRate(this._pitchRate, pitchDiff, this.maxTurnRate, this.turnGain, dt);
78820
+ const yawStep = clampTurnStep(this._yawRate, yawDiff, dt);
78821
+ const pitchStep = clampTurnStep(this._pitchRate, pitchDiff, dt);
78822
+ this._yawRate = yawStep / dt;
78823
+ this._pitchRate = pitchStep / dt;
78824
+ // FlyController applies: _angles += [-rotateY, -rotateX, 0]
78825
+ frame.deltas.rotate.append([-yawStep, -pitchStep, 0]);
78826
+ postTurnAngles.set(cameraAngles.x + pitchStep, cameraAngles.y + yawStep, 0);
78827
+ setCameraForward(postTurnAngles, forward$1);
78828
+ const alignment = math.clamp(forward$1.x * dirX + forward$1.y * dirY + forward$1.z * dirZ, 0, 1);
78829
+ const alignmentScale = smoothstep(0.05, 0.95, alignment);
78830
+ const brakeSpeed = Math.sqrt(2 * this.moveDeceleration * activeRemainingDist);
78831
+ const arrivalSpeed = activeRemainingDist * ARRIVAL_RATE;
78832
+ const maxSpeed = Math.min(this.flySpeed, brakeSpeed, arrivalSpeed);
78833
+ if (maxSpeed > this._speed) {
78834
+ this._speed = approach(this._speed, maxSpeed, this.moveAcceleration * alignmentScale * dt);
78835
+ }
78836
+ else {
78837
+ this._speed = approach(this._speed, maxSpeed, this.moveDeceleration * dt);
78838
+ }
78839
+ const arrivalMove = activeRemainingDist * (1 - Math.exp(-ARRIVAL_RATE * dt));
78840
+ const moveDist = Math.min(this._speed * dt, arrivalMove);
78841
+ if (moveDist > 0) {
78842
+ frame.deltas.move.append([0, 0, moveDist]);
78843
+ }
78844
+ // Only treat low progress as blocked once the camera is substantially
78845
+ // facing the target; otherwise a large turn-in-place would cancel early.
78846
+ if (this._progress.update(dist, dt, BLOCKED_SPEED$1, BLOCKED_DURATION$1, alignment > 0.5 && this._speed > BLOCKED_SPEED$1)) {
78847
+ this.cancel();
78848
+ }
78369
78849
  }
78370
78850
  }
78371
78851
 
@@ -78382,10 +78862,7 @@ class OrbitController {
78382
78862
  this.controller.zoomDamping = 0.97;
78383
78863
  }
78384
78864
  onEnter(camera) {
78385
- p.position.copy(camera.position);
78386
- p.angles.copy(camera.angles);
78387
- p.distance = camera.distance;
78388
- this.controller.attach(p, false);
78865
+ this._attach(camera);
78389
78866
  }
78390
78867
  update(deltaTime, inputFrame, camera) {
78391
78868
  const pose = this.controller.update(inputFrame, deltaTime);
@@ -78394,17 +78871,117 @@ class OrbitController {
78394
78871
  camera.distance = pose.distance;
78395
78872
  camera.fov = this.fov;
78396
78873
  }
78397
- onExit(camera) {
78874
+ onExit(_camera) {
78398
78875
  }
78399
78876
  goto(camera) {
78877
+ this.fov = camera.fov;
78878
+ this._attach(camera);
78879
+ }
78880
+ _attach(camera) {
78400
78881
  p.position.copy(camera.position);
78401
78882
  p.angles.copy(camera.angles);
78402
- p.distance = camera.distance;
78403
- this.fov = camera.fov;
78883
+ p.distance = Math.max(camera.distance, this.controller.zoomRange.x);
78404
78884
  this.controller.attach(p, false);
78405
78885
  }
78406
78886
  }
78407
78887
 
78888
+ const SPAWN_HIT_EPSILON = 1e-3;
78889
+ const SPAWN_SEARCH_MIN_STEP = 0.05;
78890
+ const SPAWN_SEARCH_MAX_STEPS = 128;
78891
+ const out$1 = { x: 0, y: 0, z: 0 };
78892
+ const v$1 = new Vec3();
78893
+ const probe = new Vec3();
78894
+ const queryCapsule = (collision, pos, p) => {
78895
+ const half = p.capsuleHeight * 0.5 - p.capsuleRadius;
78896
+ const center = pos.y - p.eyeHeight + p.capsuleHeight * 0.5;
78897
+ return collision.queryCapsule(pos.x, center, pos.z, half, p.capsuleRadius, out$1);
78898
+ };
78899
+ const eyeYFromGround = (groundY, p) => groundY + p.hoverHeight + p.eyeHeight;
78900
+ const isInsideSolid = (collision, pos) => {
78901
+ return collision.querySphere(pos.x, pos.y, pos.z, SPAWN_HIT_EPSILON, out$1);
78902
+ };
78903
+ const probeGroundY = (collision, pos, p) => {
78904
+ const hit = collision.queryRay(pos.x, pos.y, pos.z, 0, -1, 0, p.spawnSearchRange);
78905
+ return hit ? hit.y : null;
78906
+ };
78907
+ const hasSpawnGroundSupport = (collision, pos, p) => {
78908
+ const groundY = probeGroundY(collision, pos, p);
78909
+ if (groundY === null) {
78910
+ return false;
78911
+ }
78912
+ const clearance = pos.y - p.eyeHeight - groundY;
78913
+ return clearance >= -SPAWN_HIT_EPSILON &&
78914
+ clearance <= p.hoverHeight + p.capsuleRadius + SPAWN_HIT_EPSILON;
78915
+ };
78916
+ // Push a candidate eye position out of solid geometry. Returns true if the
78917
+ // candidate becomes clear within the allowed budget and remains supported by
78918
+ // ground beneath it.
78919
+ const resolveSpawnCandidate = (collision, pos, p) => {
78920
+ const startX = pos.x;
78921
+ const startY = pos.y;
78922
+ const startZ = pos.z;
78923
+ const maxResolveDistance = p.capsuleRadius + p.hoverHeight;
78924
+ const maxResolveDistanceSq = maxResolveDistance * maxResolveDistance;
78925
+ for (let i = 0; i < 100; i++) {
78926
+ if (!queryCapsule(collision, pos, p)) {
78927
+ return hasSpawnGroundSupport(collision, pos, p);
78928
+ }
78929
+ pos.add(v$1.set(out$1.x, out$1.y, out$1.z));
78930
+ const dx = pos.x - startX;
78931
+ const dy = pos.y - startY;
78932
+ const dz = pos.z - startZ;
78933
+ if (dx * dx + dy * dy + dz * dz > maxResolveDistanceSq) {
78934
+ return false;
78935
+ }
78936
+ }
78937
+ return false;
78938
+ };
78939
+ // Find the first collision surface below a point that can hold a clear walk
78940
+ // capsule. Writes the resolved eye position to outPos on success.
78941
+ const findClearSpawnGroundBelow = (collision, pos, range, allowInitialHit, p, outPos) => {
78942
+ const hit = collision.queryRay(pos.x, pos.y, pos.z, 0, -1, 0, range);
78943
+ if (!hit) {
78944
+ return false;
78945
+ }
78946
+ if (!allowInitialHit && Math.abs(pos.y - hit.y) <= SPAWN_HIT_EPSILON) {
78947
+ return false;
78948
+ }
78949
+ outPos.set(pos.x, eyeYFromGround(hit.y, p), pos.z);
78950
+ const clear = !queryCapsule(collision, outPos, p);
78951
+ return clear || resolveSpawnCandidate(collision, outPos, p);
78952
+ };
78953
+ const searchSpawnGround = (collision, pos, direction, p, outPos) => {
78954
+ const step = Math.max(p.capsuleRadius, p.hoverHeight, SPAWN_SEARCH_MIN_STEP, p.spawnSearchRange / SPAWN_SEARCH_MAX_STEPS);
78955
+ const endY = pos.y + direction * p.spawnSearchRange;
78956
+ for (let y = pos.y + direction * step; direction < 0 ? y >= endY : y <= endY; y += direction * step) {
78957
+ probe.set(pos.x, y, pos.z);
78958
+ if (findClearSpawnGroundBelow(collision, probe, p.spawnSearchRange, false, p, outPos)) {
78959
+ return true;
78960
+ }
78961
+ }
78962
+ return false;
78963
+ };
78964
+ /**
78965
+ * Find an eye position for spawning into walk mode. Prefer ground directly
78966
+ * below the camera; if that is not usable, search down and then up for the
78967
+ * first clear walk placement with ground below it. On success, the resolved
78968
+ * eye position is written to outPos.
78969
+ *
78970
+ * @param collision - The active collision implementation.
78971
+ * @param pos - Incoming camera position.
78972
+ * @param p - Walk capsule and spawn-search parameters.
78973
+ * @param outPos - Receives the resolved eye position.
78974
+ * @returns True if a spawn position was found.
78975
+ */
78976
+ const findWalkSpawn = (collision, pos, p, outPos) => {
78977
+ const insideSolid = isInsideSolid(collision, pos);
78978
+ if (findClearSpawnGroundBelow(collision, pos, p.spawnSearchRange, !insideSolid, p, outPos)) {
78979
+ return true;
78980
+ }
78981
+ return searchSpawnGround(collision, pos, -1, p, outPos) ||
78982
+ searchSpawnGround(collision, pos, 1, p, outPos);
78983
+ };
78984
+
78408
78985
  const FIXED_DT = 1 / 60;
78409
78986
  const MAX_SUBSTEPS = 10;
78410
78987
  /** Pre-allocated push-out vector for capsule collision */
@@ -78415,13 +78992,13 @@ const forward = new Vec3();
78415
78992
  const right$1 = new Vec3();
78416
78993
  const moveStep = [0, 0, 0];
78417
78994
  const offset = new Vec3();
78418
- const rotation = new Quat();
78995
+ const spawnProbe = new Vec3();
78419
78996
  /**
78420
- * First-person camera controller with spring-damper suspension over voxel terrain.
78997
+ * First-person camera controller with spring-damper suspension over collision terrain.
78421
78998
  *
78422
78999
  * Movement is constrained to the horizontal plane (XZ) relative to the camera yaw.
78423
79000
  * Vertical positioning uses a spring-damper system that hovers the capsule above the
78424
- * voxel surface, filtering out terrain noise for smooth camera motion. Capsule
79001
+ * collision surface, filtering out terrain noise for smooth camera motion. Capsule
78425
79002
  * collision handles walls and obstacles. When airborne, normal gravity applies.
78426
79003
  */
78427
79004
  class WalkController {
@@ -78479,7 +79056,7 @@ class WalkController {
78479
79056
  velocityDampingAir = 0.998;
78480
79057
  /**
78481
79058
  * Target clearance from capsule bottom to ground surface in meters.
78482
- * The capsule hovers this far above terrain to avoid bouncing on noisy voxels.
79059
+ * The capsule hovers this far above terrain to avoid bouncing on noisy surfaces.
78483
79060
  */
78484
79061
  hoverHeight = 0.2;
78485
79062
  /**
@@ -78495,34 +79072,42 @@ class WalkController {
78495
79072
  * Maximum downward raycast distance to search for ground below the capsule.
78496
79073
  */
78497
79074
  groundProbeRange = 1.0;
79075
+ /**
79076
+ * Maximum vertical raycast distance to search for walk spawn ground.
79077
+ */
79078
+ spawnSearchRange = 1000;
78498
79079
  _position = new Vec3();
78499
79080
  _prevPosition = new Vec3();
78500
79081
  _angles = new Vec3();
79082
+ _distance = 1;
79083
+ _spawnPosition = new Vec3();
79084
+ _spawnAngles = new Vec3();
79085
+ _spawnDistance = 1;
78501
79086
  _velocity = new Vec3();
78502
79087
  _pendingMove = [0, 0, 0];
78503
79088
  _accumulator = 0;
78504
79089
  _grounded = false;
78505
79090
  _jumping = false;
78506
79091
  _jumpHeld = false;
79092
+ _spawnGrounded = false;
79093
+ _hasSpawn = false;
78507
79094
  onEnter(camera) {
78508
79095
  this.goto(camera);
78509
79096
  if (this.collision) {
78510
- this._resolveSpawnCollision();
78511
- this._prevPosition.copy(this._position);
78512
- const groundY = this._probeGround(this._position);
78513
- if (groundY !== null) {
79097
+ this._hasSpawn = false;
79098
+ if (findWalkSpawn(this.collision, camera.position, this, spawnProbe)) {
79099
+ this._position.copy(spawnProbe);
78514
79100
  this._grounded = true;
78515
79101
  this._velocity.y = 0;
78516
- this._position.y = groundY + this.hoverHeight + this.eyeHeight;
78517
- this._prevPosition.copy(this._position);
79102
+ this._storeSpawn();
78518
79103
  }
79104
+ this._prevPosition.copy(this._position);
78519
79105
  }
78520
79106
  }
78521
79107
  update(deltaTime, inputFrame, camera) {
78522
79108
  const { move, rotate } = inputFrame.read();
78523
79109
  // apply rotation at display rate for responsive mouse look
78524
- this._angles.add(v.set(-rotate[1], -rotate[0], 0));
78525
- this._angles.x = math.clamp(this._angles.x, -90, 90);
79110
+ applyFrameRotation(this._angles, rotate);
78526
79111
  // accumulate movement input so frames without a physics step don't lose input
78527
79112
  this._pendingMove[0] += move[0];
78528
79113
  this._pendingMove[1] = this._pendingMove[1] || move[1];
@@ -78546,6 +79131,7 @@ class WalkController {
78546
79131
  const alpha = this._accumulator / FIXED_DT;
78547
79132
  camera.position.lerp(this._prevPosition, this._position, alpha);
78548
79133
  camera.angles.set(this._angles.x, this._angles.y, 0);
79134
+ camera.distance = this._distance;
78549
79135
  camera.fov = this.fov;
78550
79136
  }
78551
79137
  _step(dt, move) {
@@ -78588,12 +79174,8 @@ class WalkController {
78588
79174
  this._grounded = false;
78589
79175
  }
78590
79176
  // move
78591
- rotation.setFromEulerAngles(0, this._angles.y, 0);
78592
- rotation.transformVector(Vec3.FORWARD, forward);
78593
- rotation.transformVector(Vec3.RIGHT, right$1);
78594
- offset.set(0, 0, 0);
78595
- offset.add(forward.mulScalar(move[2]));
78596
- offset.add(right$1.mulScalar(move[0]));
79177
+ setYawBasis(this._angles.y, forward, right$1);
79178
+ setBasisOffset(offset, move[0], 0, move[2], forward, right$1, Vec3.UP);
78597
79179
  this._velocity.add(offset.mulScalar(this._grounded ? this.moveGroundSpeed : this.moveAirSpeed));
78598
79180
  const dampFactor = this._grounded ? this.velocityDampingGround : this.velocityDampingAir;
78599
79181
  const alpha = damp(dampFactor, dt);
@@ -78617,36 +79199,53 @@ class WalkController {
78617
79199
  this._prevPosition.copy(this._position);
78618
79200
  // angles (clamp pitch to avoid gimbal lock)
78619
79201
  this._angles.set(camera.angles.x, camera.angles.y, 0);
79202
+ this._distance = camera.distance;
78620
79203
  // reset velocity and state
79204
+ this._resetMotion();
79205
+ }
79206
+ /**
79207
+ * Reset the controller to the spawn pose captured on the last walk-mode entry.
79208
+ *
79209
+ * @param camera - Camera state to update with the spawn pose.
79210
+ * @returns True if a spawn pose was available.
79211
+ */
79212
+ resetToSpawn(camera) {
79213
+ if (!this._hasSpawn) {
79214
+ return false;
79215
+ }
79216
+ this._position.copy(this._spawnPosition);
79217
+ this._prevPosition.copy(this._position);
79218
+ this._angles.copy(this._spawnAngles);
79219
+ this._distance = this._spawnDistance;
79220
+ this._resetMotion();
79221
+ this._grounded = this._spawnGrounded;
79222
+ camera.position.copy(this._position);
79223
+ camera.angles.copy(this._angles);
79224
+ camera.distance = this._distance;
79225
+ camera.fov = this.fov;
79226
+ return true;
79227
+ }
79228
+ _storeSpawn() {
79229
+ this._spawnPosition.copy(this._position);
79230
+ this._spawnAngles.copy(this._angles);
79231
+ this._spawnDistance = this._distance;
79232
+ this._spawnGrounded = this._grounded;
79233
+ this._hasSpawn = true;
79234
+ }
79235
+ _resetMotion() {
78621
79236
  this._velocity.set(0, 0, 0);
78622
79237
  this._grounded = false;
78623
79238
  this._jumping = false;
79239
+ this._jumpHeld = false;
78624
79240
  this._pendingMove[0] = 0;
78625
79241
  this._pendingMove[1] = 0;
78626
79242
  this._pendingMove[2] = 0;
78627
79243
  this._accumulator = 0;
78628
79244
  }
78629
- /**
78630
- * Push the capsule upward until it clears solid geometry, up to a maximum of
78631
- * 100 iterations. Only used at spawn time to handle the case where walk mode
78632
- * activates inside a solid region. Per-frame collision resolution is unaffected,
78633
- * avoiding the ceiling launch bug.
78634
- */
78635
- _resolveSpawnCollision() {
78636
- const half = this.capsuleHeight * 0.5 - this.capsuleRadius;
78637
- const minStep = this.capsuleRadius;
78638
- for (let i = 0; i < 100; i++) {
78639
- const center = this._position.y - this.eyeHeight + this.capsuleHeight * 0.5;
78640
- if (!this.collision.queryCapsule(this._position.x, center, this._position.z, half, this.capsuleRadius, out)) {
78641
- break;
78642
- }
78643
- this._position.y += Math.max(out.y, minStep);
78644
- }
78645
- }
78646
79245
  /**
78647
79246
  * Cast multiple rays downward to find the average ground surface height.
78648
79247
  * Uses 5 rays (center + 4 cardinal at capsule radius) to spatially filter
78649
- * noisy voxel heights, giving the spring a smoother target.
79248
+ * noisy collision heights, giving the spring a smoother target.
78650
79249
  *
78651
79250
  * @param pos - Eye position in PlayCanvas world space.
78652
79251
  * @returns Average ground surface Y in PlayCanvas space, or null if no ground found.
@@ -78704,7 +79303,6 @@ class WalkController {
78704
79303
  }
78705
79304
  }
78706
79305
 
78707
- const RAD_TO_DEG = 180 / Math.PI;
78708
79306
  /** XZ distance below which the walker considers itself arrived */
78709
79307
  const ARRIVAL_DIST = 0.5;
78710
79308
  /** Minimum XZ speed (m/s) to not count as blocked */
@@ -78741,9 +79339,8 @@ class WalkSource {
78741
79339
  onComplete = null;
78742
79340
  _target = null;
78743
79341
  _yawRate = 0;
78744
- _blockedTime = 0;
78745
- _prevDist = Infinity;
78746
- get isWalking() {
79342
+ _progress = new ProgressTracker();
79343
+ get isActive() {
78747
79344
  return this._target !== null;
78748
79345
  }
78749
79346
  /**
@@ -78751,22 +79348,21 @@ class WalkSource {
78751
79348
  *
78752
79349
  * @param target - The destination (XZ used for navigation).
78753
79350
  */
78754
- walkTo(target) {
79351
+ navigateTo(target) {
78755
79352
  if (!this._target) {
78756
79353
  this._target = new Vec3();
78757
79354
  }
78758
79355
  this._target.copy(target);
78759
- this._blockedTime = 0;
78760
- this._prevDist = Infinity;
79356
+ this._progress.reset();
78761
79357
  }
78762
79358
  /**
78763
79359
  * Cancel any active auto-walk.
78764
79360
  */
78765
- cancelWalk() {
79361
+ cancel() {
78766
79362
  if (this._target) {
78767
79363
  this._target = null;
78768
79364
  this._yawRate = 0;
78769
- this._blockedTime = 0;
79365
+ this._progress.reset();
78770
79366
  this.onComplete?.();
78771
79367
  }
78772
79368
  }
@@ -78775,46 +79371,35 @@ class WalkSource {
78775
79371
  * before* the camera controller reads the frame.
78776
79372
  *
78777
79373
  * @param dt - Frame delta time in seconds.
78778
- * @param cameraPosition - Camera world position (previous frame output).
78779
- * @param cameraAngles - Camera Euler angles in degrees (previous frame output).
79374
+ * @param camera - The current camera state (read-only).
78780
79375
  * @param frame - The shared CameraFrame to append deltas to.
78781
79376
  */
78782
- update(dt, cameraPosition, cameraAngles, frame) {
79377
+ update(dt, camera, frame) {
78783
79378
  if (!this._target)
78784
79379
  return;
78785
79380
  const target = this._target;
79381
+ const cameraPosition = camera.position;
79382
+ const cameraAngles = camera.angles;
78786
79383
  const dx = target.x - cameraPosition.x;
78787
79384
  const dz = target.z - cameraPosition.z;
78788
79385
  const xzDist = Math.sqrt(dx * dx + dz * dz);
78789
79386
  // arrival
78790
79387
  if (xzDist < ARRIVAL_DIST) {
78791
- this.cancelWalk();
79388
+ this.cancel();
78792
79389
  return;
78793
79390
  }
78794
79391
  // blocked detection: compare with previous frame's distance
78795
- if (this._prevDist !== Infinity && dt > 0) {
78796
- const speed = (this._prevDist - xzDist) / dt;
78797
- if (speed < BLOCKED_SPEED) {
78798
- this._blockedTime += dt;
78799
- if (this._blockedTime >= BLOCKED_DURATION) {
78800
- this.cancelWalk();
78801
- return;
78802
- }
78803
- }
78804
- else {
78805
- this._blockedTime = 0;
78806
- }
79392
+ if (this._progress.update(xzDist, dt, BLOCKED_SPEED, BLOCKED_DURATION)) {
79393
+ this.cancel();
79394
+ return;
78807
79395
  }
78808
- this._prevDist = xzDist;
78809
79396
  // yaw toward target with smoothed turn rate
78810
- const targetYaw = Math.atan2(-dx, -dz) * RAD_TO_DEG;
78811
- let yawDiff = targetYaw - cameraAngles.y;
78812
- yawDiff = ((yawDiff % 360) + 540) % 360 - 180;
78813
- const desiredRate = Math.max(-this.maxTurnRate, Math.min(yawDiff * this.turnGain, this.maxTurnRate));
78814
- const smoothing = 1 - Math.exp(-4 * this.turnGain * dt);
78815
- this._yawRate += (desiredRate - this._yawRate) * smoothing;
79397
+ const yawDiff = getYawDiffToTarget(dx, dz, cameraAngles.y);
79398
+ this._yawRate = smoothTurnRate(this._yawRate, yawDiff, this.maxTurnRate, this.turnGain, dt);
79399
+ const yawStep = clampTurnStep(this._yawRate, yawDiff, dt);
79400
+ this._yawRate = dt > 0 ? yawStep / dt : this._yawRate;
78816
79401
  // WalkController applies: _angles.y += -rotate[0]
78817
- frame.deltas.rotate.append([-(this._yawRate * dt), 0, 0]);
79402
+ frame.deltas.rotate.append([-yawStep, 0, 0]);
78818
79403
  // scale forward speed by alignment: turn in place first, then accelerate
78819
79404
  const alignment = Math.max(0, Math.cos(yawDiff * Math.PI / 180));
78820
79405
  frame.deltas.move.append([0, 0, this.walkSpeed * dt * alignment]);
@@ -78876,8 +79461,13 @@ class CameraManager {
78876
79461
  controllers.fly.collision = collision;
78877
79462
  controllers.walk.collision = collision;
78878
79463
  const walkSource = new WalkSource();
78879
- walkSource.onComplete = () => {
78880
- events.fire('walkComplete');
79464
+ const flySource = new FlySource();
79465
+ const sourcesByMode = {
79466
+ walk: walkSource,
79467
+ fly: flySource
79468
+ };
79469
+ walkSource.onComplete = flySource.onComplete = () => {
79470
+ events.fire('navigateComplete');
78881
79471
  };
78882
79472
  const getController = (cameraMode) => {
78883
79473
  return controllers[cameraMode];
@@ -78899,6 +79489,7 @@ class CameraManager {
78899
79489
  // transition state
78900
79490
  const transitionSpeed = 1.0;
78901
79491
  let transitionTimer = 1;
79492
+ let clearOrbitTargetOnTransitionEnd = false;
78902
79493
  // start a new camera transition from the current pose
78903
79494
  const startTransition = () => {
78904
79495
  from.copy(this.camera);
@@ -78909,11 +79500,10 @@ class CameraManager {
78909
79500
  // use dt of 0 if animation is paused
78910
79501
  const dt = state.cameraMode === 'anim' && state.animationPaused ? 0 : deltaTime;
78911
79502
  // update transition timer
79503
+ const prevTransitionTimer = transitionTimer;
78912
79504
  transitionTimer = Math.min(1, transitionTimer + deltaTime * transitionSpeed);
78913
79505
  const controller = getController(state.cameraMode);
78914
- if (state.cameraMode === 'walk') {
78915
- walkSource.update(dt, this.camera.position, this.camera.angles, frame);
78916
- }
79506
+ sourcesByMode[state.cameraMode]?.update(dt, this.camera, frame);
78917
79507
  controller.update(dt, frame, target);
78918
79508
  if (transitionTimer < 1) {
78919
79509
  // lerp away from previous camera during transition
@@ -78926,19 +79516,38 @@ class CameraManager {
78926
79516
  if (state.cameraMode === 'anim') {
78927
79517
  state.animationTime = controllers.anim.animState.cursor.value;
78928
79518
  }
79519
+ if (clearOrbitTargetOnTransitionEnd && prevTransitionTimer < 1 && transitionTimer === 1) {
79520
+ clearOrbitTargetOnTransitionEnd = false;
79521
+ events.fire('orbitTarget:clear');
79522
+ }
78929
79523
  };
78930
79524
  // handle input events
78931
- events.on('inputEvent', (eventName, event) => {
79525
+ events.on('inputEvent', (eventName) => {
78932
79526
  switch (eventName) {
78933
79527
  case 'frame':
79528
+ events.fire('orbitTarget:clear');
78934
79529
  state.cameraMode = 'orbit';
78935
79530
  controllers.orbit.goto(frameCamera);
78936
79531
  startTransition();
78937
79532
  break;
78938
79533
  case 'reset':
78939
- state.cameraMode = 'orbit';
78940
- controllers.orbit.goto(resetCamera);
78941
- startTransition();
79534
+ if (state.cameraMode === 'walk') {
79535
+ walkSource.cancel();
79536
+ events.fire('navTarget:clear');
79537
+ startTransition();
79538
+ controllers.walk.resetToSpawn(target);
79539
+ }
79540
+ else if (state.cameraMode === 'fly') {
79541
+ flySource.cancel();
79542
+ startTransition();
79543
+ controllers.fly.resetToSpawn(target);
79544
+ }
79545
+ else {
79546
+ events.fire('orbitTarget:clear');
79547
+ state.cameraMode = 'orbit';
79548
+ controllers.orbit.goto(resetCamera);
79549
+ startTransition();
79550
+ }
78942
79551
  break;
78943
79552
  case 'playPause':
78944
79553
  if (state.hasAnimation) {
@@ -78984,9 +79593,7 @@ class CameraManager {
78984
79593
  });
78985
79594
  // handle camera mode switching
78986
79595
  events.on('cameraMode:changed', (value, prev) => {
78987
- if (prev === 'walk') {
78988
- walkSource.cancelWalk();
78989
- }
79596
+ sourcesByMode[prev]?.cancel();
78990
79597
  // snapshot the current pose before any controller mutation
78991
79598
  startTransition();
78992
79599
  target.copy(this.camera);
@@ -79014,8 +79621,10 @@ class CameraManager {
79014
79621
  tmpCamera.look(this.camera.position, position);
79015
79622
  controllers.orbit.goto(tmpCamera);
79016
79623
  startTransition();
79624
+ clearOrbitTargetOnTransitionEnd = true;
79017
79625
  });
79018
79626
  events.on('annotation.activate', (annotation) => {
79627
+ events.fire('orbitTarget:clear');
79019
79628
  // switch to orbit camera on pick
79020
79629
  state.cameraMode = 'orbit';
79021
79630
  const { initial } = annotation.camera;
@@ -79025,20 +79634,21 @@ class CameraManager {
79025
79634
  controllers.orbit.goto(tmpCamera);
79026
79635
  startTransition();
79027
79636
  });
79028
- // tap-to-walk: start auto-walking toward a picked 3D position
79029
- events.on('walkTo', (position, normal) => {
79030
- if (state.cameraMode === 'walk') {
79031
- walkSource.walkTo(position);
79032
- events.fire('walkTarget:set', position, normal);
79637
+ // tap-to-navigate: start auto-driving the active mode toward a picked position
79638
+ events.on('navigateTo', (position, normal) => {
79639
+ const source = sourcesByMode[state.cameraMode];
79640
+ if (source) {
79641
+ source.navigateTo(position);
79642
+ events.fire('navTarget:set', position, normal);
79033
79643
  }
79034
79644
  });
79035
- // cancel any active auto-walk
79036
- events.on('walkCancel', () => {
79037
- walkSource.cancelWalk();
79038
- events.fire('walkTarget:clear');
79645
+ // cancel any active auto-navigation in the current mode
79646
+ events.on('navigateCancel', () => {
79647
+ sourcesByMode[state.cameraMode]?.cancel();
79648
+ events.fire('navTarget:clear');
79039
79649
  });
79040
- events.on('walkComplete', () => {
79041
- events.fire('walkTarget:clear');
79650
+ events.on('navigateComplete', () => {
79651
+ events.fire('navTarget:clear');
79042
79652
  });
79043
79653
  }
79044
79654
  }
@@ -79066,6 +79676,11 @@ class InputModeTracker {
79066
79676
  }
79067
79677
  }
79068
79678
 
79679
+ const isCaptureMode$1 = (mode) => mode === 'walk' || mode === 'fly';
79680
+ const isWasdKey = (event) => (event.code === 'KeyW' ||
79681
+ event.code === 'KeyA' ||
79682
+ event.code === 'KeyS' ||
79683
+ event.code === 'KeyD');
79069
79684
  /**
79070
79685
  * Keyboard shortcuts that switch camera mode and toggle UI affordances.
79071
79686
  * Listens on `window` so the user can press 1/2/3, V, G, H, F, R, Space,
@@ -79080,8 +79695,8 @@ class ModeShortcuts {
79080
79695
  return;
79081
79696
  const { state, events } = global;
79082
79697
  if (event.key === 'Escape') {
79083
- if (this._pointerLock?.recentlyExitedWalk) ;
79084
- else if (state.cameraMode === 'walk' && state.gamingControls && state.inputMode === 'desktop') {
79698
+ if (this._pointerLock?.recentlyExitedCapture) ;
79699
+ else if (isCaptureMode$1(state.cameraMode) && state.gamingControls && state.inputMode === 'desktop') {
79085
79700
  state.gamingControls = false;
79086
79701
  }
79087
79702
  else if (state.cameraMode === 'walk') {
@@ -79116,10 +79731,17 @@ class ModeShortcuts {
79116
79731
  case 'h':
79117
79732
  events.fire('inputEvent', 'toggleHelp');
79118
79733
  break;
79734
+ case 'r':
79735
+ events.fire('inputEvent', 'reset', event);
79736
+ break;
79119
79737
  default:
79120
- if ((event.code === 'KeyW' || event.code === 'KeyA' || event.code === 'KeyS' || event.code === 'KeyD') &&
79121
- state.cameraMode === 'walk' && state.inputMode === 'desktop' && !state.gamingControls) {
79122
- state.gamingControls = true;
79738
+ if (isWasdKey(event) && state.inputMode === 'desktop') {
79739
+ if (!isCaptureMode$1(state.cameraMode)) {
79740
+ state.cameraMode = 'fly';
79741
+ }
79742
+ if (!state.gamingControls) {
79743
+ state.gamingControls = true;
79744
+ }
79123
79745
  }
79124
79746
  break;
79125
79747
  }
@@ -79128,9 +79750,6 @@ class ModeShortcuts {
79128
79750
  case 'f':
79129
79751
  events.fire('inputEvent', 'frame', event);
79130
79752
  break;
79131
- case 'r':
79132
- events.fire('inputEvent', 'reset', event);
79133
- break;
79134
79753
  case ' ':
79135
79754
  events.fire('inputEvent', 'playPause', event);
79136
79755
  break;
@@ -79150,33 +79769,342 @@ class ModeShortcuts {
79150
79769
  }
79151
79770
 
79152
79771
  /**
79153
- * Manages the browser's pointer-lock API for walk-mode + gaming controls
79154
- * on desktop. Toggles in response to `cameraMode:changed` and
79155
- * `gamingControls:changed`, and reverts state if the lock is exited or
79156
- * rejected.
79772
+ * Displacement-based inputs (mouse, touch, wheel, pinch) return accumulated
79773
+ * pixel offsets that already scale with frame time. This factor converts
79774
+ * rate-based speed constants (tuned for degrees-per-second) to work with
79775
+ * per-frame displacements, making them frame-rate-independent.
79776
+ */
79777
+ const DISPLACEMENT_SCALE = 1 / 60;
79778
+ /** Maximum accumulated touch movement (px) to still count as a tap. */
79779
+ const TAP_EPSILON = 15;
79780
+ const tmpHalfSize = new Vec3();
79781
+ /**
79782
+ * Converts screen-space pixel deltas to a world-space pan vector at the
79783
+ * given depth.
79784
+ *
79785
+ * @param camera - The camera component.
79786
+ * @param dx - Horizontal pixel delta.
79787
+ * @param dy - Vertical pixel delta.
79788
+ * @param dz - Depth (world-space) at which to project the delta.
79789
+ * @param out - Optional output vector.
79790
+ * @returns The pan vector in world space.
79791
+ */
79792
+ const screenToWorld = (camera, dx, dy, dz, out = new Vec3()) => {
79793
+ const { system, fov, aspectRatio, horizontalFov, projection, orthoHeight } = camera;
79794
+ const { width, height } = system.app.graphicsDevice.clientRect;
79795
+ out.set(-(dx / width) * 2, (dy / height) * 2, 0);
79796
+ const halfSize = tmpHalfSize.set(0, 0, 0);
79797
+ if (projection === PROJECTION_PERSPECTIVE) {
79798
+ const halfSlice = dz * Math.tan(0.5 * fov * math.DEG_TO_RAD);
79799
+ if (horizontalFov) {
79800
+ halfSize.set(halfSlice, halfSlice / aspectRatio, 0);
79801
+ }
79802
+ else {
79803
+ halfSize.set(halfSlice * aspectRatio, halfSlice, 0);
79804
+ }
79805
+ }
79806
+ else {
79807
+ halfSize.set(orthoHeight * aspectRatio, orthoHeight, 0);
79808
+ }
79809
+ out.mul(halfSize);
79810
+ return out;
79811
+ };
79812
+ /**
79813
+ * The orbit camera and the fly camera disagree on the sign of the z-axis
79814
+ * for forward motion. Apply this when emitting a forward/back z-component
79815
+ * so the same wheel-style delta drives both cameras correctly.
79157
79816
  *
79158
- * Also exposes `recentlyExitedWalk` so the keyboard-shortcut handler can
79817
+ * @param mode - The current camera mode.
79818
+ * @param z - The raw forward/back z-component.
79819
+ * @returns The z-component flipped for orbit mode, unchanged otherwise.
79820
+ */
79821
+ const flipZForOrbit = (mode, z) => (mode === 'orbit' ? -z : z);
79822
+
79823
+ const tmpV$4 = new Vec3();
79824
+ const canTargetFly = (global) => (global.state.cameraMode === 'fly' &&
79825
+ !(global.state.inputMode === 'desktop' && global.state.gamingControls));
79826
+ /**
79827
+ * Click-to-walk / click-to-fly / click-to-focus (desktop), tap equivalents
79828
+ * on mobile, and double-click-to-pick fallback. Uses collision first and
79829
+ * rendered-scene picking when collision is unavailable.
79830
+ */
79831
+ class NavInteraction {
79832
+ collision = null;
79833
+ _picker;
79834
+ _global = null;
79835
+ _canvas = null;
79836
+ _lastPointerOffsetX = 0;
79837
+ _lastPointerOffsetY = 0;
79838
+ _mouseClickTracking = false;
79839
+ _mouseClickDelta = 0;
79840
+ _suppressClick = false;
79841
+ _targetPickRequest = 0;
79842
+ _lastTap = { time: 0, x: 0, y: 0 };
79843
+ constructor(picker) {
79844
+ this._picker = picker;
79845
+ }
79846
+ _updateCursor = () => {
79847
+ const global = this._global;
79848
+ const canvas = this._canvas;
79849
+ if (!global || !canvas)
79850
+ return;
79851
+ const { state } = global;
79852
+ const canClickTarget = state.inputMode === 'desktop' && ((state.cameraMode === 'walk' && !state.gamingControls) ||
79853
+ canTargetFly(global) ||
79854
+ state.cameraMode === 'orbit');
79855
+ if (canClickTarget) {
79856
+ canvas.style.cursor = this._mouseClickTracking ? 'default' : 'pointer';
79857
+ }
79858
+ else {
79859
+ canvas.style.cursor = '';
79860
+ }
79861
+ };
79862
+ _onCameraModeChanged = () => {
79863
+ this._targetPickRequest++;
79864
+ this._updateCursor();
79865
+ };
79866
+ _pickCollision(offsetX, offsetY) {
79867
+ if (!this.collision || !this._global)
79868
+ return null;
79869
+ const camera = this._global.camera;
79870
+ const cameraPos = camera.getPosition();
79871
+ camera.camera.screenToWorld(offsetX, offsetY, 1.0, tmpV$4);
79872
+ tmpV$4.sub(cameraPos).normalize();
79873
+ const hit = this.collision.queryRay(cameraPos.x, cameraPos.y, cameraPos.z, tmpV$4.x, tmpV$4.y, tmpV$4.z, camera.camera.farClip);
79874
+ if (!hit)
79875
+ return null;
79876
+ const sn = this.collision.querySurfaceNormal(hit.x, hit.y, hit.z, tmpV$4.x, tmpV$4.y, tmpV$4.z);
79877
+ return {
79878
+ position: new Vec3(hit.x, hit.y, hit.z),
79879
+ normal: new Vec3(sn.nx, sn.ny, sn.nz)
79880
+ };
79881
+ }
79882
+ async _pickSceneTarget(offsetX, offsetY) {
79883
+ const global = this._global;
79884
+ const canvas = this._canvas;
79885
+ if (!global || !canvas)
79886
+ return null;
79887
+ const collisionTarget = this._pickCollision(offsetX, offsetY);
79888
+ if (collisionTarget) {
79889
+ return collisionTarget;
79890
+ }
79891
+ const result = await this._picker.pickSurface(offsetX / canvas.clientWidth, offsetY / canvas.clientHeight);
79892
+ if (result) {
79893
+ return result;
79894
+ }
79895
+ return null;
79896
+ }
79897
+ async _flyToPickedPosition(offsetX, offsetY) {
79898
+ const global = this._global;
79899
+ if (!global || !canTargetFly(global))
79900
+ return;
79901
+ const request = ++this._targetPickRequest;
79902
+ const target = await this._pickSceneTarget(offsetX, offsetY);
79903
+ if (target && request === this._targetPickRequest && this._global && canTargetFly(this._global)) {
79904
+ this._global.events.fire('navigateTo', target.position, target.normal);
79905
+ }
79906
+ }
79907
+ async _focusPickedPosition(offsetX, offsetY) {
79908
+ const global = this._global;
79909
+ if (!global || global.state.cameraMode !== 'orbit')
79910
+ return;
79911
+ const request = ++this._targetPickRequest;
79912
+ const target = await this._pickSceneTarget(offsetX, offsetY);
79913
+ if (target && request === this._targetPickRequest && this._global?.state.cameraMode === 'orbit') {
79914
+ const { events } = this._global;
79915
+ events.fire('orbitTarget:set', target.position, target.normal);
79916
+ events.fire('pick', target.position);
79917
+ }
79918
+ }
79919
+ _onPointerDown = (event) => {
79920
+ const global = this._global;
79921
+ if (!global)
79922
+ return;
79923
+ const { events } = global;
79924
+ // record offsets for click/tap target picking
79925
+ this._lastPointerOffsetX = event.offsetX;
79926
+ this._lastPointerOffsetY = event.offsetY;
79927
+ // start desktop click target tracking
79928
+ if (event.pointerType !== 'touch' && event.button === 0) {
79929
+ this._mouseClickTracking = true;
79930
+ this._mouseClickDelta = 0;
79931
+ this._updateCursor();
79932
+ }
79933
+ // Manual double-click/tap detection for platforms that do not emit
79934
+ // reliable native dblclick events on the canvas.
79935
+ const now = Date.now();
79936
+ const delay = Math.max(0, now - this._lastTap.time);
79937
+ if (delay < 300 &&
79938
+ Math.abs(event.clientX - this._lastTap.x) < 8 &&
79939
+ Math.abs(event.clientY - this._lastTap.y) < 8) {
79940
+ this._suppressClick = true;
79941
+ events.fire('inputEvent', 'dblclick', event);
79942
+ this._lastTap.time = 0;
79943
+ }
79944
+ else {
79945
+ this._lastTap.time = now;
79946
+ this._lastTap.x = event.clientX;
79947
+ this._lastTap.y = event.clientY;
79948
+ }
79949
+ };
79950
+ _onPointerMove = (event) => {
79951
+ const global = this._global;
79952
+ if (!global)
79953
+ return;
79954
+ const { state, events } = global;
79955
+ if (this._mouseClickTracking && event.pointerType !== 'touch') {
79956
+ const prev = this._mouseClickDelta;
79957
+ this._mouseClickDelta += Math.abs(event.movementX) + Math.abs(event.movementY);
79958
+ if (prev < TAP_EPSILON && this._mouseClickDelta >= TAP_EPSILON) {
79959
+ if ((state.cameraMode === 'walk' && !state.gamingControls) || canTargetFly(global)) {
79960
+ events.fire('navigateCancel');
79961
+ }
79962
+ }
79963
+ }
79964
+ };
79965
+ _onPointerUp = (event) => {
79966
+ const global = this._global;
79967
+ if (!global)
79968
+ return;
79969
+ const { state, events } = global;
79970
+ if (this._mouseClickTracking && event.pointerType !== 'touch' && event.button === 0) {
79971
+ this._mouseClickTracking = false;
79972
+ this._updateCursor();
79973
+ if (this._suppressClick) {
79974
+ this._suppressClick = false;
79975
+ return;
79976
+ }
79977
+ if (this._mouseClickDelta < TAP_EPSILON) {
79978
+ if (state.cameraMode === 'walk' && !state.gamingControls) {
79979
+ const result = this._pickCollision(this._lastPointerOffsetX, this._lastPointerOffsetY);
79980
+ if (result) {
79981
+ events.fire('navigateTo', result.position, result.normal);
79982
+ }
79983
+ }
79984
+ else if (state.cameraMode === 'fly') {
79985
+ this._flyToPickedPosition(this._lastPointerOffsetX, this._lastPointerOffsetY);
79986
+ }
79987
+ else if (state.cameraMode === 'orbit') {
79988
+ this._focusPickedPosition(this._lastPointerOffsetX, this._lastPointerOffsetY);
79989
+ }
79990
+ }
79991
+ }
79992
+ };
79993
+ _onInputEvent = async (eventName, event) => {
79994
+ const global = this._global;
79995
+ const canvas = this._canvas;
79996
+ if (!global || !canvas)
79997
+ return;
79998
+ if (eventName !== 'dblclick')
79999
+ return;
80000
+ if (!(event instanceof MouseEvent))
80001
+ return;
80002
+ const { events, state } = global;
80003
+ // dblclick swaps the active mode and uses the picked target:
80004
+ // fly → orbit, focus orbit at point
80005
+ // orbit / walk → fly, navigate fly toward point
80006
+ const request = ++this._targetPickRequest;
80007
+ const target = await this._pickSceneTarget(event.offsetX, event.offsetY);
80008
+ if (!target || request !== this._targetPickRequest)
80009
+ return;
80010
+ const currentMode = this._global?.state.cameraMode;
80011
+ if (currentMode === 'fly') {
80012
+ // 'pick' switches mode to orbit, which cancels the active fly nav
80013
+ // and would clobber any pre-set orbit target — set it after.
80014
+ events.fire('pick', target.position);
80015
+ events.fire('orbitTarget:set', target.position, target.normal);
80016
+ }
80017
+ else if (currentMode === 'orbit' || currentMode === 'walk') {
80018
+ state.cameraMode = 'fly';
80019
+ events.fire('navigateTo', target.position, target.normal);
80020
+ }
80021
+ };
80022
+ _onMobileTap = () => {
80023
+ const global = this._global;
80024
+ if (!global)
80025
+ return;
80026
+ const { state, events } = global;
80027
+ if (this._suppressClick) {
80028
+ this._suppressClick = false;
80029
+ return;
80030
+ }
80031
+ if (state.cameraMode === 'walk' && !state.gamingControls) {
80032
+ const result = this._pickCollision(this._lastPointerOffsetX, this._lastPointerOffsetY);
80033
+ if (result) {
80034
+ events.fire('navigateTo', result.position, result.normal);
80035
+ }
80036
+ }
80037
+ else if (state.cameraMode === 'fly') {
80038
+ this._flyToPickedPosition(this._lastPointerOffsetX, this._lastPointerOffsetY);
80039
+ }
80040
+ else if (state.cameraMode === 'orbit') {
80041
+ this._focusPickedPosition(this._lastPointerOffsetX, this._lastPointerOffsetY);
80042
+ }
80043
+ };
80044
+ attach(canvas, global) {
80045
+ this._canvas = canvas;
80046
+ this._global = global;
80047
+ const { events } = global;
80048
+ canvas.addEventListener('pointerdown', this._onPointerDown);
80049
+ canvas.addEventListener('pointermove', this._onPointerMove);
80050
+ canvas.addEventListener('pointerup', this._onPointerUp);
80051
+ // double-click/tap fallback -> fly target or orbit focus (skipped in walk mode)
80052
+ events.on('inputEvent', this._onInputEvent);
80053
+ // mobile tap (no movement) → walk/fly target or orbit focus
80054
+ events.on('mobileTap', this._onMobileTap);
80055
+ // refresh cursor on mode / gaming-controls change
80056
+ events.on('cameraMode:changed', this._onCameraModeChanged);
80057
+ events.on('inputMode:changed', this._updateCursor);
80058
+ events.on('gamingControls:changed', this._updateCursor);
80059
+ }
80060
+ detach() {
80061
+ if (this._canvas) {
80062
+ this._canvas.removeEventListener('pointerdown', this._onPointerDown);
80063
+ this._canvas.removeEventListener('pointermove', this._onPointerMove);
80064
+ this._canvas.removeEventListener('pointerup', this._onPointerUp);
80065
+ }
80066
+ if (this._global) {
80067
+ const { events } = this._global;
80068
+ events.off('inputEvent', this._onInputEvent);
80069
+ events.off('mobileTap', this._onMobileTap);
80070
+ events.off('cameraMode:changed', this._onCameraModeChanged);
80071
+ events.off('inputMode:changed', this._updateCursor);
80072
+ events.off('gamingControls:changed', this._updateCursor);
80073
+ }
80074
+ this._canvas = null;
80075
+ this._global = null;
80076
+ }
80077
+ }
80078
+
80079
+ const isCaptureMode = (mode) => mode === 'walk' || mode === 'fly';
80080
+ const hasUserActivation = () => (navigator.userActivation?.isActive === true);
80081
+ /**
80082
+ * Manages the browser's pointer-lock API for first-person gaming controls
80083
+ * on desktop. Toggles in response to camera mode, input mode, and
80084
+ * gaming-controls changes, and reverts state if the lock is exited or rejected.
80085
+ *
80086
+ * Also exposes `recentlyExitedCapture` so the keyboard-shortcut handler can
79159
80087
  * de-duplicate the Escape keydown that triggered the lock exit.
79160
80088
  */
79161
80089
  class PointerLockManager {
79162
80090
  _global = null;
79163
80091
  _canvas = null;
79164
80092
  _keyboardMouse = null;
79165
- _recentlyExitedWalk = false;
80093
+ _recentlyExitedCapture = false;
79166
80094
  _onPointerLockChange = () => {
79167
80095
  const global = this._global;
79168
80096
  if (!global)
79169
80097
  return;
79170
80098
  const { state, events } = global;
79171
- if (!document.pointerLockElement && state.cameraMode === 'walk' && state.gamingControls) {
79172
- this._recentlyExitedWalk = true;
80099
+ if (!document.pointerLockElement && isCaptureMode(state.cameraMode) && state.gamingControls) {
80100
+ this._recentlyExitedCapture = true;
79173
80101
  requestAnimationFrame(() => {
79174
- this._recentlyExitedWalk = false;
80102
+ this._recentlyExitedCapture = false;
79175
80103
  });
79176
80104
  if (state.inputMode === 'desktop') {
79177
80105
  state.gamingControls = false;
79178
80106
  }
79179
- else {
80107
+ else if (state.cameraMode === 'walk') {
79180
80108
  events.fire('inputEvent', 'exitWalk');
79181
80109
  }
79182
80110
  }
@@ -79192,10 +80120,10 @@ class PointerLockManager {
79192
80120
  if (!global)
79193
80121
  return;
79194
80122
  const { state, events } = global;
79195
- if (state.inputMode === 'desktop') {
80123
+ if (state.inputMode === 'desktop' && isCaptureMode(state.cameraMode)) {
79196
80124
  state.gamingControls = false;
79197
80125
  }
79198
- else {
80126
+ else if (state.cameraMode === 'walk') {
79199
80127
  events.fire('inputEvent', 'exitWalk');
79200
80128
  }
79201
80129
  };
@@ -79203,10 +80131,10 @@ class PointerLockManager {
79203
80131
  const state = this._global?.state;
79204
80132
  if (!state)
79205
80133
  return;
79206
- if (value === 'walk' && state.inputMode === 'desktop' && state.gamingControls) {
80134
+ if (isCaptureMode(value) && state.inputMode === 'desktop' && state.gamingControls) {
79207
80135
  this._activate();
79208
80136
  }
79209
- else if (prev === 'walk') {
80137
+ else if (isCaptureMode(prev)) {
79210
80138
  this._deactivate();
79211
80139
  }
79212
80140
  };
@@ -79214,7 +80142,7 @@ class PointerLockManager {
79214
80142
  const state = this._global?.state;
79215
80143
  if (!state)
79216
80144
  return;
79217
- if (state.cameraMode === 'walk' && state.inputMode === 'desktop') {
80145
+ if (isCaptureMode(state.cameraMode) && state.inputMode === 'desktop') {
79218
80146
  if (value) {
79219
80147
  this._activate();
79220
80148
  }
@@ -79223,11 +80151,31 @@ class PointerLockManager {
79223
80151
  }
79224
80152
  }
79225
80153
  };
80154
+ _onInputModeChanged = (value) => {
80155
+ const state = this._global?.state;
80156
+ if (!state || !isCaptureMode(state.cameraMode) || !state.gamingControls) {
80157
+ return;
80158
+ }
80159
+ if (value === 'desktop' && hasUserActivation()) {
80160
+ this._activate();
80161
+ }
80162
+ else if (value !== 'desktop') {
80163
+ this._deactivate();
80164
+ }
80165
+ };
80166
+ _onPointerDown = () => {
80167
+ const state = this._global?.state;
80168
+ if (state && state.inputMode === 'desktop' && isCaptureMode(state.cameraMode) && state.gamingControls) {
80169
+ this._activate();
80170
+ }
80171
+ };
79226
80172
  _activate() {
79227
80173
  if (this._keyboardMouse) {
79228
80174
  this._keyboardMouse.source._pointerLock = true;
79229
80175
  }
79230
- this._canvas?.requestPointerLock();
80176
+ if (document.pointerLockElement !== this._canvas) {
80177
+ this._canvas?.requestPointerLock();
80178
+ }
79231
80179
  }
79232
80180
  _deactivate() {
79233
80181
  if (this._keyboardMouse) {
@@ -79237,8 +80185,8 @@ class PointerLockManager {
79237
80185
  document.exitPointerLock();
79238
80186
  }
79239
80187
  }
79240
- get recentlyExitedWalk() {
79241
- return this._recentlyExitedWalk;
80188
+ get recentlyExitedCapture() {
80189
+ return this._recentlyExitedCapture;
79242
80190
  }
79243
80191
  attach(canvas, global, keyboardMouse) {
79244
80192
  this._canvas = canvas;
@@ -79247,6 +80195,8 @@ class PointerLockManager {
79247
80195
  const { events } = global;
79248
80196
  events.on('cameraMode:changed', this._onCameraModeChanged);
79249
80197
  events.on('gamingControls:changed', this._onGamingControlsChanged);
80198
+ events.on('inputMode:changed', this._onInputModeChanged);
80199
+ canvas.addEventListener('pointerdown', this._onPointerDown);
79250
80200
  document.addEventListener('pointerlockchange', this._onPointerLockChange);
79251
80201
  document.addEventListener('pointerlockerror', this._onPointerLockError);
79252
80202
  }
@@ -79255,7 +80205,9 @@ class PointerLockManager {
79255
80205
  const { events } = this._global;
79256
80206
  events.off('cameraMode:changed', this._onCameraModeChanged);
79257
80207
  events.off('gamingControls:changed', this._onGamingControlsChanged);
80208
+ events.off('inputMode:changed', this._onInputModeChanged);
79258
80209
  }
80210
+ this._canvas?.removeEventListener('pointerdown', this._onPointerDown);
79259
80211
  document.removeEventListener('pointerlockchange', this._onPointerLockChange);
79260
80212
  document.removeEventListener('pointerlockerror', this._onPointerLockError);
79261
80213
  this._canvas = null;
@@ -79264,806 +80216,289 @@ class PointerLockManager {
79264
80216
  }
79265
80217
  }
79266
80218
 
79267
- /**
79268
- * Double-click world picking for splat scenes.
79269
- *
79270
- * - **Compute renderer (WebGPU tiled-compute)**: uses engine `Picker` with depth enabled — expected
79271
- * depth is already provided by the tile-composite path.
79272
- * - **Raster renderers (WebGL, CPU / GPU sort, etc.)**: custom `pickPS` / `gsplatPS` patch plus
79273
- * `RGBA16F` alpha-weighted depth accumulation, because the stock pick pass encodes splat IDs /
79274
- * last-fragment depth rather than expected depth.
79275
- */
79276
- // Override global picking to pack alpha-weighted splat depth instead of meshInstance id.
79277
- const pickDepthGlsl = /* glsl */ `
79278
- vec4 encodePickOutput(uint id) {
79279
- const vec4 inv = vec4(1.0 / 255.0);
79280
- const uvec4 shifts = uvec4(16, 8, 0, 24);
79281
- uvec4 col = (uvec4(id) >> shifts) & uvec4(0xff);
79282
- return vec4(col) * inv;
79283
- }
79284
-
79285
- #ifdef GSPLAT_PICK_DEPTH
79286
- #ifndef CAMERAPLANES
79287
- #define CAMERAPLANES
79288
- uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
79289
- #endif
79290
-
79291
- vec4 getPickOutput() {
79292
- float normalizedDepth;
79293
- if (camera_params.w > 0.5) {
79294
- normalizedDepth = gl_FragCoord.z;
79295
- } else {
79296
- float linearDepth = 1.0 / gl_FragCoord.w;
79297
- normalizedDepth = (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);
79298
- }
79299
-
79300
- return vec4(gaussianColor.a * normalizedDepth, 0.0, 0.0, gaussianColor.a);
80219
+ const tmpV$3 = new Vec3();
80220
+ const stickMove = new Vec3();
80221
+ const stickRotate = new Vec3();
80222
+ class GamepadDevice {
80223
+ moveSpeed = 4;
80224
+ orbitSpeed = 18;
80225
+ gamepadRotateSensitivity = 1.0;
80226
+ _source = new GamepadSource();
80227
+ _global = null;
80228
+ attach(_canvas, global) {
80229
+ this._global = global;
80230
+ // GamepadSource polls navigator.getGamepads() — no DOM attach needed.
79301
80231
  }
79302
- #else
79303
- #ifndef PICK_CUSTOM_ID
79304
- uniform uint meshInstanceId;
79305
-
79306
- vec4 getPickOutput() {
79307
- return encodePickOutput(meshInstanceId);
79308
- }
79309
- #endif
79310
- #endif
79311
-
79312
- #ifdef DEPTH_PICK_PASS
79313
- #include "floatAsUintPS"
79314
- #ifndef CAMERAPLANES
79315
- #define CAMERAPLANES
79316
- uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
79317
- #endif
79318
-
79319
- vec4 getPickDepth() {
79320
- float linearDepth;
79321
- if (camera_params.w > 0.5) {
79322
- linearDepth = gl_FragCoord.z;
79323
- } else {
79324
- float viewDist = 1.0 / gl_FragCoord.w;
79325
- linearDepth = (viewDist - camera_params.z) / (camera_params.y - camera_params.z);
80232
+ detach() {
80233
+ this._global = null;
80234
+ }
80235
+ update(ctx, frame) {
80236
+ const { dt, cameraComponent, isFly, isFirstPerson } = ctx;
80237
+ const { leftStick, rightStick } = this._source.read();
80238
+ const orbitFactor = isFirstPerson ? cameraComponent.fov / 120 : 1;
80239
+ const { deltas } = frame;
80240
+ if (isFly && (leftStick[0] !== 0 || leftStick[1] !== 0 || rightStick[0] !== 0 || rightStick[1] !== 0)) {
80241
+ this._global?.events.fire('navigateCancel');
79326
80242
  }
79327
- return float2uint(linearDepth);
80243
+ const v = tmpV$3.set(0, 0, 0);
80244
+ stickMove.set(leftStick[0], 0, -leftStick[1]);
80245
+ v.add(stickMove.mulScalar(this.moveSpeed * dt));
80246
+ deltas.move.append([v.x, v.y, v.z]);
80247
+ v.set(0, 0, 0);
80248
+ stickRotate.set(rightStick[0], rightStick[1], 0);
80249
+ v.add(stickRotate.mulScalar(this.orbitSpeed * orbitFactor * this.gamepadRotateSensitivity * dt));
80250
+ deltas.rotate.append([v.x, v.y, v.z]);
79328
80251
  }
79329
- #endif
79330
- `;
79331
- const pickDepthWgsl = /* wgsl */ `
79332
- fn encodePickOutput(id: u32) -> vec4f {
79333
- let inv: vec4f = vec4f(1.0 / 255.0);
79334
- let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);
79335
- let col: vec4u = (vec4u(id) >> shifts) & vec4u(0xffu);
79336
- return vec4f(col) * inv;
79337
80252
  }
79338
80253
 
79339
- #ifdef GSPLAT_PICK_DEPTH
79340
- #ifndef CAMERAPLANES
79341
- #define CAMERAPLANES
79342
- uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
79343
- #endif
79344
-
79345
- fn getPickOutput() -> vec4f {
79346
- var normalizedDepth: f32;
79347
- if (uniform.camera_params.w > 0.5) {
79348
- normalizedDepth = pcPosition.z;
79349
- } else {
79350
- let linearDepth = 1.0 / pcPosition.w;
79351
- normalizedDepth = (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
80254
+ const tmpV1 = new Vec3();
80255
+ const tmpV2 = new Vec3();
80256
+ const keyMove = new Vec3();
80257
+ const flyKeyVelocity = new Vec3();
80258
+ const panMove = new Vec3();
80259
+ const mouseRotate = new Vec3();
80260
+ const wheelMove = new Vec3();
80261
+ // Patch keydown / keyup so meta-key combinations don't leave keys stuck on
80262
+ // macOS (the OS swallows keyup for any key released while Cmd is held).
80263
+ const patchKeyboardMeta = (desktopInput) => {
80264
+ const origOnKeyDown = desktopInput._onKeyDown;
80265
+ desktopInput._onKeyDown = (event) => {
80266
+ if (event.key === 'Meta') {
80267
+ desktopInput._keyNow.fill(0);
79352
80268
  }
79353
-
79354
- let a = f32(gaussianColor.a);
79355
- return vec4f(a * normalizedDepth, 0.0, 0.0, a);
79356
- }
79357
- #else
79358
- #ifndef PICK_CUSTOM_ID
79359
- uniform meshInstanceId: u32;
79360
-
79361
- fn getPickOutput() -> vec4f {
79362
- return encodePickOutput(uniform.meshInstanceId);
80269
+ else if (!event.metaKey) {
80270
+ origOnKeyDown(event);
79363
80271
  }
79364
- #endif
79365
- #endif
79366
-
79367
- #ifdef DEPTH_PICK_PASS
79368
- #include "floatAsUintPS"
79369
- #ifndef CAMERAPLANES
79370
- #define CAMERAPLANES
79371
- uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
79372
- #endif
79373
-
79374
- fn getPickDepth() -> vec4f {
79375
- var linearDepth: f32;
79376
- if (uniform.camera_params.w > 0.5) {
79377
- linearDepth = pcPosition.z;
79378
- } else {
79379
- let viewDist = 1.0 / pcPosition.w;
79380
- linearDepth = (viewDist - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
80272
+ };
80273
+ const origOnKeyUp = desktopInput._onKeyUp;
80274
+ desktopInput._onKeyUp = (event) => {
80275
+ if (event.key === 'Meta') {
80276
+ desktopInput._keyNow.fill(0);
79381
80277
  }
79382
- return float2uint(linearDepth);
80278
+ else if (!event.metaKey) {
80279
+ origOnKeyUp(event);
80280
+ }
80281
+ };
80282
+ };
80283
+ class KeyboardMouseDevice {
80284
+ moveSpeed = 4;
80285
+ orbitSpeed = 18;
80286
+ wheelSpeed = 0.06;
80287
+ mouseRotateSensitivity = 0.5;
80288
+ flyMoveAccelerationDamping = 0.992;
80289
+ flyMoveDecelerationDamping = 0.993;
80290
+ _source = new KeyboardMouseSource();
80291
+ _global = null;
80292
+ /** Running WASD/QE/arrow direction (sum of key states). */
80293
+ _axis = new Vec3();
80294
+ /** Running button-held state per index: [LMB, MMB, RMB]. */
80295
+ _buttons = [0, 0, 0];
80296
+ _shift = 0;
80297
+ _ctrl = 0;
80298
+ _jump = 0;
80299
+ _flyKeyVelocity = new Vec3();
80300
+ /**
80301
+ * Get the underlying source so other code (PointerLockManager) can
80302
+ * toggle its private pointer-lock flag, which gates how it consumes
80303
+ * mouse-delta events.
80304
+ *
80305
+ * @returns The PlayCanvas KeyboardMouseSource backing this device.
80306
+ */
80307
+ get source() {
80308
+ return this._source;
79383
80309
  }
79384
- #endif
79385
- `;
79386
- const pickPassChunkInjected = [
79387
- '#ifdef PICK_PASS',
79388
- ' #define GSPLAT_PICK_DEPTH',
79389
- ' #include "pickPS"',
79390
- '#endif'
79391
- ].join('\n');
79392
- const safeChunkReplace = (s, find, repl) => {
79393
- const out = s.replace(find, repl);
79394
- if (out === s) {
79395
- throw new Error('picker: engine gsplat/pick chunk patch failed (engine version mismatch?)');
80310
+ attach(canvas, global) {
80311
+ this._global = global;
80312
+ patchKeyboardMeta(this._source);
80313
+ this._source.attach(canvas);
79396
80314
  }
79397
- return out;
79398
- };
79399
- const patchGsplatPickGlsl = (chunk) => {
79400
- return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'pcFragColor0 = encodePickOutput(vPickId);', 'pcFragColor0 = getPickOutput();');
79401
- };
79402
- const patchGsplatPickWgsl = (chunk) => {
79403
- return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'output.color = encodePickOutput(vPickId);', 'output.color = getPickOutput();');
79404
- };
79405
- /** Per-device original chunk strings + refcount so we can restore after the last Picker releases. */
79406
- const pickerShaderPatchState = new WeakMap();
79407
- const vec4 = new Vec4();
79408
- const viewProjMat = new Mat4();
79409
- const clearColor = new Color(0, 0, 0, 1);
79410
- // Shared buffer for half-to-float conversion
79411
- const float32 = new Float32Array(1);
79412
- const uint32 = new Uint32Array(float32.buffer);
79413
- // Convert 16-bit half-float to 32-bit float using bit manipulation.
79414
- const half2Float = (h) => {
79415
- const sign = (h & 0x8000) << 16;
79416
- const exponent = (h & 0x7C00) >> 10;
79417
- const mantissa = h & 0x03FF;
79418
- if (exponent === 0) {
79419
- if (mantissa === 0) {
79420
- uint32[0] = sign;
80315
+ detach() {
80316
+ // KeyboardMouseSource does not expose a detach; nothing to undo for
80317
+ // its DOM listeners here.
80318
+ }
80319
+ update(ctx, frame) {
80320
+ const { keyCode } = KeyboardMouseSource;
80321
+ const { key, button, mouse, wheel } = this._source.read();
80322
+ const { events } = this._global;
80323
+ // accumulate running input state
80324
+ this._axis.add(tmpV1.set((key[keyCode.D] - key[keyCode.A]) + (key[keyCode.RIGHT] - key[keyCode.LEFT]), (key[keyCode.E] - key[keyCode.Q]), (key[keyCode.W] - key[keyCode.S]) + (key[keyCode.UP] - key[keyCode.DOWN])));
80325
+ this._jump += key[keyCode.SPACE];
80326
+ this._shift += key[keyCode.SHIFT];
80327
+ this._ctrl += key[keyCode.CTRL];
80328
+ const n = Math.min(button.length, this._buttons.length);
80329
+ for (let i = 0; i < n; i++) {
80330
+ this._buttons[i] += button[i];
80331
+ }
80332
+ const { isFly, isWalk, isFirstPerson, gamingControls, dt, distance, cameraComponent, mode, touchCount } = ctx;
80333
+ const pan = this._buttons[2] || +(button[2] === -1) || +(touchCount > 1);
80334
+ // auto-move cancellation and requestFirstPerson events (driven by keyboard axes)
80335
+ if (isWalk && (this._axis.x !== 0 || this._axis.z !== 0)) {
80336
+ events.fire('navigateCancel');
80337
+ }
80338
+ if (isFly && (this._axis.x !== 0 || this._axis.y !== 0 || this._axis.z !== 0)) {
80339
+ events.fire('navigateCancel');
80340
+ }
80341
+ if (isFly && wheel[0] !== 0) {
80342
+ events.fire('navigateCancel');
80343
+ }
80344
+ if (isFly && (gamingControls || pan) && (mouse[0] !== 0 || mouse[1] !== 0)) {
80345
+ events.fire('navigateCancel');
80346
+ }
80347
+ if (!isFirstPerson && this._axis.length() > 0) {
80348
+ events.fire('inputEvent', 'requestFirstPerson');
80349
+ }
80350
+ const orbitFactor = isFirstPerson ? cameraComponent.fov / 120 : 1;
80351
+ const { deltas } = frame;
80352
+ // move (WASD + mouse-drag pan + wheel)
80353
+ const v = tmpV1.set(0, 0, 0);
80354
+ keyMove.copy(this._axis);
80355
+ if (isWalk) {
80356
+ // In walk mode normalize only horizontal axes so jump doesn't
80357
+ // reduce horizontal speed.
80358
+ keyMove.y = 0;
80359
+ }
80360
+ keyMove.normalize();
80361
+ const shiftMul = isWalk ? 2 : 4;
80362
+ const ctrlMul = isWalk ? 0.5 : 0.25;
80363
+ const speed = this.moveSpeed * (this._shift ? shiftMul : this._ctrl ? ctrlMul : 1);
80364
+ keyMove.mulScalar(speed);
80365
+ if (isFly) {
80366
+ flyKeyVelocity.copy(keyMove);
80367
+ const damping = flyKeyVelocity.lengthSq() > this._flyKeyVelocity.lengthSq() ?
80368
+ this.flyMoveAccelerationDamping :
80369
+ this.flyMoveDecelerationDamping;
80370
+ this._flyKeyVelocity.lerp(this._flyKeyVelocity, flyKeyVelocity, damp(damping, dt));
80371
+ if (flyKeyVelocity.lengthSq() === 0 && this._flyKeyVelocity.lengthSq() < 1e-4) {
80372
+ this._flyKeyVelocity.set(0, 0, 0);
80373
+ }
80374
+ keyMove.copy(this._flyKeyVelocity);
79421
80375
  }
79422
80376
  else {
79423
- let e = -1;
79424
- let m = mantissa;
79425
- do {
79426
- e++;
79427
- m <<= 1;
79428
- } while ((m & 0x0400) === 0);
79429
- uint32[0] = sign | ((127 - 15 - e) << 23) | ((m & 0x03FF) << 13);
80377
+ this._flyKeyVelocity.set(0, 0, 0);
79430
80378
  }
80379
+ v.add(tmpV2.copy(keyMove).mulScalar((isFirstPerson ? 1 : 0) * dt));
80380
+ if (isWalk) {
80381
+ // Pass jump signal as raw Y; WalkController uses move[1] > 0 as
80382
+ // a boolean trigger.
80383
+ v.y = this._jump > 0 ? 1 : 0;
80384
+ }
80385
+ screenToWorld(cameraComponent, mouse[0], mouse[1], distance, panMove);
80386
+ v.add(panMove.mulScalar(pan));
80387
+ wheelMove.set(0, 0, -wheel[0]);
80388
+ v.add(wheelMove.mulScalar(this.wheelSpeed * DISPLACEMENT_SCALE));
80389
+ deltas.move.append([v.x, v.y, flipZForOrbit(mode, v.z)]);
80390
+ // rotate (mouse-drag, masked when in pan mode)
80391
+ v.set(0, 0, 0);
80392
+ mouseRotate.set(mouse[0], mouse[1], 0);
80393
+ v.add(mouseRotate.mulScalar((1 - pan) * this.orbitSpeed * orbitFactor * this.mouseRotateSensitivity * DISPLACEMENT_SCALE));
80394
+ deltas.rotate.append([v.x, v.y, v.z]);
79431
80395
  }
79432
- else if (exponent === 31) {
79433
- uint32[0] = sign | 0x7F800000 | (mantissa << 13);
79434
- }
79435
- else {
79436
- uint32[0] = sign | ((exponent + 127 - 15) << 23) | (mantissa << 13);
79437
- }
79438
- return float32[0];
79439
- };
79440
- const registerPickerShaderPatches = (app) => {
79441
- const device = app.graphicsDevice;
79442
- const existing = pickerShaderPatchState.get(device);
79443
- if (existing) {
79444
- existing.refCount++;
79445
- return;
79446
- }
79447
- const glslChunks = ShaderChunks.get(device, 'glsl');
79448
- const wgslChunks = ShaderChunks.get(device, 'wgsl');
79449
- const glslPickPS = glslChunks.get('pickPS');
79450
- const glslGsplatPS = glslChunks.get('gsplatPS');
79451
- const wgslPickPS = wgslChunks.get('pickPS');
79452
- const wgslGsplatPS = wgslChunks.get('gsplatPS');
79453
- // Patch strings before mutating ShaderChunks so engine mismatches leave globals untouched.
79454
- const patchedGlslGsplatPS = patchGsplatPickGlsl(glslGsplatPS);
79455
- const patchedWgslGsplatPS = patchGsplatPickWgsl(wgslGsplatPS);
79456
- const state = {
79457
- glslPickPS,
79458
- glslGsplatPS,
79459
- wgslPickPS,
79460
- wgslGsplatPS,
79461
- refCount: 1
80396
+ }
80397
+
80398
+ const tmpV$2 = new Vec3();
80399
+ const orbitMove = new Vec3();
80400
+ const flyMoveTmp = new Vec3();
80401
+ const flyTouchPan = new Vec3();
80402
+ const pinchMoveTmp = new Vec3();
80403
+ const orbitRotate = new Vec3();
80404
+ const flyRotate = new Vec3();
80405
+ class TouchDevice {
80406
+ orbitSpeed = 18;
80407
+ moveSpeed = 4;
80408
+ pinchSpeed = 0.4;
80409
+ touchRotateSensitivity = 1.5;
80410
+ touchPinchMoveSensitivity = 1.5;
80411
+ pinchVelocitySensitivity = 0.006;
80412
+ panVelocitySensitivity = 0.005;
80413
+ _source = new MultiTouchSource();
80414
+ _global = null;
80415
+ /** Touches currently active (running count from .read() deltas). */
80416
+ _touchCount = 0;
80417
+ /** UI joystick value [x, y], -1..1. */
80418
+ _joystick = [0, 0];
80419
+ /** Smoothed forward/back velocity from pinch gesture (-1..1). */
80420
+ _pinchVelocity = 0;
80421
+ /** Smoothed strafe/vertical velocity from two-finger pan, -1..1 each. */
80422
+ _panVelocity = [0, 0];
80423
+ /** Tap-detection state — touch count, max touches, and accumulated movement. */
80424
+ _tapTouches = 0;
80425
+ _tapMaxTouches = 0;
80426
+ _tapDelta = 0;
80427
+ /** True for one frame after a tap is detected during gaming controls. */
80428
+ _tapJump = false;
80429
+ _onJoystickInput = (value) => {
80430
+ this._joystick[0] = value.x;
80431
+ this._joystick[1] = value.y;
79462
80432
  };
79463
- pickerShaderPatchState.set(device, state);
79464
- glslChunks.set('pickPS', pickDepthGlsl);
79465
- wgslChunks.set('pickPS', pickDepthWgsl);
79466
- glslChunks.set('gsplatPS', patchedGlslGsplatPS);
79467
- wgslChunks.set('gsplatPS', patchedWgslGsplatPS);
79468
- };
79469
- const unregisterPickerShaderPatches = (app) => {
79470
- const device = app.graphicsDevice;
79471
- const state = pickerShaderPatchState.get(device);
79472
- if (!state) {
79473
- return;
79474
- }
79475
- state.refCount--;
79476
- if (state.refCount > 0) {
79477
- return;
79478
- }
79479
- const glslChunks = ShaderChunks.get(device, 'glsl');
79480
- const wgslChunks = ShaderChunks.get(device, 'wgsl');
79481
- glslChunks.set('pickPS', state.glslPickPS);
79482
- glslChunks.set('gsplatPS', state.glslGsplatPS);
79483
- wgslChunks.set('pickPS', state.wgslPickPS);
79484
- wgslChunks.set('gsplatPS', state.wgslGsplatPS);
79485
- pickerShaderPatchState.delete(device);
79486
- };
79487
- const getWorldPoint = (camera, x, y, width, height, normalizedDepth) => {
79488
- if (!Number.isFinite(normalizedDepth) || normalizedDepth < 0 || normalizedDepth > 1) {
79489
- return null;
80433
+ get touchCount() {
80434
+ return this._touchCount;
79490
80435
  }
79491
- const cam = camera.camera;
79492
- const far = cam.farClip;
79493
- const near = cam.nearClip;
79494
- const ndcDepth = cam.projection === PROJECTION_ORTHOGRAPHIC ?
79495
- normalizedDepth :
79496
- far * normalizedDepth / (normalizedDepth * (far - near) + near);
79497
- viewProjMat.mul2(cam.projectionMatrix, cam.viewMatrix).invert();
79498
- vec4.set(x / width * 2 - 1, (1 - y / height) * 2 - 1, ndcDepth * 2 - 1, 1);
79499
- viewProjMat.transformVec4(vec4, vec4);
79500
- if (!Number.isFinite(vec4.w) || Math.abs(vec4.w) < 1e-8) {
79501
- return null;
80436
+ attach(canvas, global) {
80437
+ this._global = global;
80438
+ this._source.attach(canvas);
80439
+ global.events.on('joystickInput', this._onJoystickInput);
79502
80440
  }
79503
- vec4.mulScalar(1 / vec4.w);
79504
- if (!Number.isFinite(vec4.x) || !Number.isFinite(vec4.y) || !Number.isFinite(vec4.z)) {
79505
- return null;
80441
+ detach() {
80442
+ // MultiTouchSource doesn't expose a detach.
80443
+ if (this._global) {
80444
+ this._global.events.off('joystickInput', this._onJoystickInput);
80445
+ this._global = null;
80446
+ }
79506
80447
  }
79507
- return new Vec3(vec4.x, vec4.y, vec4.z);
79508
- };
79509
- class Picker {
79510
- pick;
79511
- release;
79512
- constructor(app, camera) {
79513
- const { graphicsDevice } = app;
79514
- let enginePicker;
79515
- let accumBuffer;
79516
- let accumTarget;
79517
- let accumPass;
79518
- let chunksPatched = false;
79519
- const initRasterAccum = (width, height) => {
79520
- accumBuffer = new Texture(graphicsDevice, {
79521
- format: PIXELFORMAT_RGBA16F,
79522
- width,
79523
- height,
79524
- mipmaps: false,
79525
- minFilter: FILTER_NEAREST,
79526
- magFilter: FILTER_NEAREST,
79527
- addressU: ADDRESS_CLAMP_TO_EDGE,
79528
- addressV: ADDRESS_CLAMP_TO_EDGE,
79529
- name: 'picker-accum'
79530
- });
79531
- accumTarget = new RenderTarget({
79532
- colorBuffer: accumBuffer,
79533
- depth: false // not needed — gaussians are rendered back to front
79534
- });
79535
- accumPass = new RenderPassPicker(graphicsDevice, app.renderer);
79536
- // RGB: additive depth accumulation. Alpha: multiplicative transmittance.
79537
- accumPass.blendState = new BlendState(true, BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ONE_MINUS_SRC_ALPHA, BLENDEQUATION_ADD, BLENDMODE_ZERO, BLENDMODE_ONE_MINUS_SRC_ALPHA);
79538
- };
79539
- const readTexture = (texture, x, y, target) => {
79540
- const texY = graphicsDevice.isWebGL2 ? target.height - y - 1 : y;
79541
- return texture.read(x, texY, 1, 1, {
79542
- renderTarget: target,
79543
- immediate: true
79544
- });
79545
- };
79546
- this.pick = async (x, y) => {
79547
- const width = Math.floor(graphicsDevice.width);
79548
- const height = Math.floor(graphicsDevice.height);
79549
- // bail out if the device hasn't been sized yet
79550
- if (width <= 0 || height <= 0) {
79551
- return null;
80448
+ update(ctx, frame) {
80449
+ const { touch, pinch, count } = this._source.read();
80450
+ const { isFly, isWalk, isFirstPerson, isOrbit, gamingControls, dt, distance, cameraComponent } = ctx;
80451
+ // running touch count
80452
+ this._touchCount += count[0];
80453
+ if (isFly && gamingControls && (this._joystick[0] !== 0 || this._joystick[1] !== 0)) {
80454
+ this._global.events.fire('navigateCancel');
80455
+ }
80456
+ // tap detection for click/tap target and focus modes
80457
+ if (isWalk || isFly || isOrbit) {
80458
+ const prevTaps = this._tapTouches;
80459
+ this._tapTouches = Math.max(0, this._tapTouches + count[0]);
80460
+ if (prevTaps === 0 && this._tapTouches > 0) {
80461
+ this._tapDelta = 0;
79552
80462
  }
79553
- const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
79554
- const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
79555
- const worldLayer = app.scene.layers.getLayerByName('World');
79556
- if (!worldLayer) {
79557
- return null;
80463
+ if (this._tapTouches > 0) {
80464
+ this._tapMaxTouches = Math.max(this._tapMaxTouches, this._tapTouches);
79558
80465
  }
79559
- // enable gsplat IDs only for the duration of the pick so we don't pay the
79560
- // memory/perf cost between picks (picker instances are typically long-lived).
79561
- const prevEnableIds = app.scene.gsplat.enableIds;
79562
- app.scene.gsplat.enableIds = true;
79563
- try {
79564
- if (app.scene.gsplat.currentRenderer === GSPLAT_RENDERER_COMPUTE) {
79565
- enginePicker ??= new Picker$1(app, 1, 1, true);
79566
- enginePicker.resize(width, height);
79567
- enginePicker.prepare(camera.camera, app.scene, [worldLayer]);
79568
- return await enginePicker.getWorldPointAsync(screenX, screenY);
79569
- }
79570
- if (!chunksPatched) {
79571
- registerPickerShaderPatches(app);
79572
- chunksPatched = true;
79573
- }
79574
- if (!accumPass) {
79575
- initRasterAccum(width, height);
79576
- }
79577
- else {
79578
- accumTarget.resize(width, height);
79579
- }
79580
- accumPass.init(accumTarget);
79581
- accumPass.setClearColor(clearColor);
79582
- accumPass.update(camera.camera, app.scene, [worldLayer], new Map(), false);
79583
- accumPass.render();
79584
- const pixels = await readTexture(accumBuffer, screenX, screenY, accumTarget);
79585
- const r = half2Float(pixels[0]);
79586
- const transmittance = half2Float(pixels[3]);
79587
- const alpha = 1 - transmittance;
79588
- if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
79589
- return null;
80466
+ if (this._tapTouches > 0) {
80467
+ const prevDelta = this._tapDelta;
80468
+ this._tapDelta += Math.abs(touch[0]) + Math.abs(touch[1]) + Math.abs(pinch[0]);
80469
+ if (prevDelta < TAP_EPSILON && this._tapDelta >= TAP_EPSILON) {
80470
+ if ((isWalk && !gamingControls) || isFly) {
80471
+ this._global.events.fire('navigateCancel');
80472
+ }
79590
80473
  }
79591
- const normalizedDepth = r / alpha;
79592
- return getWorldPoint(camera, screenX, screenY, width, height, normalizedDepth);
79593
- }
79594
- finally {
79595
- // Pick is only invoked from user dblclick events, so concurrent invocations
79596
- // (which would race on enableIds) aren't a concern in practice.
79597
- // eslint-disable-next-line require-atomic-updates
79598
- app.scene.gsplat.enableIds = prevEnableIds;
79599
80474
  }
79600
- };
79601
- this.release = () => {
79602
- if (chunksPatched) {
79603
- unregisterPickerShaderPatches(app);
79604
- chunksPatched = false;
79605
- }
79606
- enginePicker?.destroy();
79607
- accumPass?.destroy();
79608
- accumTarget?.destroy();
79609
- accumBuffer?.destroy();
79610
- };
79611
- }
79612
- }
79613
-
79614
- /**
79615
- * Displacement-based inputs (mouse, touch, wheel, pinch) return accumulated
79616
- * pixel offsets that already scale with frame time. This factor converts
79617
- * rate-based speed constants (tuned for degrees-per-second) to work with
79618
- * per-frame displacements, making them frame-rate-independent.
79619
- */
79620
- const DISPLACEMENT_SCALE = 1 / 60;
79621
- /** Maximum accumulated touch movement (px) to still count as a tap. */
79622
- const TAP_EPSILON = 15;
79623
- const tmpHalfSize = new Vec3();
79624
- /**
79625
- * Converts screen-space pixel deltas to a world-space pan vector at the
79626
- * given depth.
79627
- *
79628
- * @param camera - The camera component.
79629
- * @param dx - Horizontal pixel delta.
79630
- * @param dy - Vertical pixel delta.
79631
- * @param dz - Depth (world-space) at which to project the delta.
79632
- * @param out - Optional output vector.
79633
- * @returns The pan vector in world space.
79634
- */
79635
- const screenToWorld = (camera, dx, dy, dz, out = new Vec3()) => {
79636
- const { system, fov, aspectRatio, horizontalFov, projection, orthoHeight } = camera;
79637
- const { width, height } = system.app.graphicsDevice.clientRect;
79638
- out.set(-(dx / width) * 2, (dy / height) * 2, 0);
79639
- const halfSize = tmpHalfSize.set(0, 0, 0);
79640
- if (projection === PROJECTION_PERSPECTIVE) {
79641
- const halfSlice = dz * Math.tan(0.5 * fov * math.DEG_TO_RAD);
79642
- if (horizontalFov) {
79643
- halfSize.set(halfSlice, halfSlice / aspectRatio, 0);
79644
- }
79645
- else {
79646
- halfSize.set(halfSlice * aspectRatio, halfSlice, 0);
79647
- }
79648
- }
79649
- else {
79650
- halfSize.set(orthoHeight * aspectRatio, orthoHeight, 0);
79651
- }
79652
- out.mul(halfSize);
79653
- return out;
79654
- };
79655
- /**
79656
- * The orbit camera and the fly camera disagree on the sign of the z-axis
79657
- * for forward motion. Apply this when emitting a forward/back z-component
79658
- * so the same wheel-style delta drives both cameras correctly.
79659
- *
79660
- * @param mode - The current camera mode.
79661
- * @param z - The raw forward/back z-component.
79662
- * @returns The z-component flipped for orbit mode, unchanged otherwise.
79663
- */
79664
- const flipZForOrbit = (mode, z) => (mode === 'orbit' ? -z : z);
79665
-
79666
- const tmpV$4 = new Vec3();
79667
- /**
79668
- * Click-to-walk (desktop), tap-to-walk (mobile), and double-click-to-pick
79669
- * (orbit / fly) interaction. Uses a Picker against the collision mesh to
79670
- * resolve the world-space target and fires `walkTo` / `pick` for the
79671
- * camera manager to consume.
79672
- */
79673
- class WalkInteraction {
79674
- collision = null;
79675
- _global = null;
79676
- _canvas = null;
79677
- _picker = null;
79678
- _lastPointerOffsetX = 0;
79679
- _lastPointerOffsetY = 0;
79680
- _mouseClickTracking = false;
79681
- _mouseClickDelta = 0;
79682
- _lastTap = { time: 0, x: 0, y: 0 };
79683
- _updateCursor = () => {
79684
- const global = this._global;
79685
- const canvas = this._canvas;
79686
- if (!global || !canvas)
79687
- return;
79688
- const { state } = global;
79689
- if (state.cameraMode === 'walk' && !state.gamingControls && state.inputMode === 'desktop') {
79690
- canvas.style.cursor = this._mouseClickTracking ? 'default' : 'pointer';
79691
- }
79692
- else {
79693
- canvas.style.cursor = '';
79694
- }
79695
- };
79696
- _pickCollision(offsetX, offsetY) {
79697
- if (!this.collision || !this._global)
79698
- return null;
79699
- const camera = this._global.camera;
79700
- const cameraPos = camera.getPosition();
79701
- camera.camera.screenToWorld(offsetX, offsetY, 1.0, tmpV$4);
79702
- tmpV$4.sub(cameraPos).normalize();
79703
- const hit = this.collision.queryRay(cameraPos.x, cameraPos.y, cameraPos.z, tmpV$4.x, tmpV$4.y, tmpV$4.z, camera.camera.farClip);
79704
- if (!hit)
79705
- return null;
79706
- const sn = this.collision.querySurfaceNormal(hit.x, hit.y, hit.z, tmpV$4.x, tmpV$4.y, tmpV$4.z);
79707
- return {
79708
- position: new Vec3(hit.x, hit.y, hit.z),
79709
- normal: new Vec3(sn.nx, sn.ny, sn.nz)
79710
- };
79711
- }
79712
- _onPointerDown = (event) => {
79713
- const global = this._global;
79714
- if (!global)
79715
- return;
79716
- const { events } = global;
79717
- // record offsets for click/tap-to-walk picking
79718
- this._lastPointerOffsetX = event.offsetX;
79719
- this._lastPointerOffsetY = event.offsetY;
79720
- // start desktop click-to-walk tracking
79721
- if (event.pointerType !== 'touch' && event.button === 0) {
79722
- this._mouseClickTracking = true;
79723
- this._mouseClickDelta = 0;
79724
- this._updateCursor();
79725
- }
79726
- // manual double-tap detection (iOS doesn't send dblclick)
79727
- const now = Date.now();
79728
- const delay = Math.max(0, now - this._lastTap.time);
79729
- if (delay < 300 &&
79730
- Math.abs(event.clientX - this._lastTap.x) < 8 &&
79731
- Math.abs(event.clientY - this._lastTap.y) < 8) {
79732
- events.fire('inputEvent', 'dblclick', event);
79733
- this._lastTap.time = 0;
79734
- }
79735
- else {
79736
- this._lastTap.time = now;
79737
- this._lastTap.x = event.clientX;
79738
- this._lastTap.y = event.clientY;
79739
- }
79740
- };
79741
- _onPointerMove = (event) => {
79742
- const global = this._global;
79743
- if (!global)
79744
- return;
79745
- const { state, events } = global;
79746
- if (this._mouseClickTracking && event.pointerType !== 'touch') {
79747
- const prev = this._mouseClickDelta;
79748
- this._mouseClickDelta += Math.abs(event.movementX) + Math.abs(event.movementY);
79749
- if (prev < TAP_EPSILON && this._mouseClickDelta >= TAP_EPSILON) {
79750
- if (state.cameraMode === 'walk' && !state.gamingControls) {
79751
- events.fire('walkCancel');
79752
- }
79753
- }
79754
- }
79755
- };
79756
- _onPointerUp = (event) => {
79757
- const global = this._global;
79758
- if (!global)
79759
- return;
79760
- const { state, events } = global;
79761
- if (this._mouseClickTracking && event.pointerType !== 'touch' && event.button === 0) {
79762
- this._mouseClickTracking = false;
79763
- this._updateCursor();
79764
- if (this._mouseClickDelta < TAP_EPSILON && state.cameraMode === 'walk' && !state.gamingControls) {
79765
- const result = this._pickCollision(this._lastPointerOffsetX, this._lastPointerOffsetY);
79766
- if (result) {
79767
- events.fire('walkTo', result.position, result.normal);
79768
- }
79769
- }
79770
- }
79771
- };
79772
- _onInputEvent = async (eventName, event) => {
79773
- const global = this._global;
79774
- const canvas = this._canvas;
79775
- if (!global || !canvas)
79776
- return;
79777
- if (eventName !== 'dblclick')
79778
- return;
79779
- if (!(event instanceof MouseEvent))
79780
- return;
79781
- const { app, camera, events, state } = global;
79782
- if (state.cameraMode === 'walk')
79783
- return;
79784
- if (!this._picker) {
79785
- this._picker = new Picker(app, camera);
79786
- }
79787
- const result = await this._picker.pick(event.offsetX / canvas.clientWidth, event.offsetY / canvas.clientHeight);
79788
- if (result) {
79789
- events.fire('pick', result);
79790
- }
79791
- };
79792
- _onMobileTap = () => {
79793
- const global = this._global;
79794
- if (!global)
79795
- return;
79796
- const { state, events } = global;
79797
- if (state.cameraMode !== 'walk' || state.gamingControls)
79798
- return;
79799
- const result = this._pickCollision(this._lastPointerOffsetX, this._lastPointerOffsetY);
79800
- if (result) {
79801
- events.fire('walkTo', result.position, result.normal);
79802
- }
79803
- };
79804
- attach(canvas, global) {
79805
- this._canvas = canvas;
79806
- this._global = global;
79807
- const { events } = global;
79808
- canvas.addEventListener('pointerdown', this._onPointerDown);
79809
- canvas.addEventListener('pointermove', this._onPointerMove);
79810
- canvas.addEventListener('pointerup', this._onPointerUp);
79811
- // double-click → pick → fire 'pick' event (skipped in walk mode)
79812
- events.on('inputEvent', this._onInputEvent);
79813
- // mobile tap (no movement) → walkTo
79814
- events.on('mobileTap', this._onMobileTap);
79815
- // refresh cursor on mode / gaming-controls change
79816
- events.on('cameraMode:changed', this._updateCursor);
79817
- events.on('gamingControls:changed', this._updateCursor);
79818
- }
79819
- detach() {
79820
- if (this._canvas) {
79821
- this._canvas.removeEventListener('pointerdown', this._onPointerDown);
79822
- this._canvas.removeEventListener('pointermove', this._onPointerMove);
79823
- this._canvas.removeEventListener('pointerup', this._onPointerUp);
79824
- }
79825
- if (this._global) {
79826
- const { events } = this._global;
79827
- events.off('inputEvent', this._onInputEvent);
79828
- events.off('mobileTap', this._onMobileTap);
79829
- events.off('cameraMode:changed', this._updateCursor);
79830
- events.off('gamingControls:changed', this._updateCursor);
79831
- }
79832
- this._canvas = null;
79833
- this._global = null;
79834
- this._picker = null;
79835
- }
79836
- }
79837
-
79838
- const tmpV$3 = new Vec3();
79839
- const stickMove = new Vec3();
79840
- const stickRotate = new Vec3();
79841
- class GamepadDevice {
79842
- moveSpeed = 4;
79843
- orbitSpeed = 18;
79844
- gamepadRotateSensitivity = 1.0;
79845
- _source = new GamepadSource();
79846
- attach(_canvas, _global) {
79847
- // GamepadSource polls navigator.getGamepads() — no DOM attach needed.
79848
- }
79849
- detach() { }
79850
- update(ctx, frame) {
79851
- const { dt, cameraComponent, isFirstPerson } = ctx;
79852
- const { leftStick, rightStick } = this._source.read();
79853
- const orbitFactor = isFirstPerson ? cameraComponent.fov / 120 : 1;
79854
- const { deltas } = frame;
79855
- const v = tmpV$3.set(0, 0, 0);
79856
- stickMove.set(leftStick[0], 0, -leftStick[1]);
79857
- v.add(stickMove.mulScalar(this.moveSpeed * dt));
79858
- deltas.move.append([v.x, v.y, v.z]);
79859
- v.set(0, 0, 0);
79860
- stickRotate.set(rightStick[0], rightStick[1], 0);
79861
- v.add(stickRotate.mulScalar(this.orbitSpeed * orbitFactor * this.gamepadRotateSensitivity * dt));
79862
- deltas.rotate.append([v.x, v.y, v.z]);
79863
- }
79864
- }
79865
-
79866
- const tmpV1 = new Vec3();
79867
- const keyMove = new Vec3();
79868
- const panMove = new Vec3();
79869
- const mouseRotate = new Vec3();
79870
- const wheelMove = new Vec3();
79871
- // Patch keydown / keyup so meta-key combinations don't leave keys stuck on
79872
- // macOS (the OS swallows keyup for any key released while Cmd is held).
79873
- const patchKeyboardMeta = (desktopInput) => {
79874
- const origOnKeyDown = desktopInput._onKeyDown;
79875
- desktopInput._onKeyDown = (event) => {
79876
- if (event.key === 'Meta') {
79877
- desktopInput._keyNow.fill(0);
79878
- }
79879
- else if (!event.metaKey) {
79880
- origOnKeyDown(event);
79881
- }
79882
- };
79883
- const origOnKeyUp = desktopInput._onKeyUp;
79884
- desktopInput._onKeyUp = (event) => {
79885
- if (event.key === 'Meta') {
79886
- desktopInput._keyNow.fill(0);
79887
- }
79888
- else if (!event.metaKey) {
79889
- origOnKeyUp(event);
79890
- }
79891
- };
79892
- };
79893
- class KeyboardMouseDevice {
79894
- moveSpeed = 4;
79895
- orbitSpeed = 18;
79896
- wheelSpeed = 0.06;
79897
- mouseRotateSensitivity = 0.5;
79898
- _source = new KeyboardMouseSource();
79899
- _global = null;
79900
- /** Running WASD/QE/arrow direction (sum of key states). */
79901
- _axis = new Vec3();
79902
- /** Running button-held state per index: [LMB, MMB, RMB]. */
79903
- _buttons = [0, 0, 0];
79904
- _shift = 0;
79905
- _ctrl = 0;
79906
- _jump = 0;
79907
- /**
79908
- * Get the underlying source so other code (PointerLockManager) can
79909
- * toggle its private pointer-lock flag, which gates how it consumes
79910
- * mouse-delta events.
79911
- *
79912
- * @returns The PlayCanvas KeyboardMouseSource backing this device.
79913
- */
79914
- get source() {
79915
- return this._source;
79916
- }
79917
- attach(canvas, global) {
79918
- this._global = global;
79919
- patchKeyboardMeta(this._source);
79920
- this._source.attach(canvas);
79921
- }
79922
- detach() {
79923
- // KeyboardMouseSource does not expose a detach; nothing to undo for
79924
- // its DOM listeners here.
79925
- }
79926
- update(ctx, frame) {
79927
- const { keyCode } = KeyboardMouseSource;
79928
- const { key, button, mouse, wheel } = this._source.read();
79929
- const { events } = this._global;
79930
- // accumulate running input state
79931
- this._axis.add(tmpV1.set((key[keyCode.D] - key[keyCode.A]) + (key[keyCode.RIGHT] - key[keyCode.LEFT]), (key[keyCode.E] - key[keyCode.Q]), (key[keyCode.W] - key[keyCode.S]) + (key[keyCode.UP] - key[keyCode.DOWN])));
79932
- this._jump += key[keyCode.SPACE];
79933
- this._shift += key[keyCode.SHIFT];
79934
- this._ctrl += key[keyCode.CTRL];
79935
- const n = Math.min(button.length, this._buttons.length);
79936
- for (let i = 0; i < n; i++) {
79937
- this._buttons[i] += button[i];
79938
- }
79939
- const { isWalk, isFirstPerson, dt, distance, cameraComponent, mode, touchCount } = ctx;
79940
- // walk-cancel and requestFirstPerson events (driven by WASD axis)
79941
- if (isWalk && (this._axis.x !== 0 || this._axis.z !== 0)) {
79942
- events.fire('walkCancel');
79943
- }
79944
- if (!isFirstPerson && this._axis.length() > 0) {
79945
- events.fire('inputEvent', 'requestFirstPerson');
79946
- }
79947
- // pan flag: RMB held, RMB just released this frame, or 2+ touches active
79948
- const pan = this._buttons[2] || +(button[2] === -1) || +(touchCount > 1);
79949
- const orbitFactor = isFirstPerson ? cameraComponent.fov / 120 : 1;
79950
- const { deltas } = frame;
79951
- // move (WASD + mouse-drag pan + wheel)
79952
- const v = tmpV1.set(0, 0, 0);
79953
- keyMove.copy(this._axis);
79954
- if (isWalk) {
79955
- // In walk mode normalize only horizontal axes so jump doesn't
79956
- // reduce horizontal speed.
79957
- keyMove.y = 0;
79958
- }
79959
- keyMove.normalize();
79960
- const shiftMul = isWalk ? 2 : 4;
79961
- const ctrlMul = isWalk ? 0.5 : 0.25;
79962
- const speed = this.moveSpeed * (this._shift ? shiftMul : this._ctrl ? ctrlMul : 1);
79963
- v.add(keyMove.mulScalar((isFirstPerson ? 1 : 0) * speed * dt));
79964
- if (isWalk) {
79965
- // Pass jump signal as raw Y; WalkController uses move[1] > 0 as
79966
- // a boolean trigger.
79967
- v.y = this._jump > 0 ? 1 : 0;
79968
- }
79969
- screenToWorld(cameraComponent, mouse[0], mouse[1], distance, panMove);
79970
- v.add(panMove.mulScalar(pan));
79971
- wheelMove.set(0, 0, -wheel[0]);
79972
- v.add(wheelMove.mulScalar(this.wheelSpeed * DISPLACEMENT_SCALE));
79973
- deltas.move.append([v.x, v.y, flipZForOrbit(mode, v.z)]);
79974
- // rotate (mouse-drag, masked when in pan mode)
79975
- v.set(0, 0, 0);
79976
- mouseRotate.set(mouse[0], mouse[1], 0);
79977
- v.add(mouseRotate.mulScalar((1 - pan) * this.orbitSpeed * orbitFactor * this.mouseRotateSensitivity * DISPLACEMENT_SCALE));
79978
- deltas.rotate.append([v.x, v.y, v.z]);
79979
- }
79980
- }
79981
-
79982
- const tmpV$2 = new Vec3();
79983
- const orbitMove = new Vec3();
79984
- const flyMoveTmp = new Vec3();
79985
- const flyTouchPan = new Vec3();
79986
- const pinchMoveTmp = new Vec3();
79987
- const orbitRotate = new Vec3();
79988
- const flyRotate = new Vec3();
79989
- class TouchDevice {
79990
- orbitSpeed = 18;
79991
- moveSpeed = 4;
79992
- pinchSpeed = 0.4;
79993
- touchRotateSensitivity = 1.5;
79994
- touchPinchMoveSensitivity = 1.5;
79995
- pinchVelocitySensitivity = 0.006;
79996
- panVelocitySensitivity = 0.005;
79997
- _source = new MultiTouchSource();
79998
- _global = null;
79999
- /** Touches currently active (running count from .read() deltas). */
80000
- _touchCount = 0;
80001
- /** UI joystick value [x, y], -1..1. */
80002
- _joystick = [0, 0];
80003
- /** Smoothed forward/back velocity from pinch gesture (-1..1). */
80004
- _pinchVelocity = 0;
80005
- /** Smoothed strafe/vertical velocity from two-finger pan, -1..1 each. */
80006
- _panVelocity = [0, 0];
80007
- /** Tap-detection state — touch count and accumulated finger movement. */
80008
- _tapTouches = 0;
80009
- _tapDelta = 0;
80010
- /** True for one frame after a tap is detected during gaming controls. */
80011
- _tapJump = false;
80012
- _onJoystickInput = (value) => {
80013
- this._joystick[0] = value.x;
80014
- this._joystick[1] = value.y;
80015
- };
80016
- get touchCount() {
80017
- return this._touchCount;
80018
- }
80019
- attach(canvas, global) {
80020
- this._global = global;
80021
- this._source.attach(canvas);
80022
- global.events.on('joystickInput', this._onJoystickInput);
80023
- }
80024
- detach() {
80025
- // MultiTouchSource doesn't expose a detach.
80026
- if (this._global) {
80027
- this._global.events.off('joystickInput', this._onJoystickInput);
80028
- this._global = null;
80029
- }
80030
- }
80031
- update(ctx, frame) {
80032
- const { touch, pinch, count } = this._source.read();
80033
- const { isWalk, isFirstPerson, isOrbit, gamingControls, dt, distance, cameraComponent } = ctx;
80034
- // running touch count
80035
- this._touchCount += count[0];
80036
- // tap detection (walk mode only)
80037
- if (isWalk) {
80038
- const prevTaps = this._tapTouches;
80039
- this._tapTouches = Math.max(0, this._tapTouches + count[0]);
80040
- if (prevTaps === 0 && this._tapTouches > 0) {
80041
- this._tapDelta = 0;
80042
- }
80043
- if (this._tapTouches > 0) {
80044
- const prevDelta = this._tapDelta;
80045
- this._tapDelta += Math.abs(touch[0]) + Math.abs(touch[1]);
80046
- if (prevDelta < TAP_EPSILON && this._tapDelta >= TAP_EPSILON) {
80047
- if (!gamingControls) {
80048
- this._global.events.fire('walkCancel');
80049
- }
80050
- }
80051
- }
80052
- if (prevTaps > 0 && this._tapTouches === 0) {
80053
- if (this._tapDelta < TAP_EPSILON) {
80054
- if (!gamingControls) {
80055
- // Walk-interaction listens for this and fires walkTo
80056
- // after picking.
80057
- this._global.events.fire('mobileTap');
80058
- }
80059
- else {
80060
- this._tapJump = true;
80061
- }
80062
- }
80475
+ if (prevTaps > 0 && this._tapTouches === 0) {
80476
+ if (this._tapDelta < TAP_EPSILON && this._tapMaxTouches === 1) {
80477
+ if (isWalk && !gamingControls) {
80478
+ // Walk-interaction listens for this and fires navigateTo
80479
+ // after picking.
80480
+ this._global.events.fire('mobileTap');
80481
+ }
80482
+ else if (isWalk) {
80483
+ this._tapJump = true;
80484
+ }
80485
+ else if (isFly && !gamingControls) {
80486
+ // Walk-interaction listens for this and fires navigateTo
80487
+ // after picking.
80488
+ this._global.events.fire('mobileTap');
80489
+ }
80490
+ else if (isOrbit) {
80491
+ // Walk-interaction listens for this and sets orbit focus
80492
+ // after picking.
80493
+ this._global.events.fire('mobileTap');
80494
+ }
80495
+ }
80496
+ this._tapMaxTouches = 0;
80063
80497
  }
80064
80498
  }
80065
80499
  else {
80066
80500
  this._tapTouches = 0;
80501
+ this._tapMaxTouches = 0;
80067
80502
  }
80068
80503
  // smoothed velocities for fly/walk first-person motion (non-gaming)
80069
80504
  if (isFirstPerson && !gamingControls && this._touchCount > 1) {
@@ -80232,6 +80667,9 @@ class TrackpadDevice {
80232
80667
  }
80233
80668
  else {
80234
80669
  // fly / walk: always rotate (shift is a speed modifier, not a gesture)
80670
+ if (mode === 'fly') {
80671
+ this._global.events.fire('navigateCancel');
80672
+ }
80235
80673
  this._orbit[0] += deltaX;
80236
80674
  this._orbit[1] += deltaY;
80237
80675
  }
@@ -80293,7 +80731,7 @@ class TrackpadDevice {
80293
80731
 
80294
80732
  /**
80295
80733
  * Coordinator that wires together input devices (keyboard-mouse, touch,
80296
- * trackpad, gamepad) and app-level UX helpers (mode shortcuts, walk
80734
+ * trackpad, gamepad) and app-level UX helpers (mode shortcuts, nav
80297
80735
  * interaction, pointer lock, input-mode tracker), and exposes the
80298
80736
  * resulting per-frame `InputFrame` for the camera manager to consume.
80299
80737
  */
@@ -80307,18 +80745,19 @@ class InputController {
80307
80745
  _keyboardMouse = new KeyboardMouseDevice();
80308
80746
  _touch = new TouchDevice();
80309
80747
  _gamepad = new GamepadDevice();
80310
- _walkInteraction = new WalkInteraction();
80748
+ _navInteraction;
80311
80749
  _pointerLock = new PointerLockManager();
80312
80750
  _modeShortcuts = new ModeShortcuts();
80313
80751
  _inputModeTracker = new InputModeTracker();
80314
80752
  set collision(value) {
80315
- this._walkInteraction.collision = value;
80753
+ this._navInteraction.collision = value;
80316
80754
  }
80317
80755
  get collision() {
80318
- return this._walkInteraction.collision;
80756
+ return this._navInteraction.collision;
80319
80757
  }
80320
- constructor(global) {
80758
+ constructor(global, picker) {
80321
80759
  this._global = global;
80760
+ this._navInteraction = new NavInteraction(picker);
80322
80761
  const { app, events } = global;
80323
80762
  const canvas = app.graphicsDevice.canvas;
80324
80763
  // Trackpad MUST attach before KeyboardMouseDevice so its wheel
@@ -80328,7 +80767,7 @@ class InputController {
80328
80767
  this._keyboardMouse.attach(canvas, global);
80329
80768
  this._touch.attach(canvas, global);
80330
80769
  this._gamepad.attach(canvas, global);
80331
- this._walkInteraction.attach(canvas, global);
80770
+ this._navInteraction.attach(canvas, global);
80332
80771
  this._pointerLock.attach(canvas, global, this._keyboardMouse);
80333
80772
  this._modeShortcuts.attach(global, this._pointerLock);
80334
80773
  this._inputModeTracker.attach(global);
@@ -80436,211 +80875,1258 @@ const encodeFlatColors = (tris, cameraFrameEnabled, out) => {
80436
80875
  gray = grayY;
80437
80876
  }
80438
80877
  else {
80439
- gray = grayZ;
80878
+ gray = grayZ;
80879
+ }
80880
+ const oc = i * 12;
80881
+ for (let j = 0; j < 3; j++) {
80882
+ const k = oc + j * 4;
80883
+ colors[k] = gray;
80884
+ colors[k + 1] = gray;
80885
+ colors[k + 2] = gray;
80886
+ colors[k + 3] = alpha;
80887
+ }
80888
+ }
80889
+ return colors;
80890
+ };
80891
+ const buildFlatMesh = (tris, cameraFrameEnabled) => {
80892
+ const numTris = tris.count;
80893
+ const flatPositions = new Float32Array(numTris * 9);
80894
+ const flatColors = encodeFlatColors(tris, cameraFrameEnabled);
80895
+ const flatIndices = new Uint32Array(numTris * 3);
80896
+ for (let i = 0; i < numTris; i++) {
80897
+ const op = i * 9;
80898
+ flatPositions[op] = tris.v0x[i];
80899
+ flatPositions[op + 1] = tris.v0y[i];
80900
+ flatPositions[op + 2] = tris.v0z[i];
80901
+ flatPositions[op + 3] = tris.v1x[i];
80902
+ flatPositions[op + 4] = tris.v1y[i];
80903
+ flatPositions[op + 5] = tris.v1z[i];
80904
+ flatPositions[op + 6] = tris.v2x[i];
80905
+ flatPositions[op + 7] = tris.v2y[i];
80906
+ flatPositions[op + 8] = tris.v2z[i];
80907
+ const oi = i * 3;
80908
+ flatIndices[oi] = oi;
80909
+ flatIndices[oi + 1] = oi + 1;
80910
+ flatIndices[oi + 2] = oi + 2;
80911
+ }
80912
+ return { flatPositions, flatColors, flatIndices };
80913
+ };
80914
+ // Configures a StandardMaterial that emits the per-vertex color directly. The
80915
+ // depth pre-pass and the color pass use the same configuration (so they
80916
+ // compile to identical shaders and produce bit-identical depth values for
80917
+ // FUNC_EQUAL); only their write masks and depth state differ.
80918
+ const makeSurfaceMaterial = () => {
80919
+ const m = new StandardMaterial();
80920
+ m.useLighting = false;
80921
+ m.useSkybox = false;
80922
+ m.useFog = false;
80923
+ m.useTonemap = false;
80924
+ m.ambient = new Color(0, 0, 0);
80925
+ m.diffuse = new Color(0, 0, 0);
80926
+ m.specular = new Color(0, 0, 0);
80927
+ m.emissive = new Color(1, 1, 1);
80928
+ m.emissiveVertexColor = true;
80929
+ m.emissiveVertexColorChannel = 'rgb';
80930
+ m.opacityVertexColor = true;
80931
+ m.opacityVertexColorChannel = 'a';
80932
+ m.opacity = 1;
80933
+ return m;
80934
+ };
80935
+ class MeshDebugOverlay {
80936
+ app;
80937
+ camera;
80938
+ layer;
80939
+ entity;
80940
+ mesh;
80941
+ triangles;
80942
+ flatColors;
80943
+ materials;
80944
+ _enabled = false;
80945
+ constructor(app, collision, camera, cameraFrameEnabled) {
80946
+ this.app = app;
80947
+ this.camera = camera;
80948
+ this.triangles = collision.triangles;
80949
+ const device = app.graphicsDevice;
80950
+ const { flatPositions, flatColors, flatIndices } = buildFlatMesh(this.triangles, cameraFrameEnabled);
80951
+ this.flatColors = flatColors;
80952
+ const mesh = new Mesh(device);
80953
+ mesh.setPositions(flatPositions);
80954
+ mesh.setColors32(flatColors);
80955
+ mesh.setIndices(flatIndices);
80956
+ mesh.update(PRIMITIVE_TRIANGLES);
80957
+ mesh.generateWireframe();
80958
+ this.mesh = mesh;
80959
+ this.layer = new Layer({
80960
+ name: 'CollisionOverlay',
80961
+ enabled: false,
80962
+ clearColorBuffer: false,
80963
+ clearDepthBuffer: true,
80964
+ opaqueSortMode: SORTMODE_MANUAL,
80965
+ transparentSortMode: SORTMODE_MANUAL
80966
+ });
80967
+ app.scene.layers.push(this.layer);
80968
+ camera.camera.layers = [...camera.camera.layers, this.layer.id];
80969
+ // Pass 1: depth pre-pass. Color writes masked off so only depth lands
80970
+ // in the buffer. Both this and pass 2 use the same depthBias /
80971
+ // slopeDepthBias so they write/test identical depth values
80972
+ // (FUNC_EQUAL relies on this) while still sitting slightly behind the
80973
+ // wireframe lines so pass 3's FUNC_LESSEQUAL passes reliably without
80974
+ // z-fighting.
80975
+ const depthMaterial = makeSurfaceMaterial();
80976
+ depthMaterial.cull = CULLFACE_BACK;
80977
+ depthMaterial.blendType = BLEND_NORMAL;
80978
+ depthMaterial.depthTest = true;
80979
+ depthMaterial.depthWrite = true;
80980
+ depthMaterial.depthBias = 1;
80981
+ depthMaterial.slopeDepthBias = 1;
80982
+ depthMaterial.redWrite = false;
80983
+ depthMaterial.greenWrite = false;
80984
+ depthMaterial.blueWrite = false;
80985
+ depthMaterial.alphaWrite = false;
80986
+ depthMaterial.update();
80987
+ const depthInstance = new MeshInstance(mesh, depthMaterial);
80988
+ depthInstance.drawOrder = 0;
80989
+ const depthEntity = new Entity('CollisionDepthPrepass');
80990
+ depthEntity.addComponent('render', {
80991
+ meshInstances: [depthInstance],
80992
+ layers: [this.layer.id]
80993
+ });
80994
+ // Pass 2: surface color, depth EQUAL. Only the front-most fragment
80995
+ // from pass 1 survives, so a single layer of vertex color blends onto
80996
+ // the camera target.
80997
+ const surfaceMaterial = makeSurfaceMaterial();
80998
+ surfaceMaterial.cull = CULLFACE_BACK;
80999
+ surfaceMaterial.blendType = BLEND_NORMAL;
81000
+ surfaceMaterial.depthTest = true;
81001
+ surfaceMaterial.depthFunc = FUNC_EQUAL;
81002
+ surfaceMaterial.depthWrite = false;
81003
+ surfaceMaterial.depthBias = 1;
81004
+ surfaceMaterial.slopeDepthBias = 1;
81005
+ surfaceMaterial.update();
81006
+ const surfaceInstance = new MeshInstance(mesh, surfaceMaterial);
81007
+ surfaceInstance.drawOrder = 1;
81008
+ const surfaceEntity = new Entity('CollisionSurface');
81009
+ surfaceEntity.addComponent('render', {
81010
+ meshInstances: [surfaceInstance],
81011
+ layers: [this.layer.id]
81012
+ });
81013
+ // Pass 3: wireframe — black lines depth-tested against the surface so
81014
+ // back-facing edges are hidden. BLEND_NORMAL with opacity = 1 looks
81015
+ // opaque but routes through the same transparent render action as the
81016
+ // other two passes, keeping all three under one depth clear.
81017
+ const wireframeMaterial = new StandardMaterial();
81018
+ wireframeMaterial.useLighting = false;
81019
+ wireframeMaterial.useSkybox = false;
81020
+ wireframeMaterial.useFog = false;
81021
+ wireframeMaterial.useTonemap = false;
81022
+ wireframeMaterial.ambient = new Color(0, 0, 0);
81023
+ wireframeMaterial.diffuse = new Color(0, 0, 0);
81024
+ wireframeMaterial.specular = new Color(0, 0, 0);
81025
+ wireframeMaterial.emissive = new Color(0, 0, 0);
81026
+ wireframeMaterial.opacity = 1;
81027
+ wireframeMaterial.blendType = BLEND_NORMAL;
81028
+ wireframeMaterial.depthTest = true;
81029
+ wireframeMaterial.depthFunc = FUNC_LESSEQUAL;
81030
+ wireframeMaterial.depthWrite = false;
81031
+ wireframeMaterial.cull = CULLFACE_NONE;
81032
+ wireframeMaterial.update();
81033
+ const wireframeInstance = new MeshInstance(mesh, wireframeMaterial);
81034
+ wireframeInstance.drawOrder = 2;
81035
+ const wireframeEntity = new Entity('CollisionWireframe');
81036
+ wireframeEntity.addComponent('render', {
81037
+ meshInstances: [wireframeInstance],
81038
+ layers: [this.layer.id]
81039
+ });
81040
+ wireframeEntity.render.renderStyle = RENDERSTYLE_WIREFRAME;
81041
+ this.materials = [depthMaterial, surfaceMaterial, wireframeMaterial];
81042
+ this.entity = new Entity('MeshCollisionDebug');
81043
+ this.entity.addChild(depthEntity);
81044
+ this.entity.addChild(surfaceEntity);
81045
+ this.entity.addChild(wireframeEntity);
81046
+ this.entity.enabled = false;
81047
+ app.root.addChild(this.entity);
81048
+ }
81049
+ set enabled(value) {
81050
+ this._enabled = value;
81051
+ this.entity.enabled = value;
81052
+ // Disable the layer too — otherwise its render actions still execute
81053
+ // each frame and the per-layer `clearDepthBuffer` would wipe depth
81054
+ // even when no overlay meshes are submitted.
81055
+ this.layer.enabled = value;
81056
+ }
81057
+ get enabled() {
81058
+ return this._enabled;
81059
+ }
81060
+ /**
81061
+ * Re-bake and re-upload the per-vertex colors so the overlay stays
81062
+ * correct if CameraFrame is destroyed or recreated at runtime (the
81063
+ * gamma path differs between the two states).
81064
+ *
81065
+ * @param cameraFrameEnabled - whether CameraFrame is currently active.
81066
+ */
81067
+ setCameraFrameEnabled(cameraFrameEnabled) {
81068
+ encodeFlatColors(this.triangles, cameraFrameEnabled, this.flatColors);
81069
+ this.mesh.setColors32(this.flatColors);
81070
+ this.mesh.update(PRIMITIVE_TRIANGLES);
81071
+ }
81072
+ destroy() {
81073
+ // Entity.destroy() removes child entities and tears down their render
81074
+ // components, which destroy the MeshInstances and decref the shared
81075
+ // Mesh (the last decref destroys its GPU buffers). Materials are not
81076
+ // owned by MeshInstance so destroy them explicitly here.
81077
+ this.entity?.destroy();
81078
+ for (const m of this.materials)
81079
+ m.destroy();
81080
+ this.materials.length = 0;
81081
+ this.app.scene.layers.remove(this.layer);
81082
+ this.camera.camera.layers = this.camera.camera.layers.filter(id => id !== this.layer.id);
81083
+ }
81084
+ }
81085
+
81086
+ /**
81087
+ * World picking for splat scenes.
81088
+ *
81089
+ * - **Compute renderer (WebGPU tiled-compute)**: uses engine `Picker` with depth enabled — expected
81090
+ * depth is already provided by the tile-composite path.
81091
+ * - **Raster renderers (WebGL, CPU / GPU sort, etc.)**: custom `pickPS` / `gsplatPS` patch plus
81092
+ * `RGBA16F` alpha-weighted depth accumulation, because the stock pick pass encodes splat IDs /
81093
+ * last-fragment depth rather than expected depth.
81094
+ */
81095
+ // Override global picking to pack alpha-weighted splat depth instead of meshInstance id.
81096
+ const pickDepthGlsl = /* glsl */ `
81097
+ vec4 encodePickOutput(uint id) {
81098
+ const vec4 inv = vec4(1.0 / 255.0);
81099
+ const uvec4 shifts = uvec4(16, 8, 0, 24);
81100
+ uvec4 col = (uvec4(id) >> shifts) & uvec4(0xff);
81101
+ return vec4(col) * inv;
81102
+ }
81103
+
81104
+ #ifdef GSPLAT_PICK_DEPTH
81105
+ #ifndef CAMERAPLANES
81106
+ #define CAMERAPLANES
81107
+ uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
81108
+ #endif
81109
+
81110
+ vec4 getPickOutput() {
81111
+ float normalizedDepth;
81112
+ if (camera_params.w > 0.5) {
81113
+ normalizedDepth = gl_FragCoord.z;
81114
+ } else {
81115
+ float linearDepth = 1.0 / gl_FragCoord.w;
81116
+ normalizedDepth = (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);
81117
+ }
81118
+
81119
+ return vec4(gaussianColor.a * normalizedDepth, 0.0, 0.0, gaussianColor.a);
81120
+ }
81121
+ #else
81122
+ #ifndef PICK_CUSTOM_ID
81123
+ uniform uint meshInstanceId;
81124
+
81125
+ vec4 getPickOutput() {
81126
+ return encodePickOutput(meshInstanceId);
81127
+ }
81128
+ #endif
81129
+ #endif
81130
+
81131
+ #ifdef DEPTH_PICK_PASS
81132
+ #include "floatAsUintPS"
81133
+ #ifndef CAMERAPLANES
81134
+ #define CAMERAPLANES
81135
+ uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
81136
+ #endif
81137
+
81138
+ vec4 getPickDepth() {
81139
+ float linearDepth;
81140
+ if (camera_params.w > 0.5) {
81141
+ linearDepth = gl_FragCoord.z;
81142
+ } else {
81143
+ float viewDist = 1.0 / gl_FragCoord.w;
81144
+ linearDepth = (viewDist - camera_params.z) / (camera_params.y - camera_params.z);
81145
+ }
81146
+ return float2uint(linearDepth);
81147
+ }
81148
+ #endif
81149
+ `;
81150
+ const pickDepthWgsl = /* wgsl */ `
81151
+ fn encodePickOutput(id: u32) -> vec4f {
81152
+ let inv: vec4f = vec4f(1.0 / 255.0);
81153
+ let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);
81154
+ let col: vec4u = (vec4u(id) >> shifts) & vec4u(0xffu);
81155
+ return vec4f(col) * inv;
81156
+ }
81157
+
81158
+ #ifdef GSPLAT_PICK_DEPTH
81159
+ #ifndef CAMERAPLANES
81160
+ #define CAMERAPLANES
81161
+ uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
81162
+ #endif
81163
+
81164
+ fn getPickOutput() -> vec4f {
81165
+ var normalizedDepth: f32;
81166
+ if (uniform.camera_params.w > 0.5) {
81167
+ normalizedDepth = pcPosition.z;
81168
+ } else {
81169
+ let linearDepth = 1.0 / pcPosition.w;
81170
+ normalizedDepth = (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
81171
+ }
81172
+
81173
+ let a = f32(gaussianColor.a);
81174
+ return vec4f(a * normalizedDepth, 0.0, 0.0, a);
81175
+ }
81176
+ #else
81177
+ #ifndef PICK_CUSTOM_ID
81178
+ uniform meshInstanceId: u32;
81179
+
81180
+ fn getPickOutput() -> vec4f {
81181
+ return encodePickOutput(uniform.meshInstanceId);
81182
+ }
81183
+ #endif
81184
+ #endif
81185
+
81186
+ #ifdef DEPTH_PICK_PASS
81187
+ #include "floatAsUintPS"
81188
+ #ifndef CAMERAPLANES
81189
+ #define CAMERAPLANES
81190
+ uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
81191
+ #endif
81192
+
81193
+ fn getPickDepth() -> vec4f {
81194
+ var linearDepth: f32;
81195
+ if (uniform.camera_params.w > 0.5) {
81196
+ linearDepth = pcPosition.z;
81197
+ } else {
81198
+ let viewDist = 1.0 / pcPosition.w;
81199
+ linearDepth = (viewDist - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
81200
+ }
81201
+ return float2uint(linearDepth);
81202
+ }
81203
+ #endif
81204
+ `;
81205
+ const pickPassChunkInjected = [
81206
+ '#ifdef PICK_PASS',
81207
+ ' #define GSPLAT_PICK_DEPTH',
81208
+ ' #include "pickPS"',
81209
+ '#endif'
81210
+ ].join('\n');
81211
+ const safeChunkReplace = (s, find, repl) => {
81212
+ const out = s.replace(find, repl);
81213
+ if (out === s) {
81214
+ throw new Error('picker: engine gsplat/pick chunk patch failed (engine version mismatch?)');
81215
+ }
81216
+ return out;
81217
+ };
81218
+ const patchGsplatPickGlsl = (chunk) => {
81219
+ return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'pcFragColor0 = encodePickOutput(vPickId);', 'pcFragColor0 = getPickOutput();');
81220
+ };
81221
+ const patchGsplatPickWgsl = (chunk) => {
81222
+ return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'output.color = encodePickOutput(vPickId);', 'output.color = getPickOutput();');
81223
+ };
81224
+ /** Per-device original chunk strings + refcount so we can restore after the last Picker releases. */
81225
+ const pickerShaderPatchState = new WeakMap();
81226
+ const vec4 = new Vec4();
81227
+ const viewProjMat = new Mat4();
81228
+ const clearColor = new Color(0, 0, 0, 1);
81229
+ const NORMAL_EPSILON$1 = 1e-12;
81230
+ const NORMAL_OUTLIER_MIN_DOT = 0.35;
81231
+ const NORMAL_SAMPLE_RADII = [1, 2, 4, 8];
81232
+ const NORMAL_SAMPLE_DIRECTIONS = [
81233
+ [1, 0],
81234
+ [1, 1],
81235
+ [0, 1],
81236
+ [-1, 1],
81237
+ [-1, 0],
81238
+ [-1, -1],
81239
+ [0, -1],
81240
+ [1, -1]
81241
+ ];
81242
+ // Shared buffer for half-to-float conversion
81243
+ const float32 = new Float32Array(1);
81244
+ const uint32 = new Uint32Array(float32.buffer);
81245
+ // Convert 16-bit half-float to 32-bit float using bit manipulation.
81246
+ const half2Float = (h) => {
81247
+ const sign = (h & 0x8000) << 16;
81248
+ const exponent = (h & 0x7C00) >> 10;
81249
+ const mantissa = h & 0x03FF;
81250
+ if (exponent === 0) {
81251
+ if (mantissa === 0) {
81252
+ uint32[0] = sign;
81253
+ }
81254
+ else {
81255
+ let e = -1;
81256
+ let m = mantissa;
81257
+ do {
81258
+ e++;
81259
+ m <<= 1;
81260
+ } while ((m & 0x0400) === 0);
81261
+ uint32[0] = sign | ((127 - 15 - e) << 23) | ((m & 0x03FF) << 13);
81262
+ }
81263
+ }
81264
+ else if (exponent === 31) {
81265
+ uint32[0] = sign | 0x7F800000 | (mantissa << 13);
81266
+ }
81267
+ else {
81268
+ uint32[0] = sign | ((exponent + 127 - 15) << 23) | (mantissa << 13);
81269
+ }
81270
+ return float32[0];
81271
+ };
81272
+ const registerPickerShaderPatches = (app) => {
81273
+ const device = app.graphicsDevice;
81274
+ const existing = pickerShaderPatchState.get(device);
81275
+ if (existing) {
81276
+ existing.refCount++;
81277
+ return;
81278
+ }
81279
+ const glslChunks = ShaderChunks.get(device, 'glsl');
81280
+ const wgslChunks = ShaderChunks.get(device, 'wgsl');
81281
+ const glslPickPS = glslChunks.get('pickPS');
81282
+ const glslGsplatPS = glslChunks.get('gsplatPS');
81283
+ const wgslPickPS = wgslChunks.get('pickPS');
81284
+ const wgslGsplatPS = wgslChunks.get('gsplatPS');
81285
+ // Patch strings before mutating ShaderChunks so engine mismatches leave globals untouched.
81286
+ const patchedGlslGsplatPS = patchGsplatPickGlsl(glslGsplatPS);
81287
+ const patchedWgslGsplatPS = patchGsplatPickWgsl(wgslGsplatPS);
81288
+ const state = {
81289
+ glslPickPS,
81290
+ glslGsplatPS,
81291
+ wgslPickPS,
81292
+ wgslGsplatPS,
81293
+ refCount: 1
81294
+ };
81295
+ pickerShaderPatchState.set(device, state);
81296
+ glslChunks.set('pickPS', pickDepthGlsl);
81297
+ wgslChunks.set('pickPS', pickDepthWgsl);
81298
+ glslChunks.set('gsplatPS', patchedGlslGsplatPS);
81299
+ wgslChunks.set('gsplatPS', patchedWgslGsplatPS);
81300
+ };
81301
+ const unregisterPickerShaderPatches = (app) => {
81302
+ const device = app.graphicsDevice;
81303
+ const state = pickerShaderPatchState.get(device);
81304
+ if (!state) {
81305
+ return;
81306
+ }
81307
+ state.refCount--;
81308
+ if (state.refCount > 0) {
81309
+ return;
81310
+ }
81311
+ const glslChunks = ShaderChunks.get(device, 'glsl');
81312
+ const wgslChunks = ShaderChunks.get(device, 'wgsl');
81313
+ glslChunks.set('pickPS', state.glslPickPS);
81314
+ glslChunks.set('gsplatPS', state.glslGsplatPS);
81315
+ wgslChunks.set('pickPS', state.wgslPickPS);
81316
+ wgslChunks.set('gsplatPS', state.wgslGsplatPS);
81317
+ pickerShaderPatchState.delete(device);
81318
+ };
81319
+ const createPickCameraSnapshot = () => ({
81320
+ position: new Vec3(),
81321
+ viewMatrix: new Mat4(),
81322
+ projectionMatrix: new Mat4(),
81323
+ nearClip: 0,
81324
+ farClip: 0,
81325
+ projection: 0
81326
+ });
81327
+ const captureCameraSnapshot = (camera, out) => {
81328
+ const cam = camera.camera;
81329
+ out.position.copy(camera.getPosition());
81330
+ out.viewMatrix.copy(cam.viewMatrix);
81331
+ out.projectionMatrix.copy(cam.projectionMatrix);
81332
+ out.nearClip = cam.nearClip;
81333
+ out.farClip = cam.farClip;
81334
+ out.projection = cam.projection;
81335
+ };
81336
+ const getWorldPoint = (camera, x, y, width, height, normalizedDepth, out) => {
81337
+ if (!Number.isFinite(normalizedDepth) || normalizedDepth < 0 || normalizedDepth > 1) {
81338
+ return null;
81339
+ }
81340
+ const { farClip: far, nearClip: near } = camera;
81341
+ const ndcDepth = camera.projection === PROJECTION_ORTHOGRAPHIC ?
81342
+ normalizedDepth :
81343
+ far * normalizedDepth / (normalizedDepth * (far - near) + near);
81344
+ viewProjMat.mul2(camera.projectionMatrix, camera.viewMatrix).invert();
81345
+ vec4.set(x / width * 2 - 1, (1 - y / height) * 2 - 1, ndcDepth * 2 - 1, 1);
81346
+ viewProjMat.transformVec4(vec4, vec4);
81347
+ if (!Number.isFinite(vec4.w) || Math.abs(vec4.w) < 1e-8) {
81348
+ return null;
81349
+ }
81350
+ vec4.mulScalar(1 / vec4.w);
81351
+ if (!Number.isFinite(vec4.x) || !Number.isFinite(vec4.y) || !Number.isFinite(vec4.z)) {
81352
+ return null;
81353
+ }
81354
+ return (out ?? new Vec3()).set(vec4.x, vec4.y, vec4.z);
81355
+ };
81356
+ const setCameraFacingNormal = (cameraPosition, position, normal) => {
81357
+ normal.sub2(cameraPosition, position);
81358
+ const len = normal.length();
81359
+ if (len > 1e-6) {
81360
+ normal.mulScalar(1 / len);
81361
+ }
81362
+ else {
81363
+ normal.set(0, 1, 0);
81364
+ }
81365
+ return normal;
81366
+ };
81367
+ class Picker {
81368
+ pick;
81369
+ pickSurface;
81370
+ release;
81371
+ constructor(app, camera) {
81372
+ const { graphicsDevice } = app;
81373
+ let enginePicker;
81374
+ let accumBuffer;
81375
+ let accumTarget;
81376
+ let accumPass;
81377
+ let chunksPatched = false;
81378
+ let pickQueue = Promise.resolve();
81379
+ let cacheValid = false;
81380
+ let cacheWidth = 0;
81381
+ let cacheHeight = 0;
81382
+ const cacheCamera = createPickCameraSnapshot();
81383
+ const initRasterAccum = (width, height) => {
81384
+ accumBuffer = new Texture(graphicsDevice, {
81385
+ format: PIXELFORMAT_RGBA16F,
81386
+ width,
81387
+ height,
81388
+ mipmaps: false,
81389
+ minFilter: FILTER_NEAREST,
81390
+ magFilter: FILTER_NEAREST,
81391
+ addressU: ADDRESS_CLAMP_TO_EDGE,
81392
+ addressV: ADDRESS_CLAMP_TO_EDGE,
81393
+ name: 'picker-accum'
81394
+ });
81395
+ accumTarget = new RenderTarget({
81396
+ colorBuffer: accumBuffer,
81397
+ depth: false // not needed — gaussians are rendered back to front
81398
+ });
81399
+ accumPass = new RenderPassPicker(graphicsDevice, app.renderer);
81400
+ // RGB: additive depth accumulation. Alpha: multiplicative transmittance.
81401
+ accumPass.blendState = new BlendState(true, BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ONE_MINUS_SRC_ALPHA, BLENDEQUATION_ADD, BLENDMODE_ZERO, BLENDMODE_ONE_MINUS_SRC_ALPHA);
81402
+ };
81403
+ const readTexture = (texture, x, y, target) => {
81404
+ const texY = graphicsDevice.isWebGL2 ? target.height - y - 1 : y;
81405
+ return texture.read(x, texY, 1, 1, {
81406
+ renderTarget: target,
81407
+ immediate: true
81408
+ });
81409
+ };
81410
+ const updateCache = (width, height) => {
81411
+ captureCameraSnapshot(camera, cacheCamera);
81412
+ cacheWidth = width;
81413
+ cacheHeight = height;
81414
+ };
81415
+ const cameraMatches = (width, height) => {
81416
+ const cam = camera.camera;
81417
+ return cacheValid &&
81418
+ cacheWidth === width &&
81419
+ cacheHeight === height &&
81420
+ cacheCamera.viewMatrix.equals(cam.viewMatrix) &&
81421
+ cacheCamera.projectionMatrix.equals(cam.projectionMatrix) &&
81422
+ cacheCamera.nearClip === cam.nearClip &&
81423
+ cacheCamera.farClip === cam.farClip &&
81424
+ cacheCamera.projection === cam.projection;
81425
+ };
81426
+ const getCacheCameraSnapshot = () => {
81427
+ const snapshot = createPickCameraSnapshot();
81428
+ snapshot.position.copy(cacheCamera.position);
81429
+ snapshot.viewMatrix.copy(cacheCamera.viewMatrix);
81430
+ snapshot.projectionMatrix.copy(cacheCamera.projectionMatrix);
81431
+ snapshot.nearClip = cacheCamera.nearClip;
81432
+ snapshot.farClip = cacheCamera.farClip;
81433
+ snapshot.projection = cacheCamera.projection;
81434
+ return snapshot;
81435
+ };
81436
+ const readRasterBlock = async (blockX, blockY, blockWidth, blockHeight, viewportWidth, viewportHeight, pickCamera) => {
81437
+ const texY = graphicsDevice.isWebGL2 ? accumTarget.height - blockY - blockHeight : blockY;
81438
+ const pixels = await accumBuffer.read(blockX, texY, blockWidth, blockHeight, {
81439
+ renderTarget: accumTarget,
81440
+ immediate: true
81441
+ });
81442
+ return (x, y) => {
81443
+ const localX = x - blockX;
81444
+ const localY = y - blockY;
81445
+ if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
81446
+ return null;
81447
+ }
81448
+ const row = graphicsDevice.isWebGL2 ? blockHeight - localY - 1 : localY;
81449
+ const index = (row * blockWidth + localX) * 4;
81450
+ const r = half2Float(pixels[index]);
81451
+ const transmittance = half2Float(pixels[index + 3]);
81452
+ const alpha = 1 - transmittance;
81453
+ if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
81454
+ return null;
81455
+ }
81456
+ const normalizedDepth = r / alpha;
81457
+ return getWorldPoint(pickCamera, x, y, viewportWidth, viewportHeight, normalizedDepth);
81458
+ };
81459
+ };
81460
+ const ensureRendered = (width, height, isComputeRenderer, worldLayer) => {
81461
+ if (cameraMatches(width, height)) {
81462
+ return;
81463
+ }
81464
+ // Enable gsplat IDs only while rendering the pick target so we
81465
+ // don't pay the memory/perf cost between pick passes.
81466
+ const prevEnableIds = app.scene.gsplat.enableIds;
81467
+ app.scene.gsplat.enableIds = true;
81468
+ try {
81469
+ if (isComputeRenderer) {
81470
+ enginePicker ??= new Picker$1(app, 1, 1, true);
81471
+ enginePicker.resize(width, height);
81472
+ enginePicker.prepare(camera.camera, app.scene, [worldLayer]);
81473
+ }
81474
+ else {
81475
+ if (!chunksPatched) {
81476
+ registerPickerShaderPatches(app);
81477
+ chunksPatched = true;
81478
+ }
81479
+ if (!accumPass) {
81480
+ initRasterAccum(width, height);
81481
+ }
81482
+ else if (cacheWidth !== width || cacheHeight !== height) {
81483
+ cacheValid = false;
81484
+ accumTarget.resize(width, height);
81485
+ }
81486
+ accumPass.init(accumTarget);
81487
+ accumPass.setClearColor(clearColor);
81488
+ accumPass.update(camera.camera, app.scene, [worldLayer], new Map(), false);
81489
+ accumPass.render();
81490
+ }
81491
+ updateCache(width, height);
81492
+ cacheValid = true;
81493
+ }
81494
+ finally {
81495
+ app.scene.gsplat.enableIds = prevEnableIds;
81496
+ }
81497
+ };
81498
+ const prepareSample = (x, y) => {
81499
+ const width = Math.floor(graphicsDevice.width);
81500
+ const height = Math.floor(graphicsDevice.height);
81501
+ // bail out if the device hasn't been sized yet
81502
+ if (width <= 0 || height <= 0) {
81503
+ return null;
81504
+ }
81505
+ const worldLayer = app.scene.layers.getLayerByName('World');
81506
+ if (!worldLayer) {
81507
+ return null;
81508
+ }
81509
+ const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
81510
+ const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
81511
+ const isComputeRenderer = app.scene.gsplat.currentRenderer === GSPLAT_RENDERER_COMPUTE;
81512
+ ensureRendered(width, height, isComputeRenderer, worldLayer);
81513
+ const pickCamera = getCacheCameraSnapshot();
81514
+ return { width, height, screenX, screenY, isComputeRenderer, pickCamera };
81515
+ };
81516
+ const pickPosition = async (x, y) => {
81517
+ const sample = prepareSample(x, y);
81518
+ if (!sample) {
81519
+ return null;
81520
+ }
81521
+ const { width, height, screenX, screenY, isComputeRenderer, pickCamera } = sample;
81522
+ if (isComputeRenderer) {
81523
+ const normalizedDepth = await enginePicker.getPointDepthAsync(screenX, screenY);
81524
+ const position = normalizedDepth !== null ?
81525
+ getWorldPoint(pickCamera, screenX, screenY, width, height, normalizedDepth) :
81526
+ null;
81527
+ return position ? { position, camera: pickCamera, screenX, screenY, width, height, isComputeRenderer } : null;
81528
+ }
81529
+ const pixels = await readTexture(accumBuffer, screenX, screenY, accumTarget);
81530
+ const r = half2Float(pixels[0]);
81531
+ const transmittance = half2Float(pixels[3]);
81532
+ const alpha = 1 - transmittance;
81533
+ if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
81534
+ return null;
81535
+ }
81536
+ const normalizedDepth = r / alpha;
81537
+ const position = getWorldPoint(pickCamera, screenX, screenY, width, height, normalizedDepth);
81538
+ return position ? { position, camera: pickCamera, screenX, screenY, width, height, isComputeRenderer } : null;
81539
+ };
81540
+ const serializePick = (operation) => {
81541
+ // The render targets are shared by all picks on this instance.
81542
+ const result = pickQueue.then(operation, operation);
81543
+ pickQueue = result.then(() => undefined, () => undefined);
81544
+ return result;
81545
+ };
81546
+ const pick = async (x, y) => {
81547
+ const result = await pickPosition(x, y);
81548
+ return result?.position ?? null;
81549
+ };
81550
+ const pickSurface = async (x, y) => {
81551
+ const sample = prepareSample(x, y);
81552
+ if (!sample) {
81553
+ return null;
81554
+ }
81555
+ const { width, height, screenX, screenY, isComputeRenderer, pickCamera } = sample;
81556
+ if (isComputeRenderer) {
81557
+ const normalizedDepth = await enginePicker.getPointDepthAsync(screenX, screenY);
81558
+ const position = normalizedDepth !== null ?
81559
+ getWorldPoint(pickCamera, screenX, screenY, width, height, normalizedDepth) :
81560
+ null;
81561
+ if (!position) {
81562
+ return null;
81563
+ }
81564
+ return {
81565
+ position,
81566
+ normal: new Vec3(0, 1, 0)
81567
+ };
81568
+ }
81569
+ // Single block read serves both depth (center pixel) and normal samples (ring).
81570
+ const maxRadius = NORMAL_SAMPLE_RADII[NORMAL_SAMPLE_RADII.length - 1];
81571
+ const blockX = Math.max(0, screenX - maxRadius);
81572
+ const blockY = Math.max(0, screenY - maxRadius);
81573
+ const blockWidth = Math.min(width - 1, screenX + maxRadius) - blockX + 1;
81574
+ const blockHeight = Math.min(height - 1, screenY + maxRadius) - blockY + 1;
81575
+ const rasterBlock = await readRasterBlock(blockX, blockY, blockWidth, blockHeight, width, height, pickCamera);
81576
+ const position = rasterBlock(screenX, screenY);
81577
+ if (!position) {
81578
+ return null;
81579
+ }
81580
+ const samplePixel = (px, py) => {
81581
+ if (px < 0 || px >= width || py < 0 || py >= height) {
81582
+ return null;
81583
+ }
81584
+ return rasterBlock(px, py);
81585
+ };
81586
+ const sampleRings = NORMAL_SAMPLE_RADII.map((radius) => {
81587
+ return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
81588
+ return samplePixel(screenX + dx * radius, screenY + dy * radius);
81589
+ });
81590
+ });
81591
+ const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
81592
+ const candidates = [];
81593
+ const va = new Vec3();
81594
+ const vb = new Vec3();
81595
+ const sampleNormal = new Vec3();
81596
+ sampleRings.forEach((points) => {
81597
+ for (let i = 0; i < NORMAL_SAMPLE_DIRECTIONS.length; i++) {
81598
+ const pointA = points[i];
81599
+ const pointB = points[(i + 1) % NORMAL_SAMPLE_DIRECTIONS.length];
81600
+ if (!pointA || !pointB) {
81601
+ continue;
81602
+ }
81603
+ va.sub2(pointA, position);
81604
+ vb.sub2(pointB, position);
81605
+ if (va.lengthSq() <= NORMAL_EPSILON$1 || vb.lengthSq() <= NORMAL_EPSILON$1) {
81606
+ continue;
81607
+ }
81608
+ // Direction order is clockwise in screen space. Screen Y points
81609
+ // down, so crossing next by current gives a camera-facing normal.
81610
+ sampleNormal.cross(vb, va);
81611
+ if (sampleNormal.lengthSq() <= NORMAL_EPSILON$1) {
81612
+ continue;
81613
+ }
81614
+ const candidate = sampleNormal.clone().normalize();
81615
+ if (candidate.dot(toCamera) < 0) {
81616
+ candidate.mulScalar(-1);
81617
+ }
81618
+ candidates.push(candidate);
81619
+ }
81620
+ });
81621
+ const normal = new Vec3();
81622
+ candidates.forEach((candidate) => {
81623
+ normal.add(candidate);
81624
+ });
81625
+ if (normal.lengthSq() > NORMAL_EPSILON$1) {
81626
+ normal.normalize();
81627
+ const refined = new Vec3();
81628
+ candidates.forEach((candidate) => {
81629
+ if (candidate.dot(normal) >= NORMAL_OUTLIER_MIN_DOT) {
81630
+ refined.add(candidate);
81631
+ }
81632
+ });
81633
+ if (refined.lengthSq() > NORMAL_EPSILON$1) {
81634
+ normal.copy(refined).normalize();
81635
+ }
81636
+ }
81637
+ else {
81638
+ normal.copy(toCamera);
81639
+ }
81640
+ return {
81641
+ position,
81642
+ normal
81643
+ };
81644
+ };
81645
+ this.pick = (x, y) => serializePick(() => pick(x, y));
81646
+ this.pickSurface = (x, y) => serializePick(() => pickSurface(x, y));
81647
+ this.release = () => {
81648
+ if (chunksPatched) {
81649
+ unregisterPickerShaderPatches(app);
81650
+ chunksPatched = false;
81651
+ }
81652
+ enginePicker?.destroy();
81653
+ accumPass?.destroy();
81654
+ accumTarget?.destroy();
81655
+ accumBuffer?.destroy();
81656
+ cacheValid = false;
81657
+ };
81658
+ }
81659
+ }
81660
+
81661
+ const SVGNS = 'http://www.w3.org/2000/svg';
81662
+ const NUM_SAMPLES = 12;
81663
+ const CIRCLE_OUTER_RADIUS = 0.2;
81664
+ const CIRCLE_INNER_RADIUS = 0.17;
81665
+ const BEZIER_K = 1 / 6;
81666
+ const NORMAL_SMOOTH_FACTOR = 0.25;
81667
+ const NORMAL_SNAP_ANGLE = Math.PI / 4;
81668
+ const NORMAL_EPSILON = 1e-6;
81669
+ const createNormalSnapDirections = () => {
81670
+ const result = [];
81671
+ for (let pitchStep = -2; pitchStep <= 2; pitchStep++) {
81672
+ const pitch = pitchStep * NORMAL_SNAP_ANGLE;
81673
+ const cp = Math.cos(pitch);
81674
+ const sy = Math.sin(pitch);
81675
+ if (Math.abs(cp) <= NORMAL_EPSILON) {
81676
+ result.push(new Vec3(0, sy > 0 ? 1 : -1, 0));
81677
+ continue;
81678
+ }
81679
+ for (let yawStep = 0; yawStep < 8; yawStep++) {
81680
+ const yaw = yawStep * NORMAL_SNAP_ANGLE;
81681
+ result.push(new Vec3(Math.cos(yaw) * cp, sy, Math.sin(yaw) * cp));
81682
+ }
81683
+ }
81684
+ return result;
81685
+ };
81686
+ const NORMAL_SNAP_DIRECTIONS = createNormalSnapDirections();
81687
+ const snapNormal = (nx, ny, nz, out) => {
81688
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
81689
+ if (len <= NORMAL_EPSILON) {
81690
+ return out.set(0, 1, 0);
81691
+ }
81692
+ const invLen = 1 / len;
81693
+ const x = nx * invLen;
81694
+ const y = ny * invLen;
81695
+ const z = nz * invLen;
81696
+ let best = NORMAL_SNAP_DIRECTIONS[0];
81697
+ let bestDot = -Infinity;
81698
+ for (let i = 0; i < NORMAL_SNAP_DIRECTIONS.length; i++) {
81699
+ const candidate = NORMAL_SNAP_DIRECTIONS[i];
81700
+ const dot = candidate.x * x + candidate.y * y + candidate.z * z;
81701
+ if (dot > bestDot) {
81702
+ bestDot = dot;
81703
+ best = candidate;
81704
+ }
81705
+ }
81706
+ return out.copy(best);
81707
+ };
81708
+ const tmpV = new Vec3();
81709
+ const tmpScreen = new Vec3();
81710
+ const tangent = new Vec3();
81711
+ const bitangent = new Vec3();
81712
+ const worldPt = new Vec3();
81713
+ const up = new Vec3(0, 1, 0);
81714
+ const right = new Vec3(1, 0, 0);
81715
+ const tmpViewPos = new Vec3();
81716
+ const tmpClipVec = new Vec4();
81717
+ const tmpViewProj = new Mat4();
81718
+ const worldPointToDepth = (camera, worldPos) => {
81719
+ if (camera.projection === PROJECTION_ORTHOGRAPHIC) {
81720
+ tmpViewProj.mul2(camera.projectionMatrix, camera.viewMatrix);
81721
+ tmpClipVec.set(worldPos.x, worldPos.y, worldPos.z, 1);
81722
+ tmpViewProj.transformVec4(tmpClipVec, tmpClipVec);
81723
+ if (Math.abs(tmpClipVec.w) < 1e-8) {
81724
+ return -1;
81725
+ }
81726
+ return (tmpClipVec.z / tmpClipVec.w + 1) * 0.5;
81727
+ }
81728
+ camera.viewMatrix.transformPoint(worldPos, tmpViewPos);
81729
+ const linearDepth = -tmpViewPos.z;
81730
+ const range = camera.farClip - camera.nearClip;
81731
+ if (range <= 0) {
81732
+ return -1;
81733
+ }
81734
+ return (linearDepth - camera.nearClip) / range;
81735
+ };
81736
+ const createSurfaceSample = () => ({
81737
+ normalizedDepth: 0,
81738
+ normal: new Vec3(),
81739
+ camera: {
81740
+ position: new Vec3(),
81741
+ viewMatrix: new Mat4(),
81742
+ projectionMatrix: new Mat4(),
81743
+ nearClip: 0,
81744
+ farClip: 0,
81745
+ projection: 0
81746
+ },
81747
+ width: 0,
81748
+ height: 0
81749
+ });
81750
+ const buildBezierRing = (sx, sy) => {
81751
+ const n = sx.length;
81752
+ let p = `M${sx[0].toFixed(1)},${sy[0].toFixed(1)}`;
81753
+ for (let i = 0; i < n; i++) {
81754
+ const i0 = (i - 1 + n) % n;
81755
+ const i1 = i;
81756
+ const i2 = (i + 1) % n;
81757
+ const i3 = (i + 2) % n;
81758
+ const cp1x = sx[i1] + (sx[i2] - sx[i0]) * BEZIER_K;
81759
+ const cp1y = sy[i1] + (sy[i2] - sy[i0]) * BEZIER_K;
81760
+ const cp2x = sx[i2] - (sx[i3] - sx[i1]) * BEZIER_K;
81761
+ const cp2y = sy[i2] - (sy[i3] - sy[i1]) * BEZIER_K;
81762
+ p += ` C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${sx[i2].toFixed(1)},${sy[i2].toFixed(1)}`;
81763
+ }
81764
+ return `${p} Z`;
81765
+ };
81766
+ class CursorRing {
81767
+ path;
81768
+ svg;
81769
+ camera;
81770
+ smoothing;
81771
+ smoothNx = 0;
81772
+ smoothNy = 1;
81773
+ smoothNz = 0;
81774
+ hasSmoothedNormal = false;
81775
+ outerX = new Float64Array(NUM_SAMPLES);
81776
+ outerY = new Float64Array(NUM_SAMPLES);
81777
+ innerX = new Float64Array(NUM_SAMPLES);
81778
+ innerY = new Float64Array(NUM_SAMPLES);
81779
+ constructor(svg, camera, smoothing) {
81780
+ this.svg = svg;
81781
+ this.camera = camera;
81782
+ this.smoothing = smoothing;
81783
+ this.path = document.createElementNS(SVGNS, 'path');
81784
+ this.path.setAttribute('fill', 'white');
81785
+ this.path.setAttribute('fill-opacity', '0.6');
81786
+ this.path.setAttribute('fill-rule', 'evenodd');
81787
+ this.path.setAttribute('stroke', 'none');
81788
+ this.path.style.display = 'none';
81789
+ svg.appendChild(this.path);
81790
+ }
81791
+ projectCircle(px, py, pz, nx, ny, nz, radius, outX, outY) {
81792
+ const normal = tmpV.set(nx, ny, nz);
81793
+ if (Math.abs(normal.y) < 0.99) {
81794
+ tangent.cross(normal, up).normalize();
81795
+ }
81796
+ else {
81797
+ tangent.cross(normal, right).normalize();
80440
81798
  }
80441
- const oc = i * 12;
80442
- for (let j = 0; j < 3; j++) {
80443
- const k = oc + j * 4;
80444
- colors[k] = gray;
80445
- colors[k + 1] = gray;
80446
- colors[k + 2] = gray;
80447
- colors[k + 3] = alpha;
81799
+ bitangent.cross(normal, tangent);
81800
+ const cam = this.camera.camera;
81801
+ const angleStep = (2 * Math.PI) / NUM_SAMPLES;
81802
+ for (let i = 0; i < NUM_SAMPLES; i++) {
81803
+ const theta = i * angleStep;
81804
+ const ct = Math.cos(theta);
81805
+ const st = Math.sin(theta);
81806
+ const tx = ct * tangent.x + st * bitangent.x;
81807
+ const ty = ct * tangent.y + st * bitangent.y;
81808
+ const tz = ct * tangent.z + st * bitangent.z;
81809
+ worldPt.set(px + tx * radius, py + ty * radius, pz + tz * radius);
81810
+ cam.worldToScreen(worldPt, tmpScreen);
81811
+ outX[i] = tmpScreen.x;
81812
+ outY[i] = tmpScreen.y;
80448
81813
  }
80449
81814
  }
80450
- return colors;
80451
- };
80452
- const buildFlatMesh = (tris, cameraFrameEnabled) => {
80453
- const numTris = tris.count;
80454
- const flatPositions = new Float32Array(numTris * 9);
80455
- const flatColors = encodeFlatColors(tris, cameraFrameEnabled);
80456
- const flatIndices = new Uint32Array(numTris * 3);
80457
- for (let i = 0; i < numTris; i++) {
80458
- const op = i * 9;
80459
- flatPositions[op] = tris.v0x[i];
80460
- flatPositions[op + 1] = tris.v0y[i];
80461
- flatPositions[op + 2] = tris.v0z[i];
80462
- flatPositions[op + 3] = tris.v1x[i];
80463
- flatPositions[op + 4] = tris.v1y[i];
80464
- flatPositions[op + 5] = tris.v1z[i];
80465
- flatPositions[op + 6] = tris.v2x[i];
80466
- flatPositions[op + 7] = tris.v2y[i];
80467
- flatPositions[op + 8] = tris.v2z[i];
80468
- const oi = i * 3;
80469
- flatIndices[oi] = oi;
80470
- flatIndices[oi + 1] = oi + 1;
80471
- flatIndices[oi + 2] = oi + 2;
81815
+ render(pos, normal) {
81816
+ snapNormal(normal.x, normal.y, normal.z, tmpV);
81817
+ let nx = tmpV.x;
81818
+ let ny = tmpV.y;
81819
+ let nz = tmpV.z;
81820
+ if (this.smoothing) {
81821
+ if (this.hasSmoothedNormal) {
81822
+ const t = NORMAL_SMOOTH_FACTOR;
81823
+ nx = this.smoothNx + (nx - this.smoothNx) * t;
81824
+ ny = this.smoothNy + (ny - this.smoothNy) * t;
81825
+ nz = this.smoothNz + (nz - this.smoothNz) * t;
81826
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
81827
+ if (len > 1e-6) {
81828
+ const invLen = 1.0 / len;
81829
+ nx *= invLen;
81830
+ ny *= invLen;
81831
+ nz *= invLen;
81832
+ }
81833
+ }
81834
+ this.smoothNx = nx;
81835
+ this.smoothNy = ny;
81836
+ this.smoothNz = nz;
81837
+ this.hasSmoothedNormal = true;
81838
+ }
81839
+ this.projectCircle(pos.x, pos.y, pos.z, nx, ny, nz, CIRCLE_OUTER_RADIUS, this.outerX, this.outerY);
81840
+ this.projectCircle(pos.x, pos.y, pos.z, nx, ny, nz, CIRCLE_INNER_RADIUS, this.innerX, this.innerY);
81841
+ this.path.setAttribute('d', `${buildBezierRing(this.outerX, this.outerY)} ${buildBezierRing(this.innerX, this.innerY)}`);
81842
+ this.path.style.display = '';
81843
+ this.svg.style.display = '';
80472
81844
  }
80473
- return { flatPositions, flatColors, flatIndices };
80474
- };
80475
- // Configures a StandardMaterial that emits the per-vertex color directly. The
80476
- // depth pre-pass and the color pass use the same configuration (so they
80477
- // compile to identical shaders and produce bit-identical depth values for
80478
- // FUNC_EQUAL); only their write masks and depth state differ.
80479
- const makeSurfaceMaterial = () => {
80480
- const m = new StandardMaterial();
80481
- m.useLighting = false;
80482
- m.useSkybox = false;
80483
- m.useFog = false;
80484
- m.useTonemap = false;
80485
- m.ambient = new Color(0, 0, 0);
80486
- m.diffuse = new Color(0, 0, 0);
80487
- m.specular = new Color(0, 0, 0);
80488
- m.emissive = new Color(1, 1, 1);
80489
- m.emissiveVertexColor = true;
80490
- m.emissiveVertexColorChannel = 'rgb';
80491
- m.opacityVertexColor = true;
80492
- m.opacityVertexColorChannel = 'a';
80493
- m.opacity = 1;
80494
- return m;
80495
- };
80496
- class MeshDebugOverlay {
80497
- app;
81845
+ hide() {
81846
+ this.path.style.display = 'none';
81847
+ this.hasSmoothedNormal = false;
81848
+ }
81849
+ }
81850
+ class NavCursor {
81851
+ svg;
81852
+ hoverRing;
81853
+ targetRing;
80498
81854
  camera;
80499
- layer;
80500
- entity;
80501
- mesh;
80502
- triangles;
80503
- flatColors;
80504
- materials;
80505
- _enabled = false;
80506
- constructor(app, collision, camera, cameraFrameEnabled) {
80507
- this.app = app;
81855
+ collision;
81856
+ canvas;
81857
+ state;
81858
+ picker;
81859
+ app;
81860
+ onPrerender;
81861
+ active = false;
81862
+ navigating = false;
81863
+ targetPos = null;
81864
+ targetNormal = null;
81865
+ targetMode = null;
81866
+ surfaceCursorX = 0;
81867
+ surfaceCursorY = 0;
81868
+ hasSurfaceCursorPosition = false;
81869
+ surfaceCursorVersion = 0;
81870
+ surfaceCursorPickPending = false;
81871
+ surfaceSample = createSurfaceSample();
81872
+ hasSurfaceSample = false;
81873
+ scratchHoverPos = new Vec3();
81874
+ onPointerMove;
81875
+ onPointerLeave;
81876
+ collisionTarget = {
81877
+ position: new Vec3(),
81878
+ normal: new Vec3()
81879
+ };
81880
+ constructor(app, camera, collision, events, state, picker) {
80508
81881
  this.camera = camera;
80509
- this.triangles = collision.triangles;
80510
- const device = app.graphicsDevice;
80511
- const { flatPositions, flatColors, flatIndices } = buildFlatMesh(this.triangles, cameraFrameEnabled);
80512
- this.flatColors = flatColors;
80513
- const mesh = new Mesh(device);
80514
- mesh.setPositions(flatPositions);
80515
- mesh.setColors32(flatColors);
80516
- mesh.setIndices(flatIndices);
80517
- mesh.update(PRIMITIVE_TRIANGLES);
80518
- mesh.generateWireframe();
80519
- this.mesh = mesh;
80520
- this.layer = new Layer({
80521
- name: 'CollisionOverlay',
80522
- enabled: false,
80523
- clearColorBuffer: false,
80524
- clearDepthBuffer: true,
80525
- opaqueSortMode: SORTMODE_MANUAL,
80526
- transparentSortMode: SORTMODE_MANUAL
81882
+ this.collision = collision;
81883
+ this.canvas = app.graphicsDevice.canvas;
81884
+ this.state = state;
81885
+ this.picker = picker;
81886
+ this.app = app;
81887
+ this.svg = document.createElementNS(SVGNS, 'svg');
81888
+ this.svg.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:1';
81889
+ this.canvas.parentElement.appendChild(this.svg);
81890
+ this.hoverRing = new CursorRing(this.svg, camera, true);
81891
+ this.targetRing = new CursorRing(this.svg, camera, false);
81892
+ this.svg.style.display = 'none';
81893
+ this.onPointerMove = (e) => {
81894
+ if (e.pointerType === 'touch') {
81895
+ this.hasSurfaceCursorPosition = false;
81896
+ this.surfaceCursorVersion++;
81897
+ this.hoverRing.hide();
81898
+ return;
81899
+ }
81900
+ if (e.buttons) {
81901
+ this.hasSurfaceCursorPosition = false;
81902
+ this.surfaceCursorVersion++;
81903
+ this.hoverRing.hide();
81904
+ return;
81905
+ }
81906
+ this.updateCursor(e.offsetX, e.offsetY);
81907
+ };
81908
+ this.onPointerLeave = () => {
81909
+ this.hasSurfaceCursorPosition = false;
81910
+ this.surfaceCursorVersion++;
81911
+ this.hoverRing.hide();
81912
+ };
81913
+ this.canvas.addEventListener('pointermove', this.onPointerMove);
81914
+ this.canvas.addEventListener('pointerleave', this.onPointerLeave);
81915
+ const updateActive = () => {
81916
+ const flyMouseCaptured = (state.cameraMode === 'fly' &&
81917
+ state.inputMode === 'desktop' &&
81918
+ state.gamingControls);
81919
+ this.active = (state.cameraMode === 'walk' && !state.gamingControls) ||
81920
+ (state.cameraMode === 'fly' && !flyMouseCaptured) ||
81921
+ state.cameraMode === 'orbit';
81922
+ this.surfaceCursorVersion++;
81923
+ this.hoverRing.hide();
81924
+ if (state.inputMode !== 'desktop') {
81925
+ this.hasSurfaceCursorPosition = false;
81926
+ }
81927
+ if (this.targetMode && this.targetMode !== state.cameraMode) {
81928
+ this.navigating = false;
81929
+ this.clearTarget();
81930
+ }
81931
+ if (!this.active) {
81932
+ this.svg.style.display = 'none';
81933
+ }
81934
+ };
81935
+ events.on('cameraMode:changed', updateActive);
81936
+ events.on('inputMode:changed', updateActive);
81937
+ events.on('gamingControls:changed', updateActive);
81938
+ events.on('navigateTo', () => {
81939
+ this.navigating = true;
81940
+ this.hoverRing.hide();
80527
81941
  });
80528
- app.scene.layers.push(this.layer);
80529
- camera.camera.layers = [...camera.camera.layers, this.layer.id];
80530
- // Pass 1: depth pre-pass. Color writes masked off so only depth lands
80531
- // in the buffer. Both this and pass 2 use the same depthBias /
80532
- // slopeDepthBias so they write/test identical depth values
80533
- // (FUNC_EQUAL relies on this) while still sitting slightly behind the
80534
- // wireframe lines so pass 3's FUNC_LESSEQUAL passes reliably without
80535
- // z-fighting.
80536
- const depthMaterial = makeSurfaceMaterial();
80537
- depthMaterial.cull = CULLFACE_BACK;
80538
- depthMaterial.blendType = BLEND_NORMAL;
80539
- depthMaterial.depthTest = true;
80540
- depthMaterial.depthWrite = true;
80541
- depthMaterial.depthBias = 1;
80542
- depthMaterial.slopeDepthBias = 1;
80543
- depthMaterial.redWrite = false;
80544
- depthMaterial.greenWrite = false;
80545
- depthMaterial.blueWrite = false;
80546
- depthMaterial.alphaWrite = false;
80547
- depthMaterial.update();
80548
- const depthInstance = new MeshInstance(mesh, depthMaterial);
80549
- depthInstance.drawOrder = 0;
80550
- const depthEntity = new Entity('CollisionDepthPrepass');
80551
- depthEntity.addComponent('render', {
80552
- meshInstances: [depthInstance],
80553
- layers: [this.layer.id]
81942
+ events.on('navigateCancel', () => {
81943
+ this.navigating = false;
81944
+ this.clearTarget();
80554
81945
  });
80555
- // Pass 2: surface color, depth EQUAL. Only the front-most fragment
80556
- // from pass 1 survives, so a single layer of vertex color blends onto
80557
- // the camera target.
80558
- const surfaceMaterial = makeSurfaceMaterial();
80559
- surfaceMaterial.cull = CULLFACE_BACK;
80560
- surfaceMaterial.blendType = BLEND_NORMAL;
80561
- surfaceMaterial.depthTest = true;
80562
- surfaceMaterial.depthFunc = FUNC_EQUAL;
80563
- surfaceMaterial.depthWrite = false;
80564
- surfaceMaterial.depthBias = 1;
80565
- surfaceMaterial.slopeDepthBias = 1;
80566
- surfaceMaterial.update();
80567
- const surfaceInstance = new MeshInstance(mesh, surfaceMaterial);
80568
- surfaceInstance.drawOrder = 1;
80569
- const surfaceEntity = new Entity('CollisionSurface');
80570
- surfaceEntity.addComponent('render', {
80571
- meshInstances: [surfaceInstance],
80572
- layers: [this.layer.id]
81946
+ events.on('navigateComplete', () => {
81947
+ this.navigating = false;
81948
+ this.clearTarget();
80573
81949
  });
80574
- // Pass 3: wireframe — black lines depth-tested against the surface so
80575
- // back-facing edges are hidden. BLEND_NORMAL with opacity = 1 looks
80576
- // opaque but routes through the same transparent render action as the
80577
- // other two passes, keeping all three under one depth clear.
80578
- const wireframeMaterial = new StandardMaterial();
80579
- wireframeMaterial.useLighting = false;
80580
- wireframeMaterial.useSkybox = false;
80581
- wireframeMaterial.useFog = false;
80582
- wireframeMaterial.useTonemap = false;
80583
- wireframeMaterial.ambient = new Color(0, 0, 0);
80584
- wireframeMaterial.diffuse = new Color(0, 0, 0);
80585
- wireframeMaterial.specular = new Color(0, 0, 0);
80586
- wireframeMaterial.emissive = new Color(0, 0, 0);
80587
- wireframeMaterial.opacity = 1;
80588
- wireframeMaterial.blendType = BLEND_NORMAL;
80589
- wireframeMaterial.depthTest = true;
80590
- wireframeMaterial.depthFunc = FUNC_LESSEQUAL;
80591
- wireframeMaterial.depthWrite = false;
80592
- wireframeMaterial.cull = CULLFACE_NONE;
80593
- wireframeMaterial.update();
80594
- const wireframeInstance = new MeshInstance(mesh, wireframeMaterial);
80595
- wireframeInstance.drawOrder = 2;
80596
- const wireframeEntity = new Entity('CollisionWireframe');
80597
- wireframeEntity.addComponent('render', {
80598
- meshInstances: [wireframeInstance],
80599
- layers: [this.layer.id]
81950
+ events.on('navTarget:set', (pos, normal) => {
81951
+ const mode = state.cameraMode === 'walk' || state.cameraMode === 'fly' ?
81952
+ state.cameraMode : 'walk';
81953
+ this.setTarget(pos, normal, mode);
80600
81954
  });
80601
- wireframeEntity.render.renderStyle = RENDERSTYLE_WIREFRAME;
80602
- this.materials = [depthMaterial, surfaceMaterial, wireframeMaterial];
80603
- this.entity = new Entity('MeshCollisionDebug');
80604
- this.entity.addChild(depthEntity);
80605
- this.entity.addChild(surfaceEntity);
80606
- this.entity.addChild(wireframeEntity);
80607
- this.entity.enabled = false;
80608
- app.root.addChild(this.entity);
81955
+ events.on('navTarget:clear', () => {
81956
+ this.clearTarget();
81957
+ });
81958
+ events.on('orbitTarget:set', (pos, normal) => {
81959
+ this.navigating = false;
81960
+ this.setTarget(pos, normal, 'orbit');
81961
+ });
81962
+ events.on('orbitTarget:clear', () => {
81963
+ if (this.targetMode === 'orbit') {
81964
+ this.clearTarget();
81965
+ }
81966
+ });
81967
+ this.onPrerender = () => {
81968
+ this.updateTarget();
81969
+ };
81970
+ app.on('prerender', this.onPrerender);
81971
+ updateActive();
80609
81972
  }
80610
- set enabled(value) {
80611
- this._enabled = value;
80612
- this.entity.enabled = value;
80613
- // Disable the layer too — otherwise its render actions still execute
80614
- // each frame and the per-layer `clearDepthBuffer` would wipe depth
80615
- // even when no overlay meshes are submitted.
80616
- this.layer.enabled = value;
81973
+ setTarget(pos, normal, mode) {
81974
+ this.surfaceCursorVersion++;
81975
+ this.targetPos = pos.clone();
81976
+ this.targetNormal = normal.clone();
81977
+ this.targetMode = mode;
81978
+ this.hoverRing.hide();
81979
+ this.targetRing.hide();
80617
81980
  }
80618
- get enabled() {
80619
- return this._enabled;
81981
+ clearTarget() {
81982
+ const mode = this.targetMode;
81983
+ this.targetPos = null;
81984
+ this.targetNormal = null;
81985
+ this.targetMode = null;
81986
+ if (mode === 'orbit') {
81987
+ this.hoverRing.hide();
81988
+ }
81989
+ this.targetRing.hide();
81990
+ this.refreshSurfaceCursor();
80620
81991
  }
80621
- /**
80622
- * Re-bake and re-upload the per-vertex colors so the overlay stays
80623
- * correct if CameraFrame is destroyed or recreated at runtime (the
80624
- * gamma path differs between the two states).
80625
- *
80626
- * @param cameraFrameEnabled - whether CameraFrame is currently active.
80627
- */
80628
- setCameraFrameEnabled(cameraFrameEnabled) {
80629
- encodeFlatColors(this.triangles, cameraFrameEnabled, this.flatColors);
80630
- this.mesh.setColors32(this.flatColors);
80631
- this.mesh.update(PRIMITIVE_TRIANGLES);
81992
+ pickCollision(offsetX, offsetY) {
81993
+ if (!this.collision) {
81994
+ return null;
81995
+ }
81996
+ const { camera, collision } = this;
81997
+ const cameraPos = camera.getPosition();
81998
+ camera.camera.screenToWorld(offsetX, offsetY, 1.0, tmpV);
81999
+ tmpV.sub(cameraPos).normalize();
82000
+ const hit = collision.queryRay(cameraPos.x, cameraPos.y, cameraPos.z, tmpV.x, tmpV.y, tmpV.z, camera.camera.farClip);
82001
+ if (!hit) {
82002
+ return null;
82003
+ }
82004
+ const sn = collision.querySurfaceNormal(hit.x, hit.y, hit.z, tmpV.x, tmpV.y, tmpV.z);
82005
+ this.collisionTarget.position.set(hit.x, hit.y, hit.z);
82006
+ this.collisionTarget.normal.set(sn.nx, sn.ny, sn.nz);
82007
+ return this.collisionTarget;
82008
+ }
82009
+ async pickSceneTarget(offsetX, offsetY) {
82010
+ const collisionTarget = this.pickCollision(offsetX, offsetY);
82011
+ if (collisionTarget) {
82012
+ return collisionTarget;
82013
+ }
82014
+ const result = await this.picker.pickSurface(offsetX / this.canvas.clientWidth, offsetY / this.canvas.clientHeight);
82015
+ return result ?? null;
82016
+ }
82017
+ shouldShowSurfaceCursor() {
82018
+ const flyMouseCaptured = this.state.cameraMode === 'fly' &&
82019
+ this.state.inputMode === 'desktop' &&
82020
+ this.state.gamingControls;
82021
+ return this.active &&
82022
+ this.state.inputMode === 'desktop' &&
82023
+ this.hasSurfaceCursorPosition &&
82024
+ !this.navigating && ((this.state.cameraMode === 'fly' && !flyMouseCaptured) ||
82025
+ (this.state.cameraMode === 'orbit' && this.targetMode !== 'orbit'));
82026
+ }
82027
+ updateSurfaceCursor(offsetX, offsetY) {
82028
+ this.surfaceCursorX = offsetX;
82029
+ this.surfaceCursorY = offsetY;
82030
+ this.hasSurfaceCursorPosition = true;
82031
+ this.surfaceCursorVersion++;
82032
+ // Render immediately using the most recent depth sample, re-projecting
82033
+ // at the new pointer position. The async pick below will refresh the
82034
+ // sample.
82035
+ this.renderSurfaceCursor();
82036
+ if (!this.surfaceCursorPickPending) {
82037
+ this.processSurfaceCursor();
82038
+ }
82039
+ }
82040
+ renderSurfaceCursor() {
82041
+ if (!this.hasSurfaceSample || !this.shouldShowSurfaceCursor()) {
82042
+ this.hoverRing.hide();
82043
+ return;
82044
+ }
82045
+ const sample = this.surfaceSample;
82046
+ const position = getWorldPoint(sample.camera, this.surfaceCursorX, this.surfaceCursorY, sample.width, sample.height, sample.normalizedDepth, this.scratchHoverPos);
82047
+ if (!position) {
82048
+ this.hoverRing.hide();
82049
+ return;
82050
+ }
82051
+ this.hoverRing.render(position, sample.normal);
82052
+ }
82053
+ refreshSurfaceCursor() {
82054
+ if (this.hasSurfaceCursorPosition && this.shouldShowSurfaceCursor() && !this.surfaceCursorPickPending) {
82055
+ this.surfaceCursorVersion++;
82056
+ this.processSurfaceCursor();
82057
+ }
82058
+ }
82059
+ processSurfaceCursor() {
82060
+ this.surfaceCursorPickPending = true;
82061
+ const version = this.surfaceCursorVersion;
82062
+ // Capture the camera at pick fire time so the depth we extract from
82063
+ // the result is interpretable through the same view/projection. The
82064
+ // surface cursor only animates while the camera is static, so this
82065
+ // snapshot matches the camera the picker actually rendered with.
82066
+ captureCameraSnapshot(this.camera, this.surfaceSample.camera);
82067
+ const snapshotWidth = this.canvas.clientWidth;
82068
+ const snapshotHeight = this.canvas.clientHeight;
82069
+ this.pickSceneTarget(this.surfaceCursorX, this.surfaceCursorY).then((target) => {
82070
+ if (target) {
82071
+ this.surfaceSample.normalizedDepth = worldPointToDepth(this.surfaceSample.camera, target.position);
82072
+ this.surfaceSample.normal.copy(target.normal);
82073
+ this.surfaceSample.width = snapshotWidth;
82074
+ this.surfaceSample.height = snapshotHeight;
82075
+ this.hasSurfaceSample = this.surfaceSample.normalizedDepth >= 0;
82076
+ }
82077
+ else {
82078
+ this.hasSurfaceSample = false;
82079
+ }
82080
+ this.renderSurfaceCursor();
82081
+ }).catch(() => {
82082
+ if (version === this.surfaceCursorVersion) {
82083
+ this.hasSurfaceSample = false;
82084
+ this.hoverRing.hide();
82085
+ }
82086
+ }).finally(() => {
82087
+ this.surfaceCursorPickPending = false;
82088
+ if (version !== this.surfaceCursorVersion && this.shouldShowSurfaceCursor()) {
82089
+ this.processSurfaceCursor();
82090
+ }
82091
+ });
82092
+ }
82093
+ updateCursor(offsetX, offsetY) {
82094
+ if (!this.active || this.navigating) {
82095
+ this.hoverRing.hide();
82096
+ return;
82097
+ }
82098
+ if (this.state.cameraMode === 'orbit' && this.targetMode === 'orbit') {
82099
+ this.hoverRing.hide();
82100
+ return;
82101
+ }
82102
+ if (this.state.cameraMode === 'fly' || this.state.cameraMode === 'orbit') {
82103
+ this.updateSurfaceCursor(offsetX, offsetY);
82104
+ return;
82105
+ }
82106
+ const target = this.pickCollision(offsetX, offsetY);
82107
+ if (!target) {
82108
+ this.hoverRing.hide();
82109
+ return;
82110
+ }
82111
+ this.hoverRing.render(target.position, target.normal);
82112
+ }
82113
+ updateTarget() {
82114
+ if (!this.active || !this.targetPos || !this.targetNormal) {
82115
+ return;
82116
+ }
82117
+ const camPos = this.camera.getPosition();
82118
+ const dist = camPos.distance(this.targetPos);
82119
+ if (this.targetMode !== 'orbit' && dist < 2.0) {
82120
+ this.targetRing.hide();
82121
+ return;
82122
+ }
82123
+ this.targetRing.render(this.targetPos, this.targetNormal);
80632
82124
  }
80633
82125
  destroy() {
80634
- // Entity.destroy() removes child entities and tears down their render
80635
- // components, which destroy the MeshInstances and decref the shared
80636
- // Mesh (the last decref destroys its GPU buffers). Materials are not
80637
- // owned by MeshInstance so destroy them explicitly here.
80638
- this.entity?.destroy();
80639
- for (const m of this.materials)
80640
- m.destroy();
80641
- this.materials.length = 0;
80642
- this.app.scene.layers.remove(this.layer);
80643
- this.camera.camera.layers = this.camera.camera.layers.filter(id => id !== this.layer.id);
82126
+ this.app.off('prerender', this.onPrerender);
82127
+ this.canvas.removeEventListener('pointermove', this.onPointerMove);
82128
+ this.canvas.removeEventListener('pointerleave', this.onPointerLeave);
82129
+ this.svg.remove();
80644
82130
  }
80645
82131
  }
80646
82132
 
@@ -81274,232 +82760,6 @@ class VoxelDebugOverlay {
81274
82760
  }
81275
82761
  }
81276
82762
 
81277
- const SVGNS = 'http://www.w3.org/2000/svg';
81278
- const NUM_SAMPLES = 12;
81279
- const CIRCLE_OUTER_RADIUS = 0.2;
81280
- const CIRCLE_INNER_RADIUS = 0.17;
81281
- const BEZIER_K = 1 / 6;
81282
- const NORMAL_SMOOTH_FACTOR = 0.25;
81283
- const tmpV = new Vec3();
81284
- const tmpScreen = new Vec3();
81285
- const tangent = new Vec3();
81286
- const bitangent = new Vec3();
81287
- const worldPt = new Vec3();
81288
- const up = new Vec3(0, 1, 0);
81289
- const right = new Vec3(1, 0, 0);
81290
- const buildBezierRing = (sx, sy) => {
81291
- const n = sx.length;
81292
- let p = `M${sx[0].toFixed(1)},${sy[0].toFixed(1)}`;
81293
- for (let i = 0; i < n; i++) {
81294
- const i0 = (i - 1 + n) % n;
81295
- const i1 = i;
81296
- const i2 = (i + 1) % n;
81297
- const i3 = (i + 2) % n;
81298
- const cp1x = sx[i1] + (sx[i2] - sx[i0]) * BEZIER_K;
81299
- const cp1y = sy[i1] + (sy[i2] - sy[i0]) * BEZIER_K;
81300
- const cp2x = sx[i2] - (sx[i3] - sx[i1]) * BEZIER_K;
81301
- const cp2y = sy[i2] - (sy[i3] - sy[i1]) * BEZIER_K;
81302
- p += ` C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${sx[i2].toFixed(1)},${sy[i2].toFixed(1)}`;
81303
- }
81304
- return `${p} Z`;
81305
- };
81306
- class WalkCursor {
81307
- svg;
81308
- cursorPath;
81309
- targetPath;
81310
- app;
81311
- camera;
81312
- collision;
81313
- canvas;
81314
- active = false;
81315
- walking = false;
81316
- targetPos = null;
81317
- targetNormal = null;
81318
- smoothNx = 0;
81319
- smoothNy = 1;
81320
- smoothNz = 0;
81321
- hasSmoothedNormal = false;
81322
- onPointerMove;
81323
- onPointerLeave;
81324
- scratchX = new Float64Array(NUM_SAMPLES);
81325
- scratchY = new Float64Array(NUM_SAMPLES);
81326
- outerX = new Float64Array(NUM_SAMPLES);
81327
- outerY = new Float64Array(NUM_SAMPLES);
81328
- innerX = new Float64Array(NUM_SAMPLES);
81329
- innerY = new Float64Array(NUM_SAMPLES);
81330
- constructor(app, camera, collision, events, state) {
81331
- this.app = app;
81332
- this.camera = camera;
81333
- this.collision = collision;
81334
- this.canvas = app.graphicsDevice.canvas;
81335
- this.svg = document.createElementNS(SVGNS, 'svg');
81336
- this.svg.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:1';
81337
- this.canvas.parentElement.appendChild(this.svg);
81338
- // Hover cursor: thick ring
81339
- this.cursorPath = document.createElementNS(SVGNS, 'path');
81340
- this.cursorPath.setAttribute('fill', 'white');
81341
- this.cursorPath.setAttribute('fill-opacity', '0.6');
81342
- this.cursorPath.setAttribute('fill-rule', 'evenodd');
81343
- this.cursorPath.setAttribute('stroke', 'none');
81344
- this.svg.appendChild(this.cursorPath);
81345
- // Walk target: filled circle
81346
- this.targetPath = document.createElementNS(SVGNS, 'path');
81347
- this.targetPath.setAttribute('fill', 'white');
81348
- this.targetPath.setAttribute('fill-opacity', '0.5');
81349
- this.targetPath.setAttribute('stroke', 'none');
81350
- this.targetPath.style.display = 'none';
81351
- this.svg.appendChild(this.targetPath);
81352
- this.svg.style.display = 'none';
81353
- this.onPointerMove = (e) => {
81354
- if (e.pointerType === 'touch')
81355
- return;
81356
- if (e.buttons) {
81357
- this.cursorPath.style.display = 'none';
81358
- this.hasSmoothedNormal = false;
81359
- return;
81360
- }
81361
- this.updateCursor(e.offsetX, e.offsetY);
81362
- };
81363
- this.onPointerLeave = () => {
81364
- this.cursorPath.style.display = 'none';
81365
- this.hasSmoothedNormal = false;
81366
- };
81367
- this.canvas.addEventListener('pointermove', this.onPointerMove);
81368
- this.canvas.addEventListener('pointerleave', this.onPointerLeave);
81369
- const updateActive = () => {
81370
- this.active = state.cameraMode === 'walk' &&
81371
- !state.gamingControls;
81372
- if (!this.active) {
81373
- this.svg.style.display = 'none';
81374
- }
81375
- };
81376
- events.on('cameraMode:changed', updateActive);
81377
- events.on('gamingControls:changed', updateActive);
81378
- events.on('walkTo', () => {
81379
- this.walking = true;
81380
- this.cursorPath.style.display = 'none';
81381
- this.hasSmoothedNormal = false;
81382
- });
81383
- events.on('walkCancel', () => {
81384
- this.walking = false;
81385
- this.clearTarget();
81386
- });
81387
- events.on('walkComplete', () => {
81388
- this.walking = false;
81389
- this.clearTarget();
81390
- });
81391
- events.on('walkTarget:set', (pos, normal) => {
81392
- this.setTarget(pos, normal);
81393
- });
81394
- events.on('walkTarget:clear', () => {
81395
- this.clearTarget();
81396
- });
81397
- app.on('prerender', () => {
81398
- this.updateTarget();
81399
- });
81400
- updateActive();
81401
- }
81402
- setTarget(pos, normal) {
81403
- this.targetPos = pos.clone();
81404
- this.targetNormal = normal.clone();
81405
- }
81406
- clearTarget() {
81407
- this.targetPos = null;
81408
- this.targetNormal = null;
81409
- this.targetPath.style.display = 'none';
81410
- }
81411
- projectCircle(px, py, pz, nx, ny, nz, radius, outX, outY) {
81412
- const normal = tmpV.set(nx, ny, nz);
81413
- if (Math.abs(normal.y) < 0.99) {
81414
- tangent.cross(normal, up).normalize();
81415
- }
81416
- else {
81417
- tangent.cross(normal, right).normalize();
81418
- }
81419
- bitangent.cross(normal, tangent);
81420
- const cam = this.camera.camera;
81421
- const angleStep = (2 * Math.PI) / NUM_SAMPLES;
81422
- for (let i = 0; i < NUM_SAMPLES; i++) {
81423
- const theta = i * angleStep;
81424
- const ct = Math.cos(theta);
81425
- const st = Math.sin(theta);
81426
- const tx = ct * tangent.x + st * bitangent.x;
81427
- const ty = ct * tangent.y + st * bitangent.y;
81428
- const tz = ct * tangent.z + st * bitangent.z;
81429
- worldPt.set(px + tx * radius, py + ty * radius, pz + tz * radius);
81430
- cam.worldToScreen(worldPt, tmpScreen);
81431
- outX[i] = tmpScreen.x;
81432
- outY[i] = tmpScreen.y;
81433
- }
81434
- }
81435
- updateCursor(offsetX, offsetY) {
81436
- if (!this.active || this.walking) {
81437
- this.cursorPath.style.display = 'none';
81438
- this.hasSmoothedNormal = false;
81439
- return;
81440
- }
81441
- const { camera, collision } = this;
81442
- const cameraPos = camera.getPosition();
81443
- camera.camera.screenToWorld(offsetX, offsetY, 1.0, tmpV);
81444
- tmpV.sub(cameraPos).normalize();
81445
- const hit = collision.queryRay(cameraPos.x, cameraPos.y, cameraPos.z, tmpV.x, tmpV.y, tmpV.z, camera.camera.farClip);
81446
- if (!hit) {
81447
- this.cursorPath.style.display = 'none';
81448
- this.hasSmoothedNormal = false;
81449
- return;
81450
- }
81451
- const px = hit.x;
81452
- const py = hit.y;
81453
- const pz = hit.z;
81454
- const sn = collision.querySurfaceNormal(hit.x, hit.y, hit.z, tmpV.x, tmpV.y, tmpV.z);
81455
- let nx = sn.nx;
81456
- let ny = sn.ny;
81457
- let nz = sn.nz;
81458
- if (this.hasSmoothedNormal) {
81459
- const t = NORMAL_SMOOTH_FACTOR;
81460
- nx = this.smoothNx + (nx - this.smoothNx) * t;
81461
- ny = this.smoothNy + (ny - this.smoothNy) * t;
81462
- nz = this.smoothNz + (nz - this.smoothNz) * t;
81463
- const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
81464
- if (len > 1e-6) {
81465
- const invLen = 1.0 / len;
81466
- nx *= invLen;
81467
- ny *= invLen;
81468
- nz *= invLen;
81469
- }
81470
- }
81471
- this.smoothNx = nx;
81472
- this.smoothNy = ny;
81473
- this.smoothNz = nz;
81474
- this.hasSmoothedNormal = true;
81475
- this.projectCircle(px, py, pz, nx, ny, nz, CIRCLE_OUTER_RADIUS, this.outerX, this.outerY);
81476
- this.projectCircle(px, py, pz, nx, ny, nz, CIRCLE_INNER_RADIUS, this.innerX, this.innerY);
81477
- this.cursorPath.setAttribute('d', `${buildBezierRing(this.outerX, this.outerY)} ${buildBezierRing(this.innerX, this.innerY)}`);
81478
- this.cursorPath.style.display = '';
81479
- this.svg.style.display = '';
81480
- }
81481
- updateTarget() {
81482
- if (!this.active || !this.targetPos || !this.targetNormal) {
81483
- return;
81484
- }
81485
- const camPos = this.camera.getPosition();
81486
- const dist = camPos.distance(this.targetPos);
81487
- if (dist < 2.0) {
81488
- this.targetPath.style.display = 'none';
81489
- return;
81490
- }
81491
- this.projectCircle(this.targetPos.x, this.targetPos.y, this.targetPos.z, this.targetNormal.x, this.targetNormal.y, this.targetNormal.z, CIRCLE_OUTER_RADIUS, this.scratchX, this.scratchY);
81492
- this.targetPath.setAttribute('d', buildBezierRing(this.scratchX, this.scratchY));
81493
- this.targetPath.style.display = '';
81494
- this.svg.style.display = '';
81495
- }
81496
- destroy() {
81497
- this.canvas.removeEventListener('pointermove', this.onPointerMove);
81498
- this.canvas.removeEventListener('pointerleave', this.onPointerLeave);
81499
- this.svg.remove();
81500
- }
81501
- }
81502
-
81503
82763
  // String.replace wrapper that warns when the source substring is missing, so
81504
82764
  // shader chunk patches against the engine fail loudly instead of silently
81505
82765
  // producing the original chunk.
@@ -81602,11 +82862,12 @@ class Viewer {
81602
82862
  cameraFrame;
81603
82863
  inputController;
81604
82864
  cameraManager;
82865
+ picker;
81605
82866
  annotations;
81606
82867
  forceRenderNextFrame = false;
81607
82868
  voxelOverlay = null;
81608
82869
  meshOverlay = null;
81609
- walkCursor = null;
82870
+ navCursor = null;
81610
82871
  origChunks;
81611
82872
  constructor(global, gsplatLoad, skyboxLoad, collisionLoad) {
81612
82873
  this.global = global;
@@ -81750,7 +83011,8 @@ class Viewer {
81750
83011
  if (!config.noui) {
81751
83012
  this.annotations = new Annotations(global, this.cameraFrame != null);
81752
83013
  }
81753
- this.inputController = new InputController(global);
83014
+ this.picker = new Picker(app, camera);
83015
+ this.inputController = new InputController(global, this.picker);
81754
83016
  this.inputController.collision = collision ?? null;
81755
83017
  state.hasCollision = !!collision;
81756
83018
  // Create collision debug overlay (voxel uses a compute shader, mesh
@@ -81774,8 +83036,8 @@ class Viewer {
81774
83036
  }
81775
83037
  this.cameraManager = new CameraManager(global, sceneBound, collision);
81776
83038
  applyCamera(this.cameraManager.camera);
81777
- if (collision) {
81778
- this.walkCursor = new WalkCursor(app, camera, collision, events, state);
83039
+ if (!config.noui) {
83040
+ this.navCursor = new NavCursor(app, camera, collision ?? null, events, state, this.picker);
81779
83041
  }
81780
83042
  const { instance } = gsplat;
81781
83043
  if (instance) {
@@ -81810,22 +83072,27 @@ class Viewer {
81810
83072
  high: 4
81811
83073
  }
81812
83074
  };
81813
- const getBudget = () => {
81814
- if (config.budget !== undefined && Number.isFinite(config.budget) && config.budget > 0) {
81815
- return config.budget;
81816
- }
81817
- const quality = platform.mobile ? budgets.mobile : budgets.desktop;
81818
- return state.performanceMode ? quality.low : quality.high;
83075
+ const applyPerfSettings = () => {
83076
+ const budget = () => {
83077
+ if (config.budget !== undefined && Number.isFinite(config.budget) && config.budget > 0) {
83078
+ return config.budget;
83079
+ }
83080
+ const quality = platform.mobile ? budgets.mobile : budgets.desktop;
83081
+ return state.performanceMode ? quality.low : quality.high;
83082
+ };
83083
+ gsplat.splatBudget = budget() * 1000000;
83084
+ gsplat.lodRangeMin = 0;
83085
+ gsplat.lodRangeMax = 1000;
83086
+ gsplat.colorUpdateAngle = state.performanceMode ? 4 : 2;
81819
83087
  };
81820
83088
  if (config.fullload) {
81821
83089
  // reveal once full quality has finished loading (used for screenshots)
81822
- gsplat.splatBudget = getBudget() * 1000000;
81823
- gsplat.lodRangeMin = 0;
81824
- gsplat.lodRangeMax = 1000;
83090
+ applyPerfSettings();
81825
83091
  }
81826
83092
  else {
81827
83093
  // reveal once low lod has loaded for fastest possible reveal
81828
- const lodLevels = results[0].gsplat.resource?.octree?.lodLevels;
83094
+ const resource = results[0].gsplat.resource;
83095
+ const lodLevels = resource?.octree?.lodLevels;
81829
83096
  if (lodLevels) {
81830
83097
  gsplat.lodRangeMax = gsplat.lodRangeMin = lodLevels - 1;
81831
83098
  }
@@ -81861,13 +83128,8 @@ class Viewer {
81861
83128
  eventHandler.off('frame:ready', readyHandler);
81862
83129
  state.readyToRender = true;
81863
83130
  // handle quality mode changes
81864
- const updateLod = () => {
81865
- gsplat.splatBudget = getBudget() * 1000000;
81866
- gsplat.lodRangeMin = 0;
81867
- gsplat.lodRangeMax = 1000;
81868
- };
81869
- events.on('performanceMode:changed', updateLod);
81870
- updateLod();
83131
+ events.on('performanceMode:changed', applyPerfSettings);
83132
+ applyPerfSettings();
81871
83133
  // debug colorize lods
81872
83134
  gsplat.debug = config.colorize ? GSPLAT_DEBUG_LOD : GSPLAT_DEBUG_NONE;
81873
83135
  gsplat.renderer = rendererTable[config.renderer];
@@ -82863,7 +84125,7 @@ const initXr = (global) => {
82863
84125
  });
82864
84126
  };
82865
84127
 
82866
- var version = "1.21.0";
84128
+ var version = "1.22.1";
82867
84129
 
82868
84130
  const loadGsplat = async (app, config, progressCallback) => {
82869
84131
  const { contents, contentUrl, aa } = config;