@playcanvas/supersplat-viewer 1.32.0 → 1.33.0

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/dist/viewer.js CHANGED
@@ -2621,7 +2621,7 @@ const importSettings = (settings) => {
2621
2621
  return result;
2622
2622
  };
2623
2623
 
2624
- var version = "1.32.0";
2624
+ var version = "1.33.0";
2625
2625
 
2626
2626
  class Tooltip {
2627
2627
  register;
@@ -4915,9 +4915,30 @@ class SphereMover {
4915
4915
  }
4916
4916
  }
4917
4917
 
4918
- /** Maximum Euclidean distance (metres) from the spawn origin to search for a valid placement. */
4918
+ /**
4919
+ * Maximum Euclidean distance (metres) from the spawn origin to search for a valid placement.
4920
+ * Used by the cylinder search, which has to reach far enough to find a standable floor. The
4921
+ * sphere search sizes itself from its own radius instead — see `SPHERE_SEARCH_REACH_RADII`.
4922
+ */
4919
4923
  const SEARCH_RADIUS = 5;
4920
4924
  const SEARCH_RADIUS_SQ = SEARCH_RADIUS * SEARCH_RADIUS;
4925
+ /**
4926
+ * Reach of the sphere search, in multiples of the sphere's radius.
4927
+ *
4928
+ * Its job is to un-clip a sphere that is intersecting a surface, not to relocate one that is deep
4929
+ * inside geometry — `FlyController` holds collision until the camera is clear rather than relying
4930
+ * on a rescue — so reaching a few radii is enough. Bounding the reach is what makes the search
4931
+ * cheap: at radius 0.2 on a 0.05 m grid the worst case, finding nothing, is 7,153 probes, where
4932
+ * reaching `SEARCH_RADIUS` cost 8,120,601. A sphere deep inside geometry never finds a free cell
4933
+ * to tighten `bestDistSq`, so nothing breaks the search early and it pays for every shell.
4934
+ *
4935
+ * The lattice still steps by `collision.voxelResolution`, deliberately. A coarser step is not
4936
+ * safe: the valid positions for a collider's centre are free space eroded by its radius, which
4937
+ * can be far narrower than the free space itself. A 0.45 m passage admits a 0.2 m sphere across
4938
+ * only a 0.05 m band of centres, so a 0.1 m lattice steps straight over it and reports no
4939
+ * placement at all.
4940
+ */
4941
+ const SPHERE_SEARCH_REACH_RADII = 3;
4921
4942
  /** Ray budget when probing for ground/ceiling under or above a candidate column. */
4922
4943
  const RAY_MAX_DIST = 1000;
4923
4944
  // Scratch values reused across calls — these helpers run only at spawn time
@@ -4930,7 +4951,8 @@ const scratchPush = { x: 0, y: 0, z: 0 };
4930
4951
  *
4931
4952
  * Lattice search across voxel-spaced offsets from the origin (step =
4932
4953
  * `collision.voxelResolution`), ordered by Chebyshev shell with Euclidean
4933
- * tie-break within a shell. Search bounded by `SEARCH_RADIUS`.
4954
+ * tie-break within a shell. Reach is derived from `radius` — see
4955
+ * `SPHERE_SEARCH_REACH_RADII`.
4934
4956
  *
4935
4957
  * @param collision - Active collision implementation.
4936
4958
  * @param ox - Origin X (world space).
@@ -4942,7 +4964,9 @@ const scratchPush = { x: 0, y: 0, z: 0 };
4942
4964
  */
4943
4965
  const findSphereSpawn = (collision, ox, oy, oz, radius, out) => {
4944
4966
  const step = collision.voxelResolution;
4945
- const maxCells = Math.ceil(SEARCH_RADIUS / step);
4967
+ const reach = radius * SPHERE_SEARCH_REACH_RADII;
4968
+ const reachSq = reach * reach;
4969
+ const maxCells = Math.ceil(reach / step);
4946
4970
  let bestDistSq = Infinity;
4947
4971
  let found = false;
4948
4972
  for (let r = 0; r <= maxCells; r++) {
@@ -4953,13 +4977,16 @@ const findSphereSpawn = (collision, ox, oy, oz, radius, out) => {
4953
4977
  const absDy = dy < 0 ? -dy : dy;
4954
4978
  for (let dz = -r; dz <= r; dz++) {
4955
4979
  const absDz = dz < 0 ? -dz : dz;
4956
- for (let dx = -r; dx <= r; dx++) {
4957
- const absDx = dx < 0 ? -dx : dx;
4958
- // Only cells on the Chebyshev shell of radius r.
4959
- if (absDx < r && absDy < r && absDz < r)
4960
- continue;
4980
+ // Enumerate the Chebyshev shell of radius r directly instead of scanning the
4981
+ // whole cube and skipping its interior. A row is fully on the shell when dy or dz
4982
+ // is already at the extreme; otherwise only its two end cells are, so dx jumps
4983
+ // straight across the interior. `full` is always true at r = 0, so the stride is
4984
+ // never zero.
4985
+ const full = absDy === r || absDz === r;
4986
+ const dxStep = full ? 1 : 2 * r;
4987
+ for (let dx = -r; dx <= r; dx += dxStep) {
4961
4988
  const distSq = (dx * dx + dy * dy + dz * dz) * step * step;
4962
- if (distSq >= bestDistSq || distSq > SEARCH_RADIUS_SQ)
4989
+ if (distSq >= bestDistSq || distSq > reachSq)
4963
4990
  continue;
4964
4991
  const cx = ox + dx * step;
4965
4992
  const cy = oy + dy * step;
@@ -5027,10 +5054,11 @@ const findCylinderSpawn = (collision, ox, oy, oz, halfHeight, radius, out) => {
5027
5054
  const absDy = dy < 0 ? -dy : dy;
5028
5055
  for (let dz = -r; dz <= r; dz++) {
5029
5056
  const absDz = dz < 0 ? -dz : dz;
5030
- for (let dx = -r; dx <= r; dx++) {
5031
- const absDx = dx < 0 ? -dx : dx;
5032
- if (absDx < r && absDy < r && absDz < r)
5033
- continue;
5057
+ // Enumerate the Chebyshev shell of radius r directly rather than scanning the
5058
+ // whole cube and skipping its interior — see `findSphereSpawn`.
5059
+ const full = absDy === r || absDz === r;
5060
+ const dxStep = full ? 1 : 2 * r;
5061
+ for (let dx = -r; dx <= r; dx += dxStep) {
5034
5062
  const distSq = (dx * dx + dy * dy + dz * dz) * step * step;
5035
5063
  if (distSq >= bestDistSq || distSq > SEARCH_RADIUS_SQ)
5036
5064
  continue;
@@ -5093,6 +5121,9 @@ const right$2 = new Vec3();
5093
5121
  const up$1 = new Vec3();
5094
5122
  const offset$1 = new Vec3();
5095
5123
  const spawnProbe$1 = new Vec3();
5124
+ const clearProbe = { x: 0, y: 0, z: 0 };
5125
+ // Whether the camera sphere fits at `position` without intersecting collision geometry.
5126
+ const isClear = (collision, position) => !collision.querySphere(position.x, position.y, position.z, CAMERA_RADIUS, clearProbe);
5096
5127
  class FlyController {
5097
5128
  fov = 90;
5098
5129
  rotateDamping = DEFAULT_CONTROLLER_DAMPING;
@@ -5102,24 +5133,73 @@ class FlyController {
5102
5133
  _distance = 1;
5103
5134
  _spawn = new SpawnState();
5104
5135
  _mover = new SphereMover(CAMERA_RADIUS);
5136
+ // Collision that arrived while the camera was inside geometry, held until it is somewhere
5137
+ // valid. See the `collision` setter.
5138
+ _pendingCollision = null;
5139
+ // False until `goto` seeds `_position` from a real camera. Collision is normally attached
5140
+ // before this controller has ever been entered, and testing clearance against an unseeded
5141
+ // position would hold the attachment for no reason and skip the spawn search in `onEnter`.
5142
+ _hasPosition = false;
5105
5143
  /** Optional collision for sphere collision with sliding */
5106
5144
  set collision(value) {
5145
+ // The viewer reveals the scene before the collision data has downloaded, so fly mode has
5146
+ // no collision response until it lands and the camera may already be inside geometry by
5147
+ // then. The mover cannot escape a solid region: push-out has nothing to push against and
5148
+ // `_clipMove` cancels the movement every frame, so the camera sticks. Hold the
5149
+ // attachment until the camera is somewhere valid and let `update` engage it, which keeps
5150
+ // the flight the user is already making instead of teleporting them out. `onEnter` falls
5151
+ // back to the same hold when its spawn search cannot place the camera.
5152
+ if (value && this._hasPosition && !isClear(value, this._position)) {
5153
+ this._pendingCollision = value;
5154
+ // Detaching the mover is part of holding, not an optimisation. Left engaged it keeps
5155
+ // running push-out against geometry it cannot escape; and without the reset,
5156
+ // `SphereMover`'s last-clear position still points wherever the camera was before,
5157
+ // so `resolve` teleports it back there on the next idle step.
5158
+ this._mover.collision = null;
5159
+ this._mover.reset(this._position);
5160
+ return;
5161
+ }
5162
+ this._pendingCollision = null;
5107
5163
  this._mover.collision = value;
5108
5164
  this._mover.reset(this._position);
5109
5165
  }
5110
5166
  get collision() {
5111
5167
  return this._mover.collision;
5112
5168
  }
5169
+ /**
5170
+ * Re-run the engage-or-hold decision at the camera's current position, whether collision is
5171
+ * currently engaged or held. The invariant behind the setter: collision is never active while
5172
+ * the camera is inside a collider, because the mover cannot escape one.
5173
+ */
5174
+ _reengage() {
5175
+ this.collision = this._mover.collision ?? this._pendingCollision;
5176
+ }
5113
5177
  onEnter(camera) {
5114
5178
  this.goto(camera);
5115
- if (this.collision &&
5116
- findSphereSpawn(this.collision, this._position.x, this._position.y, this._position.z, CAMERA_RADIUS, spawnProbe$1)) {
5117
- this._position.copy(spawnProbe$1);
5118
- this._mover.reset(this._position);
5179
+ // Entry may follow a previous one that ended with collision held, so start from the
5180
+ // collision we have either way and drop that hold. Otherwise the block below would be
5181
+ // skipped on re-entry, leaving the spawn search unrun. Whether to hold again is decided
5182
+ // fresh, from this entry's position. Mirrors `WalkController.onEnter`.
5183
+ const collision = this._mover.collision ?? this._pendingCollision;
5184
+ this._pendingCollision = null;
5185
+ if (collision) {
5186
+ if (findSphereSpawn(collision, this._position.x, this._position.y, this._position.z, CAMERA_RADIUS, spawnProbe$1)) {
5187
+ this._position.copy(spawnProbe$1);
5188
+ }
5189
+ // Engage at the placed position. The search starts at the camera's own cell, so
5190
+ // failing it means the camera is inside geometry with no free space within reach to
5191
+ // nudge it to; the setter holds collision in that case and `update` engages it once
5192
+ // the camera is clear, as it does for a late attachment. Assigning rather than
5193
+ // resetting the mover inline keeps the engage-or-hold decision in one place.
5194
+ this.collision = collision;
5119
5195
  }
5120
5196
  this._storeSpawn();
5121
5197
  }
5122
5198
  update(deltaTime, inputFrame, camera) {
5199
+ // engage a held attachment as soon as the camera flies back into valid space
5200
+ if (this._pendingCollision && isClear(this._pendingCollision, this._position)) {
5201
+ this._reengage();
5202
+ }
5123
5203
  const { move, rotate } = inputFrame.read();
5124
5204
  applyFrameRotation(this._targetAngles, rotate);
5125
5205
  dampAngles(this._angles, this._targetAngles, this.rotateDamping, deltaTime);
@@ -5133,6 +5213,7 @@ class FlyController {
5133
5213
  // no cleanup needed
5134
5214
  }
5135
5215
  goto(camera) {
5216
+ this._hasPosition = true;
5136
5217
  this._position.copy(camera.position);
5137
5218
  this._angles.set(camera.angles.x, camera.angles.y, 0);
5138
5219
  this._targetAngles.copy(this._angles);
@@ -5145,7 +5226,13 @@ class FlyController {
5145
5226
  }
5146
5227
  this._distance = this._spawn.restore(this._position, this._angles);
5147
5228
  this._targetAngles.copy(this._angles);
5148
- this._mover.reset(this._position);
5229
+ // A spawn captured while collision was held is itself inside geometry — `onEnter` stores
5230
+ // the entry pose whether or not its search could place the camera. Restoring it with
5231
+ // collision engaged would put the camera straight back into the stuck state, so re-run
5232
+ // the decision instead of assuming the stored pose is valid. This also covers a spawn
5233
+ // that was valid when stored and is not now, after a collision swap. `_reengage` resets
5234
+ // the mover, which is why the explicit reset is gone.
5235
+ this._reengage();
5149
5236
  camera.position.copy(this._position);
5150
5237
  camera.angles.copy(this._angles);
5151
5238
  camera.distance = this._distance;
@@ -5440,10 +5527,6 @@ const spawnProbe = new Vec3();
5440
5527
  * collision handles walls and obstacles. When airborne, normal gravity applies.
5441
5528
  */
5442
5529
  class WalkController {
5443
- /**
5444
- * Optional collision for capsule collision with sliding
5445
- */
5446
- collision = null;
5447
5530
  /**
5448
5531
  * Field of view in degrees for walk mode.
5449
5532
  */
@@ -5519,12 +5602,63 @@ class WalkController {
5519
5602
  _grounded = false;
5520
5603
  _jumping = false;
5521
5604
  _jumpHeld = false;
5605
+ _collision = null;
5606
+ /**
5607
+ * Collision held because the capsule is inside geometry, mirroring `FlyController`. While
5608
+ * held, `_heldFloorY` stands in for the ground probe so the camera walks on the level it
5609
+ * entered at instead of falling, and the capsule check is skipped. `_step` engages it for
5610
+ * real as soon as the capsule fits.
5611
+ */
5612
+ _pendingCollision = null;
5613
+ /**
5614
+ * Synthetic ground height. Set while `_pendingCollision` is held, and while walk mode is
5615
+ * active with no collision at all: the viewer attaches collision after the scene is
5616
+ * interactive, so a host can enter walk before the data has arrived.
5617
+ */
5618
+ _heldFloorY = null;
5619
+ // False until `goto` seeds `_position` from a real camera, so an attach before this
5620
+ // controller has ever been entered engages directly instead of testing clearance against an
5621
+ // unseeded position.
5622
+ _hasPosition = false;
5623
+ /**
5624
+ * Optional collision for capsule collision with sliding. Assigning while the capsule is
5625
+ * inside geometry holds the attachment instead: engaged collision cannot escape a solid
5626
+ * region, so the capsule keeps the synthetic floor and `_step` engages it once it fits.
5627
+ * Collision normally lands this way, after walk mode may already be active.
5628
+ */
5629
+ set collision(value) {
5630
+ if (value && this._hasPosition && !this._capsuleClear(value, this._position)) {
5631
+ this._pendingCollision = value;
5632
+ this._collision = null;
5633
+ this._heldFloorY = this._position.y - this.eyeHeight - this.hoverHeight;
5634
+ return;
5635
+ }
5636
+ this._pendingCollision = null;
5637
+ this._heldFloorY = null;
5638
+ this._collision = value;
5639
+ }
5640
+ get collision() {
5641
+ return this._collision;
5642
+ }
5522
5643
  onEnter(camera) {
5523
5644
  this.goto(camera);
5524
- if (this.collision) {
5525
- // Spawn is scoped to this walk-mode entry; reset so a stale spawn
5526
- // from a previous entry can't be restored if this entry fails.
5527
- this._spawn.clear();
5645
+ // Spawn is scoped to this walk-mode entry; reset so a stale spawn from a previous entry
5646
+ // can't be restored if this entry fails or has no collision to place against.
5647
+ this._spawn.clear();
5648
+ // Entry may follow a previous one that ended with collision held, so start from the
5649
+ // collision we have either way. Whether to hold again is decided fresh, from this
5650
+ // entry's position.
5651
+ const collision = this._collision ?? this._pendingCollision;
5652
+ // Stand on the entry level until collision can place the capsule. This covers collision
5653
+ // that has not arrived yet as well as a spawn search that finds nowhere to go: engaged
5654
+ // collision would strand the camera either way, with no floor under the ground probe and
5655
+ // nothing for push-out to push against. Held, the user can walk out the way they came,
5656
+ // and the setter or `_step` engages collision once the capsule fits.
5657
+ this._pendingCollision = null;
5658
+ this._collision = null;
5659
+ this._heldFloorY = this._position.y - this.eyeHeight - this.hoverHeight;
5660
+ this._grounded = true;
5661
+ if (collision) {
5528
5662
  // Treat the walk capsule as a tight-superset cylinder for spawn.
5529
5663
  // The carve was produced with a separable XYZ dilation (flat ends,
5530
5664
  // no hemispheres), so cylinder math matches the data exactly.
@@ -5532,16 +5666,24 @@ class WalkController {
5532
5666
  // check accounts for the placed capsule's full vertical envelope:
5533
5667
  // foot sits at `floor + hoverHeight`, head at `floor + hoverHeight
5534
5668
  // + capsuleHeight`.
5535
- if (findCylinderSpawn(this.collision, camera.position.x, camera.position.y, camera.position.z, (this.capsuleHeight + this.hoverHeight) * 0.5, this.capsuleRadius, spawnProbe)) {
5669
+ if (findCylinderSpawn(collision, camera.position.x, camera.position.y, camera.position.z, (this.capsuleHeight + this.hoverHeight) * 0.5, this.capsuleRadius, spawnProbe)) {
5536
5670
  // spawnProbe is the floor world position the cylinder rests
5537
5671
  // on. Eye sits hoverHeight + eyeHeight above the floor.
5538
5672
  this._position.set(spawnProbe.x, spawnProbe.y + this.hoverHeight + this.eyeHeight, spawnProbe.z);
5539
- this._grounded = true;
5540
- this._velocity.y = 0;
5541
5673
  this._storeSpawn();
5674
+ // The placement is known to fit, so engage directly rather than re-testing it
5675
+ // through the setter's capsule query, which is a different test from the
5676
+ // cylinder search and could hold on a hairline disagreement.
5677
+ this._heldFloorY = null;
5678
+ this._collision = collision;
5679
+ }
5680
+ else {
5681
+ // No placement within reach. The setter holds if the capsule is inside geometry
5682
+ // and engages otherwise, which is what `_step` would do on its first step anyway.
5683
+ this.collision = collision;
5542
5684
  }
5543
- this._prevPosition.copy(this._position);
5544
5685
  }
5686
+ this._prevPosition.copy(this._position);
5545
5687
  }
5546
5688
  update(deltaTime, inputFrame, camera) {
5547
5689
  const { move, rotate } = inputFrame.read();
@@ -5575,6 +5717,12 @@ class WalkController {
5575
5717
  camera.fov = this.fov;
5576
5718
  }
5577
5719
  _step(dt, move) {
5720
+ // engage a held attachment as soon as the capsule reaches space it fits in
5721
+ if (this._pendingCollision && this._capsuleClear(this._pendingCollision, this._position)) {
5722
+ this._collision = this._pendingCollision;
5723
+ this._pendingCollision = null;
5724
+ this._heldFloorY = null;
5725
+ }
5578
5726
  // ground probe: cast a ray downward to find the terrain surface
5579
5727
  const groundY = this._probeGround(this._position);
5580
5728
  const hasGround = groundY !== null;
@@ -5635,6 +5783,7 @@ class WalkController {
5635
5783
  */
5636
5784
  goto(camera) {
5637
5785
  // position
5786
+ this._hasPosition = true;
5638
5787
  this._position.copy(camera.position);
5639
5788
  this._prevPosition.copy(this._position);
5640
5789
  // angles (clamp pitch to avoid gimbal lock)
@@ -5679,6 +5828,18 @@ class WalkController {
5679
5828
  this._pendingMove[2] = 0;
5680
5829
  this._accumulator = 0;
5681
5830
  }
5831
+ /**
5832
+ * Whether the walk capsule fits at `pos` without intersecting collision geometry.
5833
+ *
5834
+ * @param collision - Collision to test against.
5835
+ * @param pos - Eye position in PlayCanvas world space.
5836
+ * @returns True if the capsule is clear.
5837
+ */
5838
+ _capsuleClear(collision, pos) {
5839
+ const center = pos.y - this.eyeHeight + this.capsuleHeight * 0.5;
5840
+ const half = this.capsuleHeight * 0.5 - this.capsuleRadius;
5841
+ return !collision.queryCapsule(pos.x, center, pos.z, half, this.capsuleRadius, out);
5842
+ }
5682
5843
  /**
5683
5844
  * Cast multiple rays downward to find the average ground surface height.
5684
5845
  * Uses 5 rays (center + 4 cardinal at capsule radius) to spatially filter
@@ -5688,6 +5849,10 @@ class WalkController {
5688
5849
  * @returns Average ground surface Y in PlayCanvas space, or null if no ground found.
5689
5850
  */
5690
5851
  _probeGround(pos) {
5852
+ // While collision is held the real surface is unreachable, so stand on the level the
5853
+ // camera entered at. Without this the camera reads as airborne and falls.
5854
+ if (this._heldFloorY !== null)
5855
+ return this._heldFloorY;
5691
5856
  if (!this.collision)
5692
5857
  return null;
5693
5858
  const oy = pos.y - this.eyeHeight;
@@ -5722,6 +5887,8 @@ class WalkController {
5722
5887
  * @param disp - Pre-allocated vector to receive the collision push-out displacement.
5723
5888
  */
5724
5889
  _checkCollision(pos, disp) {
5890
+ if (!this.collision)
5891
+ return;
5725
5892
  const center = pos.y - this.eyeHeight + this.capsuleHeight * 0.5;
5726
5893
  const half = this.capsuleHeight * 0.5 - this.capsuleRadius;
5727
5894
  if (this.collision.queryCapsule(pos.x, center, pos.z, half, this.capsuleRadius, out)) {
@@ -5879,11 +6046,16 @@ class CameraManager {
5879
6046
  // mutating `camera` and/or `state.cameraMode` to make the change
5880
6047
  // visible instantly.
5881
6048
  snap;
6049
+ // Attach (or clear) collision after construction. The viewer reveals the scene without
6050
+ // waiting for collision data, which can be larger than the splats themselves, so this
6051
+ // arrives late. It re-tests whether walk mode is allowed, which gates the walk toggle
6052
+ // and the mode the camera falls back to when an animation is interrupted.
6053
+ setCollision;
5882
6054
  // holds the camera state
5883
6055
  camera = new Camera();
5884
6056
  constructor(global, bbox, collision = null) {
5885
6057
  const { events, settings, state } = global;
5886
- const walkAllowed = isWalkAllowed(bbox, collision);
6058
+ let walkAllowed = isWalkAllowed(bbox, collision);
5887
6059
  const camera0 = settings.cameras[0]?.initial;
5888
6060
  const defaultFov = camera0?.fov ?? DEFAULT_CAMERA_FOV;
5889
6061
  const frameCamera = createFrameCamera(bbox, defaultFov);
@@ -5939,8 +6111,10 @@ class CameraManager {
5939
6111
  this.camera.copy(resetCamera);
5940
6112
  const target = new Camera(this.camera); // the active controller updates this
5941
6113
  const from = new Camera(this.camera); // stores the previous camera state during transition
5942
- const defaultMode = isObjectExperience ? 'orbit' : walkAllowed ? 'walk' : 'fly';
5943
- let fromMode = defaultMode;
6114
+ const defaultMode = () => (isObjectExperience ? 'orbit' : walkAllowed ? 'walk' : 'fly');
6115
+ // null until the first mode change, so the fallback tracks `walkAllowed` if collision
6116
+ // attaches before the user has moved
6117
+ let fromMode = null;
5944
6118
  // tracks the mode to restore when exiting walk
5945
6119
  let preWalkMode = isObjectExperience ? 'orbit' : 'fly';
5946
6120
  // enter the initial controller
@@ -5954,6 +6128,11 @@ class CameraManager {
5954
6128
  from.copy(this.camera);
5955
6129
  transitionTimer = 0;
5956
6130
  };
6131
+ this.setCollision = (value) => {
6132
+ controllers.fly.collision = value;
6133
+ controllers.walk.collision = value;
6134
+ walkAllowed = isWalkAllowed(bbox, value);
6135
+ };
5957
6136
  this.snap = () => {
5958
6137
  getController(state.cameraMode).onEnter(this.camera);
5959
6138
  target.copy(this.camera);
@@ -6030,7 +6209,9 @@ class CameraManager {
6030
6209
  }
6031
6210
  break;
6032
6211
  case 'requestFirstPerson':
6033
- state.cameraMode = 'fly';
6212
+ // movement input from a non-first-person mode: walk where the scene allows
6213
+ // it, fly otherwise, the same preference as the animation fallback
6214
+ state.cameraMode = walkAllowed ? 'walk' : 'fly';
6034
6215
  break;
6035
6216
  case 'toggleWalk':
6036
6217
  if (walkAllowed) {
@@ -6049,12 +6230,12 @@ class CameraManager {
6049
6230
  break;
6050
6231
  case 'cancel':
6051
6232
  if (state.cameraMode === 'anim') {
6052
- state.cameraMode = fromMode;
6233
+ state.cameraMode = fromMode ?? defaultMode();
6053
6234
  }
6054
6235
  break;
6055
6236
  case 'interrupt':
6056
6237
  if (state.cameraMode === 'anim') {
6057
- state.cameraMode = fromMode;
6238
+ state.cameraMode = fromMode ?? defaultMode();
6058
6239
  }
6059
6240
  break;
6060
6241
  }
@@ -6875,7 +7056,7 @@ class ModeShortcuts {
6875
7056
  default:
6876
7057
  if (isWasdKey(event) && state.inputMode === 'desktop') {
6877
7058
  if (!isCaptureMode$1(state.cameraMode)) {
6878
- state.cameraMode = 'fly';
7059
+ events.fire('inputEvent', 'requestFirstPerson');
6879
7060
  }
6880
7061
  if (!state.gamingControls) {
6881
7062
  state.gamingControls = true;
@@ -8457,6 +8638,9 @@ class NavCursor {
8457
8638
  hoverRing;
8458
8639
  targetRing;
8459
8640
  camera;
8641
+ // Settable after construction: the viewer reveals the scene before the collision data has
8642
+ // downloaded, so this arrives late. Ring sizing reads `state.walkAllowed` live, so only the
8643
+ // pick path needs updating here.
8460
8644
  collision;
8461
8645
  canvas;
8462
8646
  state;
@@ -9313,12 +9497,10 @@ const MAX_STEPS: u32 = 512u;
9313
9497
  // Target wireframe edge width in pixels
9314
9498
  const EDGE_PIXELS: f32 = 1.5;
9315
9499
 
9316
- // Wireframe edge alpha (1.0 = pure black opaque edges, matching the mesh
9317
- // overlay's wireframe pass).
9500
+ // Keep edges tinted so dense grids retain the solid/free-space distinction.
9318
9501
  const EDGE_ALPHA: f32 = 0.8;
9319
9502
 
9320
- // Interior fill alpha (matching the mesh overlay's surface alpha).
9321
- const FILL_ALPHA: f32 = 0.30;
9503
+ const FILL_ALPHA: f32 = 0.4;
9322
9504
 
9323
9505
  struct Uniforms {
9324
9506
  invVP: mat4x4<f32>,
@@ -9427,10 +9609,9 @@ fn edgeFactor(hitPos: vec3f, voxMin: vec3f, voxSize: f32, edgeWidth: f32) -> f32
9427
9609
  return 1.0 - smoothstep(0.0, edgeWidth, edgeDist);
9428
9610
  }
9429
9611
 
9430
- // Shade a voxel hit, returning premultiplied RGBA. Uses the same face-axis
9431
- // grayscale palette as the mesh collision overlay (0.85 / 0.55 / 0.30 by
9432
- // dominant axis), with pure black at face edges to mimic that overlay's
9433
- // wireframe pass.
9612
+ // Shade by the camera's occupancy: gray in free space, orange inside solid
9613
+ // voxels (where the ray-march is inverted to find the exit into free space).
9614
+ // Face-axis brightness and darker edges keep the grid shape readable.
9434
9615
  fn shadeVoxelHit(hitPos: vec3f, voxMin: vec3f, voxelRes: f32, ro: vec3f) -> vec4f {
9435
9616
  let dist = length(hitPos - ro);
9436
9617
  let pixelWorld = 2.0 * dist / (f32(uniforms.screenHeight) * uniforms.projScaleY);
@@ -9450,15 +9631,12 @@ fn shadeVoxelHit(hitPos: vec3f, voxMin: vec3f, voxelRes: f32, ro: vec3f) -> vec4
9450
9631
  faceAxis = 2u;
9451
9632
  }
9452
9633
 
9453
- var baseColor: vec3f;
9454
- if (faceAxis == 0u) { baseColor = vec3f(0.85); }
9455
- else if (faceAxis == 1u) { baseColor = vec3f(0.55); }
9456
- else { baseColor = vec3f(0.30); }
9634
+ var brightness = 0.85;
9635
+ if (faceAxis == 1u) { brightness = 0.65; }
9636
+ else if (faceAxis == 2u) { brightness = 0.45; }
9457
9637
 
9458
- // Mix the surface base color toward black as the edge factor approaches 1
9459
- // and ramp alpha from FILL_ALPHA up to EDGE_ALPHA so face edges read as
9460
- // opaque black lines while the interior stays at the surface tint.
9461
- let color = mix(baseColor, vec3f(0.0), ef);
9638
+ let tint = select(vec3f(1.0), vec3f(1.0, 0.35, 0.08), uniforms.inverted != 0u);
9639
+ let color = tint * mix(brightness, 0.2, ef);
9462
9640
  let alpha = mix(FILL_ALPHA, EDGE_ALPHA, ef);
9463
9641
 
9464
9642
  return vec4f(color * alpha, alpha);
@@ -9512,7 +9690,7 @@ fn main(@builtin(global_invocation_id) gid: vec3u) {
9512
9690
  let invDir = 1.0 / rd;
9513
9691
  let gridHit = intersectAABB(ro, invDir, gridMin, gridMax);
9514
9692
 
9515
- if (gridHit.x > gridHit.y) {
9693
+ if (max(gridHit.x, 0.0) > gridHit.y) {
9516
9694
  textureStore(outputTexture, vec2i(px, py), vec4f(0.0));
9517
9695
  return;
9518
9696
  }
@@ -9849,7 +10027,7 @@ class VoxelDebugOverlay {
9849
10027
  });
9850
10028
  }
9851
10029
  update() {
9852
- if (!this.enabled)
10030
+ if (!this.enabled || this.collision.nodes.length === 0)
9853
10031
  return;
9854
10032
  const { app, camera, compute, collision } = this;
9855
10033
  const device = app.graphicsDevice;
@@ -9923,6 +10101,9 @@ class VoxelDebugOverlay {
9923
10101
  app.drawTexture(0, 0, 2, 2, null, this.overlayMaterial);
9924
10102
  }
9925
10103
  destroy() {
10104
+ this.compute.destroy();
10105
+ this.compute.shader.destroy();
10106
+ this.overlayMaterial.destroy();
9926
10107
  this.nodesBuffer?.destroy();
9927
10108
  this.leafDataBuffer?.destroy();
9928
10109
  this.storageTexture?.destroy();
@@ -10460,13 +10641,64 @@ class Viewer {
10460
10641
  }
10461
10642
  }, ignoreLoadFailure);
10462
10643
  }
10644
+ // Loading progress has to start reporting as soon as the splat data starts streaming,
10645
+ // which is well before the reveal. The reveal is wired up in the `Promise.all` below, so
10646
+ // it also waits on the skybox and the collision data — and a collision download can take
10647
+ // far longer than the splats themselves (ten seconds against under six, on a 4G trace of
10648
+ // a real scene), leaving the bar frozen at 0% for the whole wait. Chaining off
10649
+ // `gsplatLoad` alone lets the bar track the one load it can measure, from the moment
10650
+ // that load begins. The reveal below stops it and puts the bar at 100.
10651
+ let stopProgress;
10652
+ gsplatLoad.then(() => {
10653
+ if (this.destroyed)
10654
+ return;
10655
+ const eventHandler = app.systems.gsplat;
10656
+ // `loading` counts the node files the streamer has requested and not yet made
10657
+ // resident. Before the reveal the LOD range is clamped to the coarsest level, so this
10658
+ // is a single wave and completed / (completed + in-flight) tracks it directly. A drop
10659
+ // in the count is work that finished, or was cancelled, which this cannot tell apart
10660
+ // and counts as done. Clamped monotone and capped below 100 so only the reveal fills
10661
+ // the bar. See docs/streaming-progress.md for the engine signal that would replace it.
10662
+ let prevLoading = 0;
10663
+ let completed = 0;
10664
+ const progressHandler = (camera, layer, ready, loading) => {
10665
+ completed += Math.max(0, prevLoading - loading);
10666
+ prevLoading = loading;
10667
+ const total = completed + loading;
10668
+ if (total > 0) {
10669
+ state.progress = Math.max(state.progress, Math.min(99, Math.trunc((completed / total) * 100)));
10670
+ }
10671
+ };
10672
+ eventHandler.on('frame:ready', progressHandler);
10673
+ stopProgress = () => eventHandler.off('frame:ready', progressHandler);
10674
+ this.onDestroy(stopProgress);
10675
+ }, ignoreLoadFailure);
10676
+ // Collision data is not needed to draw the scene, and it can be larger than the splats
10677
+ // themselves: 5.65 MB against 4.28 MB for the coarsest LOD level on a traced scene. So
10678
+ // it is kept out of the reveal path below, which would otherwise sit on a blank poster
10679
+ // with everything needed to render already in memory. `attachCollision` wires it up
10680
+ // whenever it lands; the two chains can resolve in either order, so whichever is second
10681
+ // performs the attach.
10682
+ //
10683
+ // Nothing in the opening view depends on it. The scene always starts in `anim` mode, so
10684
+ // no collision-dependent controller is entered until the user takes over. Until it
10685
+ // attaches, `walkAllowed` stays false so walk mode cannot be entered without the data it
10686
+ // needs to place the camera, fly mode has no collision response, and nav targeting falls
10687
+ // back to splat depth instead of collision ray hits.
10688
+ let collisionReady = null;
10689
+ let attachCollision;
10690
+ collisionLoad?.then((collision) => {
10691
+ if (this.destroyed || !collision)
10692
+ return;
10693
+ collisionReady = collision;
10694
+ attachCollision?.(collision);
10695
+ }, ignoreLoadFailure);
10463
10696
  // wait for the model to load
10464
- Promise.all([gsplatLoad, skyboxLoad, collisionLoad]).then((results) => {
10697
+ Promise.all([gsplatLoad, skyboxLoad]).then((results) => {
10465
10698
  // destroyed while loading: the app is gone, so there is nothing to wire up
10466
10699
  if (this.destroyed)
10467
10700
  return;
10468
10701
  const gsplatComponent = results[0].gsplat;
10469
- const collision = results[2];
10470
10702
  // get scene bounding box
10471
10703
  const gsplatBbox = gsplatComponent.customAabb;
10472
10704
  if (gsplatBbox) {
@@ -10474,37 +10706,54 @@ class Viewer {
10474
10706
  }
10475
10707
  this.picker = new Picker(app, camera);
10476
10708
  this.inputController = new InputController(global, this.picker);
10477
- this.inputController.collision = collision ?? null;
10709
+ this.cameraManager = new CameraManager(global, sceneBound);
10710
+ applyCamera(this.cameraManager.camera);
10711
+ if (config.ui) {
10712
+ this.navCursor = new NavCursor(app, camera, null, events, state, config.reticle);
10713
+ }
10478
10714
  // hasCollision = collision data exists (drives fly-mode collision
10479
10715
  // detection and the voxel/mesh debug overlay availability).
10480
10716
  // walkAllowed = walk mode is offered to the user; requires both
10481
10717
  // collision data and a scene large enough to walk around in.
10482
- state.hasCollision = !!collision;
10483
- state.walkAllowed = isWalkAllowed(sceneBound, collision ?? null);
10484
- // Create collision debug overlay (voxel uses a compute shader, mesh
10485
- // uses standard line rendering). The voxel path requires WebGPU.
10486
- if (collision instanceof VoxelCollision && renderer !== 'webgl') {
10487
- this.voxelOverlay = new VoxelDebugOverlay(app, collision, camera);
10488
- this.voxelOverlay.mode = config.heatmap ? 'heatmap' : 'overlay';
10489
- state.hasCollisionOverlay = true;
10490
- events.on('collisionOverlayEnabled:changed', (value) => {
10491
- this.voxelOverlay.enabled = value;
10492
- app.renderNextFrame = true;
10493
- });
10494
- }
10495
- else if (collision instanceof MeshCollision) {
10496
- this.meshOverlay = new MeshDebugOverlay(app, collision, camera, !!this.cameraFrame);
10497
- state.hasCollisionOverlay = true;
10498
- events.on('collisionOverlayEnabled:changed', (value) => {
10499
- this.meshOverlay.enabled = value;
10500
- app.renderNextFrame = true;
10501
- });
10502
- }
10503
- this.cameraManager = new CameraManager(global, sceneBound, collision);
10504
- applyCamera(this.cameraManager.camera);
10505
- if (config.ui) {
10506
- this.navCursor = new NavCursor(app, camera, collision ?? null, events, state, config.reticle);
10507
- }
10718
+ attachCollision = (collision) => {
10719
+ this.inputController.collision = collision;
10720
+ this.cameraManager.setCollision(collision);
10721
+ if (this.navCursor) {
10722
+ this.navCursor.collision = collision;
10723
+ }
10724
+ state.hasCollision = true;
10725
+ state.walkAllowed = isWalkAllowed(sceneBound, collision);
10726
+ // Create collision debug overlay (voxel uses a compute shader, mesh
10727
+ // uses standard line rendering). The voxel path requires WebGPU.
10728
+ if (collision instanceof VoxelCollision && renderer !== 'webgl') {
10729
+ const setOverlayEnabled = (value) => {
10730
+ // Upload the voxel data and allocate the screen-sized texture only
10731
+ // when the debug overlay is first used.
10732
+ if (value && !this.voxelOverlay) {
10733
+ this.voxelOverlay = new VoxelDebugOverlay(app, collision, camera);
10734
+ this.voxelOverlay.mode = config.heatmap ? 'heatmap' : 'overlay';
10735
+ }
10736
+ if (this.voxelOverlay)
10737
+ this.voxelOverlay.enabled = value;
10738
+ app.renderNextFrame = true;
10739
+ };
10740
+ events.on('collisionOverlayEnabled:changed', setOverlayEnabled);
10741
+ state.hasCollisionOverlay = true;
10742
+ setOverlayEnabled(state.collisionOverlayEnabled);
10743
+ }
10744
+ else if (collision instanceof MeshCollision) {
10745
+ this.meshOverlay = new MeshDebugOverlay(app, collision, camera, !!this.cameraFrame);
10746
+ state.hasCollisionOverlay = true;
10747
+ events.on('collisionOverlayEnabled:changed', (value) => {
10748
+ this.meshOverlay.enabled = value;
10749
+ app.renderNextFrame = true;
10750
+ });
10751
+ }
10752
+ app.renderNextFrame = true;
10753
+ };
10754
+ // collision may already have landed while the splats were still streaming
10755
+ if (collisionReady)
10756
+ attachCollision(collisionReady);
10508
10757
  this.debugPanel = new DebugPanel(global, this.cameraManager);
10509
10758
  // quality budget
10510
10759
  const budgets = {
@@ -10544,12 +10793,28 @@ class Viewer {
10544
10793
  eventHandler.on('frame:request', () => {
10545
10794
  app.renderNextFrame = true;
10546
10795
  });
10547
- let current = 0;
10548
- let watermark = 1;
10796
+ // `ready && loading === 0` describes the state before streaming starts just as well
10797
+ // as the state after it finishes: on the first frame the octree instance has not run
10798
+ // its LOD pass yet, so nothing is in flight and the world trivially reports ready.
10799
+ // Taken at face value that revealed the scene on the first event, before a single
10800
+ // frame had rendered, which both skipped the whole loading bar and undid the coarse
10801
+ // LOD clamp above by running applyPerfSettings immediately. So require evidence that
10802
+ // the streamer has left that initial state: work in flight, or splats on screen.
10803
+ // Only octree content has a streaming phase to wait for; single-file content is fully
10804
+ // loaded before this handler is registered, so it must not be gated.
10805
+ const octree = gsplatComponent.resource?.octree ?? null;
10806
+ let streamingStarted = !octree;
10549
10807
  const readyHandler = (camera, layer, ready, loading) => {
10550
- if (ready && loading === 0) {
10808
+ // `frame.gsplats` is the rendered splat count, the same stat the ministats panel
10809
+ // above reads. It covers an octree that renders before it reports work in flight.
10810
+ if (loading > 0 || app.stats.frame.gsplats > 0) {
10811
+ streamingStarted = true;
10812
+ }
10813
+ if (ready && loading === 0 && streamingStarted) {
10551
10814
  // scene is done with initial/reveal loading
10552
10815
  eventHandler.off('frame:ready', readyHandler);
10816
+ stopProgress?.();
10817
+ state.progress = 100;
10553
10818
  // switch to on-demand rendering (frame:request + camera-change detection)
10554
10819
  app.autoRender = false;
10555
10820
  // handle quality mode changes
@@ -10563,12 +10828,6 @@ class Viewer {
10563
10828
  window.firstFrame?.();
10564
10829
  });
10565
10830
  }
10566
- // update loading status
10567
- if (loading !== current) {
10568
- watermark = Math.max(watermark, loading);
10569
- current = watermark - loading;
10570
- state.progress = Math.trunc((current / watermark) * 100);
10571
- }
10572
10831
  };
10573
10832
  eventHandler.on('frame:ready', readyHandler);
10574
10833
  }, ignoreLoadFailure);
@@ -10835,13 +11094,22 @@ class Viewer {
10835
11094
  }
10836
11095
  }
10837
11096
 
11097
+ // The filename's extension selects the gsplat parser, so a url with no usable name (a data:
11098
+ // uri) needs the config to name its content instead; falsy (an empty name) falls back to the
11099
+ // url-derived name.
11100
+ const contentName = (contentUrl, contentFilename) => contentFilename || new URL(contentUrl, location.href).pathname.split('/').pop();
11101
+ // Whether a prefetched response for this content is worth starting. The engine's octree parser
11102
+ // fetches lod-meta.json itself and ignores `asset.file.contents`, so prefetching it downloads
11103
+ // the metadata twice — a quarter of a megabyte on a real scene, served with no cache-control
11104
+ // header, so the second request is not a cache hit. Every other splat parser consumes the
11105
+ // prefetched response, so they keep the head start. `src/index.html` applies the same rule when
11106
+ // it starts its own prefetch, and docs/streaming-progress.md covers the engine fix that would
11107
+ // let the octree path reuse the response instead of opting out of it.
11108
+ const isPrefetchable = (contentUrl, contentFilename) => contentName(contentUrl, contentFilename)?.toLowerCase() !== 'lod-meta.json';
10838
11109
  const loadGsplat = async (app, config, progressCallback, cancelled) => {
10839
11110
  const { contents, contentUrl, contentFilename } = config;
10840
11111
  const c = contents;
10841
- // the filename's extension selects the gsplat parser, so a url with no usable name (a
10842
- // data: uri) needs the config to name its content instead; falsy (an empty name) falls
10843
- // back to the url-derived name
10844
- const filename = contentFilename || new URL(contentUrl, location.href).pathname.split('/').pop();
11112
+ const filename = contentName(contentUrl, contentFilename);
10845
11113
  const data = filename.toLowerCase() === 'meta.json' ? await (await contents).json() : undefined;
10846
11114
  // Reading that metadata spans a network round trip, so a destroy can land in the middle of
10847
11115
  // it. `app.destroy()` nulls the asset registry, so registering the asset now would throw
@@ -11018,7 +11286,8 @@ const resolveConfig = (options) => ({
11018
11286
  skyboxUrl: options.skyboxUrl,
11019
11287
  collisionUrl: options.collisionUrl,
11020
11288
  poster: options.poster ?? (options.posterUrl ? createImage(options.posterUrl) : undefined),
11021
- contents: options.contents ?? fetch(options.contentUrl),
11289
+ contents: options.contents ??
11290
+ (isPrefetchable(options.contentUrl, options.contentFilename) ? fetch(options.contentUrl) : undefined),
11022
11291
  renderer: options.renderer ?? 'webgpu',
11023
11292
  ui: options.ui ?? true,
11024
11293
  reticle: options.reticle ?? false,