@playcanvas/supersplat-viewer 1.14.2 → 1.15.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/public/index.js CHANGED
@@ -69079,7 +69079,7 @@ class GamepadSource extends InputSource {
69079
69079
  }
69080
69080
  GamepadSource.buttonCode = BUTTON_CODES;
69081
69081
 
69082
- const damp = (damping, dt)=>1 - Math.pow(damping, dt * 1000);
69082
+ const damp$1 = (damping, dt)=>1 - Math.pow(damping, dt * 1000);
69083
69083
 
69084
69084
  const offset$1 = new Vec3();
69085
69085
  const angles$1 = new Vec3();
@@ -69123,7 +69123,7 @@ let FlyController$1 = class FlyController extends InputController$1 {
69123
69123
  offset$1.add(right.mulScalar(move[0]));
69124
69124
  offset$1.add(up.mulScalar(move[1]));
69125
69125
  this._targetPose.move(offset$1);
69126
- return this._pose.lerp(this._pose, this._targetPose, damp(this.moveDamping, dt), damp(this.rotateDamping, dt));
69126
+ return this._pose.lerp(this._pose, this._targetPose, damp$1(this.moveDamping, dt), damp$1(this.rotateDamping, dt));
69127
69127
  }
69128
69128
  destroy() {
69129
69129
  this.detach();
@@ -69179,8 +69179,8 @@ let OrbitController$1 = class OrbitController extends InputController$1 {
69179
69179
  const { z: dist } = this._targetChildPose.position;
69180
69180
  this._targetChildPose.move(offset.set(0, 0, dist * (1 + move[2]) - dist));
69181
69181
  this._targetRootPose.rotate(angles.set(-rotate[1], -rotate[0], 0));
69182
- this._rootPose.lerp(this._rootPose, this._targetRootPose, damp(this.moveDamping, dt), damp(this.rotateDamping, dt), 1);
69183
- this._childPose.lerp(this._childPose, this._targetChildPose, damp(this.zoomDamping, dt), 1, 1);
69182
+ this._rootPose.lerp(this._rootPose, this._targetRootPose, damp$1(this.moveDamping, dt), damp$1(this.rotateDamping, dt), 1);
69183
+ this._childPose.lerp(this._childPose, this._targetChildPose, damp$1(this.zoomDamping, dt), 1, 1);
69184
69184
  rotation$1.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position, offset).add(this._rootPose.position);
69185
69185
  return this._pose.set(offset, this._rootPose.angles, this._childPose.position.z);
69186
69186
  }
@@ -69465,7 +69465,7 @@ const initJoystick = (dom, events, state) => {
69465
69465
  let lastTapTime = 0;
69466
69466
  // Update joystick visibility based on camera mode and input mode
69467
69467
  const updateJoystickVisibility = () => {
69468
- if (state.cameraMode === 'fly' && state.inputMode === 'touch') {
69468
+ if ((state.cameraMode === 'fly' || state.cameraMode === 'fps') && state.inputMode === 'touch') {
69469
69469
  dom.joystickBase.classList.remove('hidden');
69470
69470
  dom.joystickBase.classList.toggle('mode-2d', joystickMode === '2d');
69471
69471
  dom.joystickBase.style.left = `${joystickFixedX}px`;
@@ -69633,11 +69633,12 @@ const initUI = (global) => {
69633
69633
  'buttonContainer',
69634
69634
  'play', 'pause',
69635
69635
  'settings', 'settingsPanel',
69636
- 'orbitCamera', 'flyCamera',
69636
+ 'orbitCamera', 'flyCamera', 'fpsCamera',
69637
69637
  'hqCheck', 'hqOption', 'lqCheck', 'lqOption',
69638
69638
  'reset', 'frame',
69639
69639
  'loadingText', 'loadingBar',
69640
69640
  'joystickBase', 'joystick',
69641
+ 'showVoxels',
69641
69642
  'tooltip',
69642
69643
  'annotationNav', 'annotationPrev', 'annotationNext', 'annotationInfo', 'annotationNavTitle',
69643
69644
  'supersplatBranding'
@@ -69645,6 +69646,10 @@ const initUI = (global) => {
69645
69646
  acc[id] = document.getElementById(id);
69646
69647
  return acc;
69647
69648
  }, {});
69649
+ // Remove focus from buttons after click so keyboard input isn't captured by the UI
69650
+ dom.ui.addEventListener('click', () => {
69651
+ document.activeElement?.blur();
69652
+ });
69648
69653
  // Forward wheel events from UI overlays to the canvas so the camera zooms
69649
69654
  // instead of the page scrolling (e.g. annotation nav, tooltips, hotspots)
69650
69655
  const canvas = global.app.graphicsDevice.canvas;
@@ -69778,7 +69783,8 @@ const initUI = (global) => {
69778
69783
  });
69779
69784
  // fade ui controls after 5 seconds of inactivity
69780
69785
  events.on('controlsHidden:changed', (value) => {
69781
- dom.controlsWrap.className = value ? 'faded-out' : 'faded-in';
69786
+ dom.controlsWrap.classList.toggle('faded-out', value);
69787
+ dom.controlsWrap.classList.toggle('faded-in', !value);
69782
69788
  });
69783
69789
  // show the ui and start a timer to hide it again
69784
69790
  let uiTimeout = null;
@@ -69880,9 +69886,28 @@ const initUI = (global) => {
69880
69886
  });
69881
69887
  });
69882
69888
  // Camera mode UI
69883
- events.on('cameraMode:changed', () => {
69884
- dom.orbitCamera.classList[state.cameraMode === 'orbit' ? 'add' : 'remove']('active');
69885
- dom.flyCamera.classList[state.cameraMode === 'fly' ? 'add' : 'remove']('active');
69889
+ const updateCameraModeUI = () => {
69890
+ dom.orbitCamera.classList.toggle('active', state.cameraMode === 'orbit');
69891
+ dom.flyCamera.classList.toggle('active', state.cameraMode === 'fly');
69892
+ dom.fpsCamera.classList.toggle('active', state.cameraMode === 'fps');
69893
+ };
69894
+ events.on('cameraMode:changed', updateCameraModeUI);
69895
+ // show/hide the FPS button based on voxel data availability
69896
+ events.on('hasCollision:changed', (value) => {
69897
+ dom.fpsCamera.classList.toggle('hidden', !value);
69898
+ // adjust fly button shape: middle when FPS is visible, right when hidden
69899
+ dom.flyCamera.classList.toggle('middle', value);
69900
+ dom.flyCamera.classList.toggle('right', !value);
69901
+ });
69902
+ // Voxel overlay toggle (only visible when overlay is available)
69903
+ events.on('hasVoxelOverlay:changed', (value) => {
69904
+ dom.showVoxels.classList.toggle('hidden', !value);
69905
+ });
69906
+ dom.showVoxels.addEventListener('click', () => {
69907
+ state.voxelOverlayEnabled = !state.voxelOverlayEnabled;
69908
+ });
69909
+ events.on('voxelOverlayEnabled:changed', (value) => {
69910
+ dom.showVoxels.classList.toggle('active', value);
69886
69911
  });
69887
69912
  dom.settings.addEventListener('click', () => {
69888
69913
  dom.settingsPanel.classList.toggle('hidden');
@@ -69893,6 +69918,9 @@ const initUI = (global) => {
69893
69918
  dom.flyCamera.addEventListener('click', () => {
69894
69919
  state.cameraMode = 'fly';
69895
69920
  });
69921
+ dom.fpsCamera.addEventListener('click', () => {
69922
+ events.fire('inputEvent', 'toggleFps');
69923
+ });
69896
69924
  dom.reset.addEventListener('click', (event) => {
69897
69925
  events.fire('inputEvent', 'reset', event);
69898
69926
  });
@@ -69913,8 +69941,10 @@ const initUI = (global) => {
69913
69941
  tooltip.register(dom.pause, 'Pause', 'top');
69914
69942
  tooltip.register(dom.orbitCamera, 'Orbit Camera', 'top');
69915
69943
  tooltip.register(dom.flyCamera, 'Fly Camera', 'top');
69944
+ tooltip.register(dom.fpsCamera, 'Walk Mode', 'top');
69916
69945
  tooltip.register(dom.reset, 'Reset Camera', 'bottom');
69917
69946
  tooltip.register(dom.frame, 'Frame Scene', 'bottom');
69947
+ tooltip.register(dom.showVoxels, 'Show Voxels', 'top');
69918
69948
  tooltip.register(dom.settings, 'Settings', 'top');
69919
69949
  tooltip.register(dom.info, 'Help', 'top');
69920
69950
  tooltip.register(dom.arMode, 'Enter AR', 'top');
@@ -70686,6 +70716,7 @@ class CubicSpline {
70686
70716
  * @param dt - Delta time in seconds.
70687
70717
  * @returns - Damping factor adjusted for the delta time.
70688
70718
  */
70719
+ const damp = (damping, dt) => 1 - Math.pow(damping, dt * 1000);
70689
70720
  /**
70690
70721
  * Easing function for smooth transitions.
70691
70722
  *
@@ -70859,9 +70890,15 @@ class Camera {
70859
70890
  }
70860
70891
  }
70861
70892
 
70893
+ /** Radius of the camera collision sphere (meters) */
70894
+ const CAMERA_RADIUS = 0.2;
70862
70895
  const p$1 = new Pose();
70896
+ /** Pre-allocated push-out vector for sphere collision */
70897
+ const pushOut$1 = { x: 0, y: 0, z: 0 };
70863
70898
  class FlyController {
70864
70899
  controller;
70900
+ /** Optional voxel collider for sphere collision with sliding */
70901
+ collider = null;
70865
70902
  constructor() {
70866
70903
  this.controller = new FlyController$1();
70867
70904
  this.controller.pitchRange = new Vec2(-90, 90);
@@ -70876,9 +70913,33 @@ class FlyController {
70876
70913
  }
70877
70914
  update(deltaTime, inputFrame, camera) {
70878
70915
  const pose = this.controller.update(inputFrame, deltaTime);
70879
- camera.position.copy(pose.position);
70880
70916
  camera.angles.copy(pose.angles);
70881
70917
  camera.distance = pose.distance;
70918
+ if (this.collider) {
70919
+ // Resolve collision on _targetPose first. The engine's update() already
70920
+ // applied input to _targetPose and lerped _pose toward it. By correcting
70921
+ // _targetPose now, we ensure next frame's lerp interpolates toward a safe
70922
+ // position, preventing the camera from overshooting into the wall.
70923
+ const target = this.controller._targetPose;
70924
+ const tvx = -target.position.x;
70925
+ const tvy = -target.position.y;
70926
+ const tvz = target.position.z;
70927
+ if (this.collider.querySphere(tvx, tvy, tvz, CAMERA_RADIUS, pushOut$1)) {
70928
+ target.position.x += -pushOut$1.x;
70929
+ target.position.y += -pushOut$1.y;
70930
+ target.position.z += pushOut$1.z;
70931
+ }
70932
+ // Now resolve collision on the interpolated pose (_pose).
70933
+ const vx = -pose.position.x;
70934
+ const vy = -pose.position.y;
70935
+ const vz = pose.position.z;
70936
+ if (this.collider.querySphere(vx, vy, vz, CAMERA_RADIUS, pushOut$1)) {
70937
+ pose.position.x += -pushOut$1.x;
70938
+ pose.position.y += -pushOut$1.y;
70939
+ pose.position.z += pushOut$1.z;
70940
+ }
70941
+ }
70942
+ camera.position.copy(pose.position);
70882
70943
  }
70883
70944
  onExit(camera) {
70884
70945
  }
@@ -70887,6 +70948,168 @@ class FlyController {
70887
70948
  }
70888
70949
  }
70889
70950
 
70951
+ /** Pre-allocated push-out vector for capsule collision */
70952
+ const pushOut = { x: 0, y: 0, z: 0 };
70953
+ /**
70954
+ * First-person shooter style camera controller with gravity and capsule collision.
70955
+ *
70956
+ * Movement is constrained to the horizontal plane (XZ) relative to the camera yaw.
70957
+ * Vertical motion is driven by gravity and resolved by capsule collision with the
70958
+ * voxel grid. The camera is positioned at eye height within the capsule.
70959
+ */
70960
+ class FpsController {
70961
+ /** Optional voxel collider for capsule collision with sliding */
70962
+ collider = null;
70963
+ /** Total capsule height in meters (default: human proportion) */
70964
+ capsuleHeight = 1.8;
70965
+ /** Capsule radius in meters */
70966
+ capsuleRadius = 0.3;
70967
+ /** Camera height from the bottom of the capsule in meters */
70968
+ eyeHeight = 1.6;
70969
+ /** Gravity acceleration in m/s^2 */
70970
+ gravity = 9.8;
70971
+ /** Jump velocity in m/s */
70972
+ jumpSpeed = 5;
70973
+ /** Movement damping factor (0 = no damping, 1 = full damping) */
70974
+ moveDamping = 0.97;
70975
+ /** Rotation damping factor (0 = no damping, 1 = full damping) */
70976
+ rotateDamping = 0.97;
70977
+ // Target state (where input drives)
70978
+ _targetPosition = new Vec3();
70979
+ _targetYaw = 0;
70980
+ _targetPitch = 0;
70981
+ // Smoothed state (lerps toward target)
70982
+ _position = new Vec3();
70983
+ _yaw = 0;
70984
+ _pitch = 0;
70985
+ // Vertical velocity for gravity
70986
+ _velocityY = 0;
70987
+ // Whether the capsule is resting on the ground
70988
+ _onGround = false;
70989
+ onEnter(camera) {
70990
+ this._position.copy(camera.position);
70991
+ this._targetPosition.copy(camera.position);
70992
+ // angles.x = pitch, angles.y = yaw
70993
+ this._pitch = camera.angles.x;
70994
+ this._targetPitch = camera.angles.x;
70995
+ this._yaw = camera.angles.y;
70996
+ this._targetYaw = camera.angles.y;
70997
+ this._velocityY = 0;
70998
+ this._onGround = false;
70999
+ }
71000
+ update(deltaTime, inputFrame, camera) {
71001
+ const { move, rotate } = inputFrame.read();
71002
+ // --- Rotation ---
71003
+ this._targetYaw -= rotate[0];
71004
+ this._targetPitch = math.clamp(this._targetPitch - rotate[1], -90, 90);
71005
+ const rotateLerp = damp(this.rotateDamping, deltaTime);
71006
+ this._yaw = math.lerpAngle(this._yaw, this._targetYaw, rotateLerp);
71007
+ this._pitch = math.lerp(this._pitch, this._targetPitch, rotateLerp);
71008
+ // Normalize yaw to prevent floating-point drift over long sessions.
71009
+ // Shift both values by the same multiple of 360 to preserve their delta.
71010
+ const yawOffset = Math.round(this._yaw / 360) * 360;
71011
+ if (yawOffset !== 0) {
71012
+ this._yaw -= yawOffset;
71013
+ this._targetYaw -= yawOffset;
71014
+ }
71015
+ // --- Horizontal movement ---
71016
+ // Compute forward/right from yaw only (ignore pitch for movement)
71017
+ const yawRad = this._targetYaw * math.DEG_TO_RAD;
71018
+ const sinYaw = Math.sin(yawRad);
71019
+ const cosYaw = Math.cos(yawRad);
71020
+ // PlayCanvas convention: forward = -Z, right = +X
71021
+ const forwardX = -sinYaw;
71022
+ const forwardZ = -cosYaw;
71023
+ const rightX = cosYaw;
71024
+ const rightZ = -sinYaw;
71025
+ const moveLerp = damp(this.moveDamping, deltaTime);
71026
+ this._targetPosition.x += rightX * move[0] + forwardX * move[2];
71027
+ this._targetPosition.z += rightZ * move[0] + forwardZ * move[2];
71028
+ // --- Jump ---
71029
+ if (move[1] > 0 && this._onGround) {
71030
+ this._velocityY = this.jumpSpeed;
71031
+ this._onGround = false;
71032
+ }
71033
+ // --- Gravity ---
71034
+ this._velocityY -= this.gravity * deltaTime;
71035
+ this._targetPosition.y += this._velocityY * deltaTime;
71036
+ // --- Capsule collision on target position ---
71037
+ if (this.collider) {
71038
+ this._resolveCapsuleCollision(this._targetPosition, true);
71039
+ }
71040
+ // --- Smooth horizontal position toward target ---
71041
+ this._position.x = math.lerp(this._position.x, this._targetPosition.x, moveLerp);
71042
+ this._position.z = math.lerp(this._position.z, this._targetPosition.z, moveLerp);
71043
+ // No smoothing on Y for crisp ground contact
71044
+ this._position.y = this._targetPosition.y;
71045
+ // --- Capsule collision on smoothed position ---
71046
+ if (this.collider) {
71047
+ this._resolveCapsuleCollision(this._position, false);
71048
+ }
71049
+ // --- Output to camera ---
71050
+ camera.position.copy(this._position);
71051
+ camera.angles.set(this._pitch, this._yaw, 0);
71052
+ }
71053
+ onExit(_camera) {
71054
+ // nothing to clean up
71055
+ }
71056
+ /**
71057
+ * Teleport the controller to a given camera state (used for transitions).
71058
+ *
71059
+ * @param camera - The camera state to jump to.
71060
+ */
71061
+ goto(camera) {
71062
+ this._position.copy(camera.position);
71063
+ this._targetPosition.copy(camera.position);
71064
+ this._pitch = camera.angles.x;
71065
+ this._targetPitch = camera.angles.x;
71066
+ this._yaw = camera.angles.y;
71067
+ this._targetYaw = camera.angles.y;
71068
+ this._velocityY = 0;
71069
+ this._onGround = false;
71070
+ }
71071
+ /**
71072
+ * Resolve capsule collision for a given eye position, modifying it in place.
71073
+ * Converts from PlayCanvas space to voxel space, queries the capsule, and
71074
+ * applies the push-out vector back to PlayCanvas space.
71075
+ *
71076
+ * @param eyePos - Eye position to resolve (modified in place).
71077
+ * @param isTarget - Whether this is the target position (updates velocity on ground contact).
71078
+ */
71079
+ _resolveCapsuleCollision(eyePos, isTarget) {
71080
+ // Derive capsule center from eye position in PlayCanvas space:
71081
+ // bottom of capsule = eyePos.y - eyeHeight
71082
+ // capsule center = eyePos.y - eyeHeight + capsuleHeight / 2
71083
+ const capsuleCenterPCY = eyePos.y - this.eyeHeight + this.capsuleHeight * 0.5;
71084
+ const halfHeight = this.capsuleHeight * 0.5 - this.capsuleRadius;
71085
+ // Convert to voxel space (negate X, negate Y, keep Z)
71086
+ const vx = -eyePos.x;
71087
+ const vy = -capsuleCenterPCY;
71088
+ const vz = eyePos.z;
71089
+ if (this.collider.queryCapsule(vx, vy, vz, halfHeight, this.capsuleRadius, pushOut)) {
71090
+ // Convert push-out back to PlayCanvas space
71091
+ const pushPCX = -pushOut.x;
71092
+ const pushPCY = -pushOut.y;
71093
+ const pushPCZ = pushOut.z;
71094
+ eyePos.x += pushPCX;
71095
+ // Push-out applies to capsule center; eye moves by the same amount
71096
+ eyePos.y += pushPCY;
71097
+ eyePos.z += pushPCZ;
71098
+ // Ground detection: if pushed upward and falling, cancel downward velocity
71099
+ if (isTarget) {
71100
+ if (pushPCY > 0 && this._velocityY < 0) {
71101
+ this._velocityY = 0;
71102
+ this._onGround = true;
71103
+ }
71104
+ // Ceiling detection: if pushed downward and rising, cancel upward velocity
71105
+ if (pushPCY < 0 && this._velocityY > 0) {
71106
+ this._velocityY = 0;
71107
+ }
71108
+ }
71109
+ }
71110
+ }
71111
+ }
71112
+
70890
71113
  const p = new Pose();
70891
71114
  class OrbitController {
70892
71115
  controller;
@@ -70937,7 +71160,7 @@ class CameraManager {
70937
71160
  update;
70938
71161
  // holds the camera state
70939
71162
  camera = new Camera();
70940
- constructor(global, bbox) {
71163
+ constructor(global, bbox, collider = null) {
70941
71164
  const { events, settings, state } = global;
70942
71165
  const camera0 = settings.cameras[0].initial;
70943
71166
  const frameCamera = createFrameCamera(bbox, camera0.fov);
@@ -70962,8 +71185,11 @@ class CameraManager {
70962
71185
  const controllers = {
70963
71186
  orbit: new OrbitController(),
70964
71187
  fly: new FlyController(),
71188
+ fps: new FpsController(),
70965
71189
  anim: animTrack ? new AnimController(animTrack) : null
70966
71190
  };
71191
+ controllers.fly.collider = collider;
71192
+ controllers.fps.collider = collider;
70967
71193
  const getController = (cameraMode) => {
70968
71194
  return controllers[cameraMode];
70969
71195
  };
@@ -70976,6 +71202,8 @@ class CameraManager {
70976
71202
  const target = new Camera(this.camera); // the active controller updates this
70977
71203
  const from = new Camera(this.camera); // stores the previous camera state during transition
70978
71204
  let fromMode = isObjectExperience ? 'orbit' : 'fly';
71205
+ // tracks the mode to restore when exiting FPS
71206
+ let preFpsMode = 'fly';
70979
71207
  // enter the initial controller
70980
71208
  getController(state.cameraMode).onEnter(this.camera);
70981
71209
  // transition state
@@ -71030,7 +71258,28 @@ class CameraManager {
71030
71258
  }
71031
71259
  }
71032
71260
  break;
71261
+ case 'requestFirstPerson':
71262
+ state.cameraMode = 'fly';
71263
+ break;
71264
+ case 'toggleFps':
71265
+ if (collider) {
71266
+ if (state.cameraMode === 'fps') {
71267
+ state.cameraMode = preFpsMode;
71268
+ }
71269
+ else {
71270
+ preFpsMode = state.cameraMode;
71271
+ state.cameraMode = 'fps';
71272
+ }
71273
+ }
71274
+ break;
71033
71275
  case 'cancel':
71276
+ if (state.cameraMode === 'anim') {
71277
+ state.cameraMode = fromMode;
71278
+ }
71279
+ else if (state.cameraMode === 'fps') {
71280
+ state.cameraMode = preFpsMode;
71281
+ }
71282
+ break;
71034
71283
  case 'interrupt':
71035
71284
  if (state.cameraMode === 'anim') {
71036
71285
  state.cameraMode = fromMode;
@@ -71317,6 +71566,7 @@ class InputController {
71317
71566
  mouse: [0, 0, 0],
71318
71567
  shift: 0,
71319
71568
  ctrl: 0,
71569
+ jump: 0,
71320
71570
  touches: 0
71321
71571
  };
71322
71572
  _desktopInput = new KeyboardMouseSource();
@@ -71400,7 +71650,7 @@ class InputController {
71400
71650
  if (event.key === 'Escape') {
71401
71651
  events.fire('inputEvent', 'cancel', event);
71402
71652
  }
71403
- else if (!event.ctrlKey && !event.altKey && !event.metaKey) {
71653
+ else if (state.cameraMode !== 'fps' && !event.ctrlKey && !event.altKey && !event.metaKey) {
71404
71654
  switch (event.key) {
71405
71655
  case 'f':
71406
71656
  events.fire('inputEvent', 'frame', event);
@@ -71414,6 +71664,30 @@ class InputController {
71414
71664
  }
71415
71665
  }
71416
71666
  });
71667
+ // Pointer lock management for FPS mode on desktop
71668
+ events.on('cameraMode:changed', (value, prev) => {
71669
+ if (value === 'fps' && state.inputMode === 'desktop') {
71670
+ this._desktopInput._pointerLock = true;
71671
+ canvas.requestPointerLock();
71672
+ }
71673
+ else if (prev === 'fps') {
71674
+ this._desktopInput._pointerLock = false;
71675
+ if (document.pointerLockElement === canvas) {
71676
+ document.exitPointerLock();
71677
+ }
71678
+ }
71679
+ });
71680
+ document.addEventListener('pointerlockchange', () => {
71681
+ if (!document.pointerLockElement && state.cameraMode === 'fps') {
71682
+ events.fire('inputEvent', 'cancel');
71683
+ }
71684
+ });
71685
+ // Pointer lock request rejected (e.g., no user gesture, document hidden).
71686
+ // Revert to avoid being stuck in FPS mode without mouse capture.
71687
+ document.addEventListener('pointerlockerror', () => {
71688
+ this._desktopInput._pointerLock = false;
71689
+ events.fire('inputEvent', 'cancel');
71690
+ });
71417
71691
  }
71418
71692
  /**
71419
71693
  * @param dt - delta time in seconds
@@ -71426,29 +71700,41 @@ class InputController {
71426
71700
  const { key, button, mouse, wheel } = this._desktopInput.read();
71427
71701
  const { touch, pinch, count } = this._orbitInput.read();
71428
71702
  const { leftStick, rightStick } = this._gamepadInput.read();
71429
- const { state } = this.global;
71703
+ const { state, events } = this.global;
71430
71704
  const { camera } = this.global.camera;
71431
71705
  // update state
71432
71706
  this._state.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])));
71707
+ this._state.jump += key[keyCode.SPACE];
71433
71708
  this._state.touches += count[0];
71434
71709
  for (let i = 0; i < button.length; i++) {
71435
71710
  this._state.mouse[i] += button[i];
71436
71711
  }
71437
71712
  this._state.shift += key[keyCode.SHIFT];
71438
71713
  this._state.ctrl += key[keyCode.CTRL];
71439
- if (state.cameraMode !== 'fly' && this._state.axis.length() > 0) {
71440
- state.cameraMode = 'fly';
71714
+ const isFps = state.cameraMode === 'fps';
71715
+ const isFirstPerson = state.cameraMode === 'fly' || isFps;
71716
+ if (!isFirstPerson && this._state.axis.length() > 0) {
71717
+ events.fire('inputEvent', 'requestFirstPerson');
71441
71718
  }
71442
71719
  const orbit = +(state.cameraMode === 'orbit');
71443
- const fly = +(state.cameraMode === 'fly');
71720
+ const fly = +isFirstPerson;
71444
71721
  const double = +(this._state.touches > 1);
71445
71722
  const pan = this._state.mouse[2] || +(button[2] === -1) || double;
71446
71723
  const orbitFactor = fly ? camera.fov / 120 : 1;
71447
71724
  const { deltas } = this.frame;
71448
71725
  // desktop move
71449
71726
  const v = tmpV1.set(0, 0, 0);
71450
- const keyMove = this._state.axis.clone().normalize();
71727
+ const keyMove = this._state.axis.clone();
71728
+ if (isFps) {
71729
+ // In FPS mode, normalize only horizontal axes so jump doesn't reduce speed
71730
+ keyMove.y = 0;
71731
+ }
71732
+ keyMove.normalize();
71451
71733
  v.add(keyMove.mulScalar(fly * this.moveSpeed * (this._state.shift ? 4 : this._state.ctrl ? 0.25 : 1) * dt));
71734
+ if (isFps) {
71735
+ // Pass jump signal as raw Y; FPS controller uses move[1] > 0 as boolean trigger
71736
+ v.y = this._state.jump > 0 ? 1 : 0;
71737
+ }
71452
71738
  const panMove = screenToWorld(camera, mouse[0], mouse[1], distance);
71453
71739
  v.add(panMove.mulScalar(pan));
71454
71740
  const wheelMove = new Vec3(0, 0, -wheel[0]);
@@ -71493,6 +71779,605 @@ class InputController {
71493
71779
  }
71494
71780
  }
71495
71781
 
71782
+ // ---------------------------------------------------------------------------
71783
+ // WGSL compute shader: ray-march through the sparse voxel octree per pixel
71784
+ // ---------------------------------------------------------------------------
71785
+ const voxelOverlayWGSL = /* wgsl */ `
71786
+
71787
+ // Solid leaf sentinel: childMask=0xFF, baseOffset=0
71788
+ const SOLID_LEAF_MARKER: u32 = 0xFF000000u;
71789
+
71790
+ // Maximum DDA steps to prevent infinite loops
71791
+ const MAX_STEPS: u32 = 512u;
71792
+
71793
+ // Target wireframe edge width in pixels
71794
+ const EDGE_PIXELS: f32 = 1.5;
71795
+
71796
+ // Wireframe edge alpha
71797
+ const EDGE_ALPHA: f32 = 0.85;
71798
+
71799
+ // Interior fill alpha (subtle orientation tint)
71800
+ const FILL_ALPHA: f32 = 0.12;
71801
+
71802
+ struct Uniforms {
71803
+ invVP: mat4x4<f32>,
71804
+ screenWidth: u32,
71805
+ screenHeight: u32,
71806
+ gridMinX: f32,
71807
+ gridMinY: f32,
71808
+ gridMinZ: f32,
71809
+ voxelRes: f32,
71810
+ numVoxelsX: u32,
71811
+ numVoxelsY: u32,
71812
+ numVoxelsZ: u32,
71813
+ leafSize: u32,
71814
+ treeDepth: u32,
71815
+ projScaleY: f32,
71816
+ displayMode: u32,
71817
+ pad2: u32
71818
+ };
71819
+
71820
+ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
71821
+ @group(0) @binding(1) var<storage, read> nodes: array<u32>;
71822
+ @group(0) @binding(2) var<storage, read> leafData: array<u32>;
71823
+ @group(0) @binding(3) var outputTexture: texture_storage_2d<rgba8unorm, write>;
71824
+
71825
+ // ---- helpers ----
71826
+
71827
+ // Traverse the octree for block (bx, by, bz). Returns vec2u(result, emptyLevel):
71828
+ // result: 0 = empty, 1 = solid, 2+ = mixed leaf (2 + leafDataIndex)
71829
+ // emptyLevel: octree level at which emptiness was detected (only meaningful when result == 0)
71830
+ fn queryBlock(bx: i32, by: i32, bz: i32) -> vec2u {
71831
+ let depth = uniforms.treeDepth;
71832
+ var nodeIndex: u32 = 0u;
71833
+
71834
+ for (var level: u32 = depth - 1u; ; ) {
71835
+ let node = nodes[nodeIndex];
71836
+
71837
+ // Solid leaf sentinel
71838
+ if (node == SOLID_LEAF_MARKER) {
71839
+ return vec2u(1u, 0u);
71840
+ }
71841
+
71842
+ let childMask = (node >> 24u) & 0xFFu;
71843
+
71844
+ // childMask == 0 means this is a mixed leaf node
71845
+ if (childMask == 0u) {
71846
+ let leafIdx = node & 0x00FFFFFFu;
71847
+ return vec2u(2u + leafIdx, 0u);
71848
+ }
71849
+
71850
+ // Determine octant at this level
71851
+ let bitX = (u32(bx) >> level) & 1u;
71852
+ let bitY = (u32(by) >> level) & 1u;
71853
+ let bitZ = (u32(bz) >> level) & 1u;
71854
+ let octant = (bitZ << 2u) | (bitY << 1u) | bitX;
71855
+
71856
+ // Check if child exists
71857
+ if ((childMask & (1u << octant)) == 0u) {
71858
+ return vec2u(0u, level);
71859
+ }
71860
+
71861
+ // Compute child index
71862
+ let baseOffset = node & 0x00FFFFFFu;
71863
+ let prefix = (1u << octant) - 1u;
71864
+ let childOffset = countOneBits(childMask & prefix);
71865
+ nodeIndex = baseOffset + childOffset;
71866
+
71867
+ if (level == 0u) { break; }
71868
+ level -= 1u;
71869
+ }
71870
+
71871
+ // Reached leaf level
71872
+ let node = nodes[nodeIndex];
71873
+ if (node == SOLID_LEAF_MARKER) {
71874
+ return vec2u(1u, 0u);
71875
+ }
71876
+ let leafIdx = node & 0x00FFFFFFu;
71877
+ return vec2u(2u + leafIdx, 0u);
71878
+ }
71879
+
71880
+ // Ray-AABB intersection returning (tNear, tFar). If tNear > tFar → miss.
71881
+ fn intersectAABB(ro: vec3f, invDir: vec3f, bmin: vec3f, bmax: vec3f) -> vec2f {
71882
+ let t1 = (bmin - ro) * invDir;
71883
+ let t2 = (bmax - ro) * invDir;
71884
+ let tmin = min(t1, t2);
71885
+ let tmax = max(t1, t2);
71886
+ let tNear = max(max(tmin.x, tmin.y), tmin.z);
71887
+ let tFar = min(min(tmax.x, tmax.y), tmax.z);
71888
+ return vec2f(tNear, tFar);
71889
+ }
71890
+
71891
+ // Compute wireframe edge factor (0 = interior, 1 = on edge) for a hit point on a voxel cube.
71892
+ // Uses the median of the three per-axis face distances so it works on ANY face.
71893
+ fn edgeFactor(hitPos: vec3f, voxMin: vec3f, voxSize: f32, edgeWidth: f32) -> f32 {
71894
+ let local = (hitPos - voxMin) / voxSize;
71895
+
71896
+ // Distance to nearest face boundary for each axis
71897
+ let fx = min(local.x, 1.0 - local.x);
71898
+ let fy = min(local.y, 1.0 - local.y);
71899
+ let fz = min(local.z, 1.0 - local.z);
71900
+
71901
+ // Median of three values = second smallest = edge distance.
71902
+ // On a face, one of fx/fy/fz is ~0 (the face normal axis).
71903
+ // The median gives the smaller of the other two = distance to nearest edge.
71904
+ let edgeDist = max(min(fx, fy), min(max(fx, fy), fz));
71905
+
71906
+ return 1.0 - smoothstep(0.0, edgeWidth, edgeDist);
71907
+ }
71908
+
71909
+ // Shade a voxel hit, returning premultiplied RGBA
71910
+ fn shadeVoxelHit(hitPos: vec3f, voxMin: vec3f, voxelRes: f32, ro: vec3f, isSolid: bool) -> vec4f {
71911
+ let dist = length(hitPos - ro);
71912
+ let pixelWorld = 2.0 * dist / (f32(uniforms.screenHeight) * uniforms.projScaleY);
71913
+ let ew = clamp(EDGE_PIXELS * pixelWorld / voxelRes, 0.01, 0.5);
71914
+
71915
+ let ef = edgeFactor(hitPos, voxMin, voxelRes, ew);
71916
+ let distFade = clamp(1.0 - dist * 0.01, 0.2, 1.0);
71917
+
71918
+ let local = (hitPos - voxMin) / voxelRes;
71919
+ let fx = min(local.x, 1.0 - local.x);
71920
+ let fy = min(local.y, 1.0 - local.y);
71921
+ let fz = min(local.z, 1.0 - local.z);
71922
+
71923
+ var faceAxis: u32 = 0u;
71924
+ if (fy <= fx && fy <= fz) {
71925
+ faceAxis = 1u;
71926
+ } else if (fz <= fx) {
71927
+ faceAxis = 2u;
71928
+ }
71929
+
71930
+ var baseColor: vec3f;
71931
+ if (isSolid) {
71932
+ if (faceAxis == 0u) { baseColor = vec3f(1.0, 0.25, 0.2); }
71933
+ else if (faceAxis == 1u) { baseColor = vec3f(0.8, 0.15, 0.1); }
71934
+ else { baseColor = vec3f(0.55, 0.08, 0.05); }
71935
+ } else {
71936
+ if (faceAxis == 0u) { baseColor = vec3f(0.7, 0.7, 0.72); }
71937
+ else if (faceAxis == 1u) { baseColor = vec3f(0.5, 0.5, 0.52); }
71938
+ else { baseColor = vec3f(0.33, 0.33, 0.35); }
71939
+ }
71940
+
71941
+ let alpha = mix(FILL_ALPHA, EDGE_ALPHA, ef) * distFade;
71942
+
71943
+ return vec4f(mix(baseColor, vec3f(0.0), alpha) * alpha, alpha);
71944
+ }
71945
+
71946
+ // Blue (0) -> Cyan (0.25) -> Green (0.5) -> Yellow (0.75) -> Red (1.0)
71947
+ fn heatmap(t: f32) -> vec3f {
71948
+ let c = clamp(t, 0.0, 1.0);
71949
+ let r = clamp(min(c - 0.5, 1.0) * 2.0, 0.0, 1.0);
71950
+ let g = select(clamp(c * 4.0, 0.0, 1.0), clamp((1.0 - c) * 4.0, 0.0, 1.0), c > 0.5);
71951
+ let b = clamp(1.0 - c * 2.0, 0.0, 1.0);
71952
+ return vec3f(r, g, b);
71953
+ }
71954
+
71955
+ // ---- main ----
71956
+
71957
+ @compute @workgroup_size(8, 8, 1)
71958
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
71959
+ let px = i32(gid.x);
71960
+ let py = i32(gid.y);
71961
+ let sw = i32(uniforms.screenWidth);
71962
+ let sh = i32(uniforms.screenHeight);
71963
+
71964
+ if (px >= sw || py >= sh) {
71965
+ return;
71966
+ }
71967
+
71968
+ // Reconstruct world-space ray from pixel coordinates
71969
+ let ndcX = (f32(px) + 0.5) / f32(sw) * 2.0 - 1.0;
71970
+ let ndcY = -((f32(py) + 0.5) / f32(sh) * 2.0 - 1.0);
71971
+
71972
+ let clipNear = vec4f(ndcX, ndcY, 0.0, 1.0);
71973
+ let clipFar = vec4f(ndcX, ndcY, 1.0, 1.0);
71974
+
71975
+ var worldNear = uniforms.invVP * clipNear;
71976
+ worldNear = worldNear / worldNear.w;
71977
+ var worldFar = uniforms.invVP * clipFar;
71978
+ worldFar = worldFar / worldFar.w;
71979
+
71980
+ // Convert from PlayCanvas world space to voxel space (negate X and Y)
71981
+ let ro = vec3f(-worldNear.x, -worldNear.y, worldNear.z);
71982
+ let rd = normalize(vec3f(-(worldFar.x - worldNear.x), -(worldFar.y - worldNear.y), worldFar.z - worldNear.z));
71983
+
71984
+ // Grid AABB
71985
+ let gridMin = vec3f(uniforms.gridMinX, uniforms.gridMinY, uniforms.gridMinZ);
71986
+ let gridMax = gridMin + vec3f(
71987
+ f32(uniforms.numVoxelsX),
71988
+ f32(uniforms.numVoxelsY),
71989
+ f32(uniforms.numVoxelsZ)
71990
+ ) * uniforms.voxelRes;
71991
+
71992
+ let invDir = 1.0 / rd;
71993
+ let gridHit = intersectAABB(ro, invDir, gridMin, gridMax);
71994
+
71995
+ if (gridHit.x > gridHit.y) {
71996
+ textureStore(outputTexture, vec2i(px, py), vec4f(0.0));
71997
+ return;
71998
+ }
71999
+
72000
+ let tEntry = max(gridHit.x, 0.0) + 0.0001;
72001
+
72002
+ // Entry point in voxel-index space
72003
+ let entryWorld = ro + rd * tEntry;
72004
+ let voxelRes = uniforms.voxelRes;
72005
+ let lsf = f32(uniforms.leafSize);
72006
+ let blockRes = voxelRes * lsf;
72007
+ let leafSz = i32(uniforms.leafSize);
72008
+
72009
+ // Block-level DDA setup
72010
+ let entryBlock = (entryWorld - gridMin) / blockRes;
72011
+ let numBlocksX = i32(uniforms.numVoxelsX / uniforms.leafSize);
72012
+ let numBlocksY = i32(uniforms.numVoxelsY / uniforms.leafSize);
72013
+ let numBlocksZ = i32(uniforms.numVoxelsZ / uniforms.leafSize);
72014
+
72015
+ var bx = clamp(i32(floor(entryBlock.x)), 0, numBlocksX - 1);
72016
+ var by = clamp(i32(floor(entryBlock.y)), 0, numBlocksY - 1);
72017
+ var bz = clamp(i32(floor(entryBlock.z)), 0, numBlocksZ - 1);
72018
+
72019
+ let stepX = select(-1, 1, rd.x >= 0.0);
72020
+ let stepY = select(-1, 1, rd.y >= 0.0);
72021
+ let stepZ = select(-1, 1, rd.z >= 0.0);
72022
+
72023
+ let tDeltaX = abs(blockRes / rd.x);
72024
+ let tDeltaY = abs(blockRes / rd.y);
72025
+ let tDeltaZ = abs(blockRes / rd.z);
72026
+
72027
+ // tMax: t value to reach next block boundary along each axis
72028
+ let blockMinWorld = gridMin + vec3f(f32(bx), f32(by), f32(bz)) * blockRes;
72029
+ let nextBoundX = select(blockMinWorld.x, blockMinWorld.x + blockRes, rd.x >= 0.0);
72030
+ let nextBoundY = select(blockMinWorld.y, blockMinWorld.y + blockRes, rd.y >= 0.0);
72031
+ let nextBoundZ = select(blockMinWorld.z, blockMinWorld.z + blockRes, rd.z >= 0.0);
72032
+
72033
+ var tMaxX = (nextBoundX - ro.x) / rd.x;
72034
+ var tMaxY = (nextBoundY - ro.y) / rd.y;
72035
+ var tMaxZ = (nextBoundZ - ro.z) / rd.z;
72036
+
72037
+ var totalWork: u32 = 0u;
72038
+
72039
+ for (var step: u32 = 0u; step < MAX_STEPS; step++) {
72040
+ totalWork += 1u;
72041
+
72042
+ let qResult = queryBlock(bx, by, bz);
72043
+ let blockResult = qResult.x;
72044
+ let emptyLevel = qResult.y;
72045
+
72046
+ if (blockResult == 0u && emptyLevel >= 1u) {
72047
+ // Large empty region: advance the block DDA past the empty cell
72048
+ let cellBlocks = i32(1u << emptyLevel);
72049
+ let cellMask = ~(cellBlocks - 1);
72050
+ let cellXMin = bx & cellMask;
72051
+ let cellYMin = by & cellMask;
72052
+ let cellZMin = bz & cellMask;
72053
+
72054
+ for (var skip: u32 = 0u; skip < 128u; skip++) {
72055
+ totalWork += 1u;
72056
+
72057
+ if (tMaxX < tMaxY && tMaxX < tMaxZ) {
72058
+ bx += stepX;
72059
+ tMaxX += tDeltaX;
72060
+ if (bx < cellXMin || bx >= cellXMin + cellBlocks) { break; }
72061
+ } else if (tMaxY < tMaxZ) {
72062
+ by += stepY;
72063
+ tMaxY += tDeltaY;
72064
+ if (by < cellYMin || by >= cellYMin + cellBlocks) { break; }
72065
+ } else {
72066
+ bz += stepZ;
72067
+ tMaxZ += tDeltaZ;
72068
+ if (bz < cellZMin || bz >= cellZMin + cellBlocks) { break; }
72069
+ }
72070
+ }
72071
+ } else {
72072
+ if (blockResult != 0u) {
72073
+ let blockOrigin = gridMin + vec3f(f32(bx), f32(by), f32(bz)) * blockRes;
72074
+
72075
+ let blockMax = blockOrigin + vec3f(blockRes);
72076
+ let bHit = intersectAABB(ro, invDir, blockOrigin, blockMax);
72077
+ let tBlockEntry = max(bHit.x, 0.0);
72078
+
72079
+ // Voxel-level DDA within the block
72080
+ let entryVoxWorld = ro + rd * (tBlockEntry + 0.0001);
72081
+ let entryLocal = (entryVoxWorld - blockOrigin) / voxelRes;
72082
+ var vx = clamp(i32(floor(entryLocal.x)), 0, leafSz - 1);
72083
+ var vy = clamp(i32(floor(entryLocal.y)), 0, leafSz - 1);
72084
+ var vz = clamp(i32(floor(entryLocal.z)), 0, leafSz - 1);
72085
+
72086
+ let vTDeltaX = abs(voxelRes / rd.x);
72087
+ let vTDeltaY = abs(voxelRes / rd.y);
72088
+ let vTDeltaZ = abs(voxelRes / rd.z);
72089
+
72090
+ let voxOrigin = blockOrigin + vec3f(f32(vx), f32(vy), f32(vz)) * voxelRes;
72091
+ let vNextX = select(voxOrigin.x, voxOrigin.x + voxelRes, rd.x >= 0.0);
72092
+ let vNextY = select(voxOrigin.y, voxOrigin.y + voxelRes, rd.y >= 0.0);
72093
+ let vNextZ = select(voxOrigin.z, voxOrigin.z + voxelRes, rd.z >= 0.0);
72094
+
72095
+ var vTMaxX = (vNextX - ro.x) / rd.x;
72096
+ var vTMaxY = (vNextY - ro.y) / rd.y;
72097
+ var vTMaxZ = (vNextZ - ro.z) / rd.z;
72098
+
72099
+ var maskLo: u32 = 0u;
72100
+ var maskHi: u32 = 0u;
72101
+ if (blockResult > 1u) {
72102
+ let leafIdx = blockResult - 2u;
72103
+ maskLo = leafData[leafIdx * 2u];
72104
+ maskHi = leafData[leafIdx * 2u + 1u];
72105
+ }
72106
+
72107
+ for (var vStep: u32 = 0u; vStep < 12u; vStep++) {
72108
+ totalWork += 1u;
72109
+
72110
+ var isSolid = false;
72111
+
72112
+ if (blockResult == 1u) {
72113
+ isSolid = true;
72114
+ } else {
72115
+ let bitIndex = u32(vz) * 16u + u32(vy) * 4u + u32(vx);
72116
+ isSolid = select(
72117
+ (maskHi & (1u << (bitIndex - 32u))) != 0u,
72118
+ (maskLo & (1u << bitIndex)) != 0u,
72119
+ bitIndex < 32u
72120
+ );
72121
+ }
72122
+
72123
+ if (isSolid) {
72124
+ if (uniforms.displayMode == 0u) {
72125
+ let voxMin = blockOrigin + vec3f(f32(vx), f32(vy), f32(vz)) * voxelRes;
72126
+ let vHit = intersectAABB(ro, invDir, voxMin, voxMin + vec3f(voxelRes));
72127
+ let hitPos = ro + rd * max(vHit.x, 0.0);
72128
+ let result = shadeVoxelHit(hitPos, voxMin, voxelRes, ro, blockResult == 1u);
72129
+ textureStore(outputTexture, vec2i(px, py), result);
72130
+ } else {
72131
+ let effort = f32(totalWork) / 256.0;
72132
+ let color = heatmap(effort);
72133
+ textureStore(outputTexture, vec2i(px, py), vec4f(color, 1.0));
72134
+ }
72135
+ return;
72136
+ }
72137
+
72138
+ // Advance voxel DDA
72139
+ if (vTMaxX < vTMaxY && vTMaxX < vTMaxZ) {
72140
+ vx += stepX;
72141
+ vTMaxX += vTDeltaX;
72142
+ if (vx < 0 || vx >= leafSz) { break; }
72143
+ } else if (vTMaxY < vTMaxZ) {
72144
+ vy += stepY;
72145
+ vTMaxY += vTDeltaY;
72146
+ if (vy < 0 || vy >= leafSz) { break; }
72147
+ } else {
72148
+ vz += stepZ;
72149
+ vTMaxZ += vTDeltaZ;
72150
+ if (vz < 0 || vz >= leafSz) { break; }
72151
+ }
72152
+ }
72153
+ }
72154
+
72155
+ // Advance block DDA
72156
+ if (tMaxX < tMaxY && tMaxX < tMaxZ) {
72157
+ bx += stepX;
72158
+ tMaxX += tDeltaX;
72159
+ } else if (tMaxY < tMaxZ) {
72160
+ by += stepY;
72161
+ tMaxY += tDeltaY;
72162
+ } else {
72163
+ bz += stepZ;
72164
+ tMaxZ += tDeltaZ;
72165
+ }
72166
+ }
72167
+
72168
+ if (bx < 0 || by < 0 || bz < 0 ||
72169
+ bx >= numBlocksX || by >= numBlocksY || bz >= numBlocksZ) {
72170
+ break;
72171
+ }
72172
+ }
72173
+
72174
+ if (uniforms.displayMode == 0u) {
72175
+ textureStore(outputTexture, vec2i(px, py), vec4f(0.0));
72176
+ } else {
72177
+ let effort = f32(totalWork) / 256.0;
72178
+ let color = heatmap(effort);
72179
+ textureStore(outputTexture, vec2i(px, py), vec4f(color, 1.0));
72180
+ }
72181
+ }
72182
+ `;
72183
+ // ---------------------------------------------------------------------------
72184
+ // VoxelDebugOverlay class
72185
+ // ---------------------------------------------------------------------------
72186
+ class VoxelDebugOverlay {
72187
+ app;
72188
+ camera;
72189
+ compute;
72190
+ storageTexture;
72191
+ overlayMaterial;
72192
+ nodesBuffer;
72193
+ leafDataBuffer;
72194
+ collider;
72195
+ currentWidth = 0;
72196
+ currentHeight = 0;
72197
+ invVP = new Mat4();
72198
+ vpTemp = new Mat4();
72199
+ /** Whether the overlay is currently rendering. */
72200
+ enabled = false;
72201
+ /** Display mode: 'overlay' for wireframe debug, 'heatmap' for effort visualization. */
72202
+ mode = 'overlay';
72203
+ constructor(app, collider, camera) {
72204
+ this.app = app;
72205
+ this.camera = camera;
72206
+ this.collider = collider;
72207
+ const device = app.graphicsDevice;
72208
+ // Upload SVO node array as a read-only storage buffer
72209
+ const nodesData = collider.nodes;
72210
+ const nodesByteSize = Math.max(nodesData.byteLength, 4);
72211
+ this.nodesBuffer = new StorageBuffer(device, nodesByteSize, BUFFERUSAGE_COPY_DST);
72212
+ if (nodesData.byteLength > 0) {
72213
+ this.nodesBuffer.write(0, nodesData.buffer, nodesData.byteOffset, nodesData.byteLength);
72214
+ }
72215
+ // Upload leaf data as a read-only storage buffer
72216
+ const leafDataArr = collider.leafData;
72217
+ const leafByteSize = Math.max(leafDataArr.byteLength, 4);
72218
+ this.leafDataBuffer = new StorageBuffer(device, leafByteSize, BUFFERUSAGE_COPY_DST);
72219
+ if (leafDataArr.byteLength > 0) {
72220
+ this.leafDataBuffer.write(0, leafDataArr.buffer, leafDataArr.byteOffset, leafDataArr.byteLength);
72221
+ }
72222
+ // Create the initial storage texture (will be resized on first update)
72223
+ this.currentWidth = Math.max(device.width, 1);
72224
+ this.currentHeight = Math.max(device.height, 1);
72225
+ this.storageTexture = this.createStorageTexture(this.currentWidth, this.currentHeight);
72226
+ // Create compute shader
72227
+ const shader = new Shader(device, {
72228
+ name: 'VoxelDebugOverlay',
72229
+ shaderLanguage: SHADERLANGUAGE_WGSL,
72230
+ cshader: voxelOverlayWGSL,
72231
+ computeUniformBufferFormats: {
72232
+ uniforms: new UniformBufferFormat(device, [
72233
+ new UniformFormat('invVP', UNIFORMTYPE_MAT4),
72234
+ new UniformFormat('screenWidth', UNIFORMTYPE_UINT),
72235
+ new UniformFormat('screenHeight', UNIFORMTYPE_UINT),
72236
+ new UniformFormat('gridMinX', UNIFORMTYPE_FLOAT),
72237
+ new UniformFormat('gridMinY', UNIFORMTYPE_FLOAT),
72238
+ new UniformFormat('gridMinZ', UNIFORMTYPE_FLOAT),
72239
+ new UniformFormat('voxelRes', UNIFORMTYPE_FLOAT),
72240
+ new UniformFormat('numVoxelsX', UNIFORMTYPE_UINT),
72241
+ new UniformFormat('numVoxelsY', UNIFORMTYPE_UINT),
72242
+ new UniformFormat('numVoxelsZ', UNIFORMTYPE_UINT),
72243
+ new UniformFormat('leafSize', UNIFORMTYPE_UINT),
72244
+ new UniformFormat('treeDepth', UNIFORMTYPE_UINT),
72245
+ new UniformFormat('projScaleY', UNIFORMTYPE_FLOAT),
72246
+ new UniformFormat('displayMode', UNIFORMTYPE_UINT),
72247
+ new UniformFormat('pad2', UNIFORMTYPE_UINT)
72248
+ ])
72249
+ },
72250
+ computeBindGroupFormat: new BindGroupFormat(device, [
72251
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE),
72252
+ new BindStorageBufferFormat('nodes', SHADERSTAGE_COMPUTE, true),
72253
+ new BindStorageBufferFormat('leafData', SHADERSTAGE_COMPUTE, true),
72254
+ new BindStorageTextureFormat('outputTexture', PIXELFORMAT_RGBA8, TEXTUREDIMENSION_2D)
72255
+ ])
72256
+ });
72257
+ // Create compute instance
72258
+ this.compute = new Compute(device, shader, 'VoxelDebugOverlay');
72259
+ // Create overlay material with premultiplied alpha blending and a custom
72260
+ // fragment shader that preserves the texture's alpha channel (the built-in
72261
+ // getTextureShaderDesc hardcodes alpha = 1.0, which prevents blending).
72262
+ this.overlayMaterial = new ShaderMaterial();
72263
+ this.overlayMaterial.cull = CULLFACE_NONE;
72264
+ this.overlayMaterial.blendType = BLEND_PREMULTIPLIED;
72265
+ this.overlayMaterial.depthTest = false;
72266
+ this.overlayMaterial.depthWrite = false;
72267
+ this.overlayMaterial.setParameter('colorMap', this.storageTexture);
72268
+ this.overlayMaterial.shaderDesc = {
72269
+ uniqueName: 'VoxelOverlayComposite',
72270
+ vertexGLSL: /* glsl */ `
72271
+ attribute vec2 vertex_position;
72272
+ uniform mat4 matrix_model;
72273
+ varying vec2 uv0;
72274
+ void main(void) {
72275
+ gl_Position = matrix_model * vec4(vertex_position, 0, 1);
72276
+ uv0 = vertex_position.xy + 0.5;
72277
+ }
72278
+ `,
72279
+ vertexWGSL: /* wgsl */ `
72280
+ attribute vertex_position: vec2f;
72281
+ uniform matrix_model: mat4x4f;
72282
+ varying uv0: vec2f;
72283
+ @vertex fn vertexMain(input: VertexInput) -> VertexOutput {
72284
+ var output: VertexOutput;
72285
+ output.position = uniform.matrix_model * vec4f(input.vertex_position, 0.0, 1.0);
72286
+ output.uv0 = input.vertex_position.xy + vec2f(0.5);
72287
+ return output;
72288
+ }
72289
+ `,
72290
+ fragmentGLSL: /* glsl */ `
72291
+ varying vec2 uv0;
72292
+ uniform sampler2D colorMap;
72293
+ void main(void) {
72294
+ gl_FragColor = texture2D(colorMap, uv0);
72295
+ }
72296
+ `,
72297
+ fragmentWGSL: /* wgsl */ `
72298
+ varying uv0: vec2f;
72299
+ var colorMap: texture_2d<f32>;
72300
+ var colorMapSampler: sampler;
72301
+ @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
72302
+ var output: FragmentOutput;
72303
+ output.color = textureSample(colorMap, colorMapSampler, input.uv0);
72304
+ return output;
72305
+ }
72306
+ `,
72307
+ attributes: { vertex_position: SEMANTIC_POSITION }
72308
+ };
72309
+ this.overlayMaterial.update();
72310
+ }
72311
+ createStorageTexture(width, height) {
72312
+ return new Texture(this.app.graphicsDevice, {
72313
+ name: 'VoxelOverlay-Storage',
72314
+ width,
72315
+ height,
72316
+ format: PIXELFORMAT_RGBA8,
72317
+ mipmaps: false,
72318
+ addressU: 3, // ADDRESS_CLAMP_TO_EDGE
72319
+ addressV: 3, // ADDRESS_CLAMP_TO_EDGE
72320
+ storage: true
72321
+ });
72322
+ }
72323
+ update() {
72324
+ if (!this.enabled)
72325
+ return;
72326
+ const { app, camera, compute, collider } = this;
72327
+ const device = app.graphicsDevice;
72328
+ const width = device.width;
72329
+ const height = device.height;
72330
+ if (width <= 0 || height <= 0)
72331
+ return;
72332
+ // Resize storage texture if screen dimensions changed
72333
+ if (width !== this.currentWidth || height !== this.currentHeight) {
72334
+ this.storageTexture.destroy();
72335
+ this.currentWidth = width;
72336
+ this.currentHeight = height;
72337
+ this.storageTexture = this.createStorageTexture(width, height);
72338
+ // Update the overlay material to reference the new texture
72339
+ this.overlayMaterial.setParameter('colorMap', this.storageTexture);
72340
+ this.overlayMaterial.update();
72341
+ }
72342
+ // Compute inverse view-projection matrix
72343
+ const cam = camera.camera;
72344
+ this.vpTemp.mul2(cam.projectionMatrix, cam.viewMatrix);
72345
+ this.invVP.copy(this.vpTemp).invert();
72346
+ // Set compute uniforms
72347
+ compute.setParameter('invVP', this.invVP.data);
72348
+ compute.setParameter('screenWidth', width);
72349
+ compute.setParameter('screenHeight', height);
72350
+ compute.setParameter('gridMinX', collider.gridMinX);
72351
+ compute.setParameter('gridMinY', collider.gridMinY);
72352
+ compute.setParameter('gridMinZ', collider.gridMinZ);
72353
+ compute.setParameter('voxelRes', collider.voxelResolution);
72354
+ compute.setParameter('numVoxelsX', collider.numVoxelsX);
72355
+ compute.setParameter('numVoxelsY', collider.numVoxelsY);
72356
+ compute.setParameter('numVoxelsZ', collider.numVoxelsZ);
72357
+ compute.setParameter('leafSize', collider.leafSize);
72358
+ compute.setParameter('treeDepth', collider.treeDepth);
72359
+ compute.setParameter('projScaleY', cam.projectionMatrix.data[5]);
72360
+ compute.setParameter('displayMode', this.mode === 'heatmap' ? 1 : 0);
72361
+ compute.setParameter('pad2', 0);
72362
+ // Set storage buffers and output texture
72363
+ compute.setParameter('nodes', this.nodesBuffer);
72364
+ compute.setParameter('leafData', this.leafDataBuffer);
72365
+ compute.setParameter('outputTexture', this.storageTexture);
72366
+ // Dispatch compute shader
72367
+ const workgroupsX = Math.ceil(width / 8);
72368
+ const workgroupsY = Math.ceil(height / 8);
72369
+ compute.setupDispatch(workgroupsX, workgroupsY, 1);
72370
+ device.computeDispatch([compute], 'VoxelDebugOverlay');
72371
+ // Composite overlay on top of the scene
72372
+ app.drawTexture(0, 0, 2, 2, null, this.overlayMaterial);
72373
+ }
72374
+ destroy() {
72375
+ this.nodesBuffer?.destroy();
72376
+ this.leafDataBuffer?.destroy();
72377
+ this.storageTexture?.destroy();
72378
+ }
72379
+ }
72380
+
71496
72381
  const gammaChunkGlsl = `
71497
72382
  vec3 prepareOutputFromGamma(vec3 gammaColor) {
71498
72383
  return gammaColor;
@@ -71573,8 +72458,9 @@ class Viewer {
71573
72458
  cameraManager;
71574
72459
  annotations;
71575
72460
  forceRenderNextFrame = false;
72461
+ voxelOverlay = null;
71576
72462
  origChunks;
71577
- constructor(global, gsplatLoad, skyboxLoad) {
72463
+ constructor(global, gsplatLoad, skyboxLoad, voxelLoad) {
71578
72464
  this.global = global;
71579
72465
  const { app, settings, config, events, state, camera } = global;
71580
72466
  const { graphicsDevice } = app;
@@ -71688,14 +72574,19 @@ class Viewer {
71688
72574
  applyCamera(this.cameraManager.camera);
71689
72575
  }
71690
72576
  });
72577
+ // Render voxel debug overlay
72578
+ app.on('prerender', () => {
72579
+ this.voxelOverlay?.update();
72580
+ });
71691
72581
  // update state on first frame
71692
72582
  events.on('firstFrame', () => {
71693
72583
  state.loaded = true;
71694
72584
  state.animationPaused = !!config.noanim;
71695
72585
  });
71696
72586
  // wait for the model to load
71697
- Promise.all([gsplatLoad, skyboxLoad]).then((results) => {
72587
+ Promise.all([gsplatLoad, skyboxLoad, voxelLoad]).then((results) => {
71698
72588
  const gsplat = results[0].gsplat;
72589
+ const collider = results[2];
71699
72590
  // get scene bounding box
71700
72591
  const gsplatBbox = gsplat.customAabb;
71701
72592
  if (gsplatBbox) {
@@ -71705,7 +72596,18 @@ class Viewer {
71705
72596
  this.annotations = new Annotations(global, this.cameraFrame != null);
71706
72597
  }
71707
72598
  this.inputController = new InputController(global);
71708
- this.cameraManager = new CameraManager(global, sceneBound);
72599
+ state.hasCollision = !!collider;
72600
+ // Create voxel debug overlay in WebGPU only
72601
+ if (collider && config.webgpu) {
72602
+ this.voxelOverlay = new VoxelDebugOverlay(app, collider, camera);
72603
+ this.voxelOverlay.mode = config.heatmap ? 'heatmap' : 'overlay';
72604
+ state.hasVoxelOverlay = true;
72605
+ events.on('voxelOverlayEnabled:changed', (value) => {
72606
+ this.voxelOverlay.enabled = value;
72607
+ app.renderNextFrame = true;
72608
+ });
72609
+ }
72610
+ this.cameraManager = new CameraManager(global, sceneBound, collider);
71709
72611
  applyCamera(this.cameraManager.camera);
71710
72612
  const { instance } = gsplat;
71711
72613
  if (instance) {
@@ -71834,6 +72736,678 @@ class Viewer {
71834
72736
  }
71835
72737
  }
71836
72738
 
72739
+ /**
72740
+ * Solid leaf node marker: childMask = 0xFF, baseOffset = 0.
72741
+ * Unambiguous because BFS layout guarantees children always come after their parent,
72742
+ * so baseOffset = 0 is never valid for an interior node.
72743
+ */
72744
+ const SOLID_LEAF_MARKER = 0xFF000000 >>> 0;
72745
+ /** Minimum penetration depth to report a collision (avoids floating-point noise at corners) */
72746
+ const PENETRATION_EPSILON = 1e-4;
72747
+ /**
72748
+ * Count the number of set bits in a 32-bit integer.
72749
+ *
72750
+ * @param n - 32-bit integer.
72751
+ * @returns Number of bits set to 1.
72752
+ */
72753
+ function popcount(n) {
72754
+ n >>>= 0;
72755
+ n -= ((n >>> 1) & 0x55555555);
72756
+ n = (n & 0x33333333) + ((n >>> 2) & 0x33333333);
72757
+ return (((n + (n >>> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24;
72758
+ }
72759
+ /**
72760
+ * Runtime sparse voxel octree collider.
72761
+ *
72762
+ * Loads the two-file format (.voxel.json + .voxel.bin) produced by
72763
+ * splat-transform's writeVoxel and provides point and sphere collision queries.
72764
+ */
72765
+ class VoxelCollider {
72766
+ /** Grid-aligned bounds (min xyz) */
72767
+ _gridMinX;
72768
+ _gridMinY;
72769
+ _gridMinZ;
72770
+ /** Number of voxels along each axis */
72771
+ _numVoxelsX;
72772
+ _numVoxelsY;
72773
+ _numVoxelsZ;
72774
+ /** Size of each voxel in world units */
72775
+ _voxelResolution;
72776
+ /** Voxels per leaf dimension (always 4) */
72777
+ _leafSize;
72778
+ /** Maximum tree depth (number of octree levels above the leaf level) */
72779
+ _treeDepth;
72780
+ /** Flat Laine-Karras node array */
72781
+ _nodes;
72782
+ /** Leaf voxel masks: pairs of (lo, hi) Uint32 per mixed leaf */
72783
+ _leafData;
72784
+ /** Pre-allocated scratch push-out vector to avoid per-frame allocations */
72785
+ _push = { x: 0, y: 0, z: 0 };
72786
+ /** Pre-allocated constraint normals for iterative corner resolution (max 3 walls) */
72787
+ _constraintNormals = [
72788
+ { x: 0, y: 0, z: 0 },
72789
+ { x: 0, y: 0, z: 0 },
72790
+ { x: 0, y: 0, z: 0 }
72791
+ ];
72792
+ constructor(metadata, nodes, leafData) {
72793
+ this._gridMinX = metadata.gridBounds.min[0];
72794
+ this._gridMinY = metadata.gridBounds.min[1];
72795
+ this._gridMinZ = metadata.gridBounds.min[2];
72796
+ const res = metadata.voxelResolution;
72797
+ this._numVoxelsX = Math.round((metadata.gridBounds.max[0] - metadata.gridBounds.min[0]) / res);
72798
+ this._numVoxelsY = Math.round((metadata.gridBounds.max[1] - metadata.gridBounds.min[1]) / res);
72799
+ this._numVoxelsZ = Math.round((metadata.gridBounds.max[2] - metadata.gridBounds.min[2]) / res);
72800
+ this._voxelResolution = res;
72801
+ this._leafSize = metadata.leafSize;
72802
+ this._treeDepth = metadata.treeDepth;
72803
+ this._nodes = nodes;
72804
+ this._leafData = leafData;
72805
+ }
72806
+ /**
72807
+ * Grid-aligned bounds minimum X in world units.
72808
+ *
72809
+ * @returns {number} The minimum X coordinate.
72810
+ */
72811
+ get gridMinX() {
72812
+ return this._gridMinX;
72813
+ }
72814
+ /**
72815
+ * Grid-aligned bounds minimum Y in world units.
72816
+ *
72817
+ * @returns {number} The minimum Y coordinate.
72818
+ */
72819
+ get gridMinY() {
72820
+ return this._gridMinY;
72821
+ }
72822
+ /**
72823
+ * Grid-aligned bounds minimum Z in world units.
72824
+ *
72825
+ * @returns {number} The minimum Z coordinate.
72826
+ */
72827
+ get gridMinZ() {
72828
+ return this._gridMinZ;
72829
+ }
72830
+ /**
72831
+ * Number of voxels along the X axis.
72832
+ *
72833
+ * @returns {number} The voxel count on X.
72834
+ */
72835
+ get numVoxelsX() {
72836
+ return this._numVoxelsX;
72837
+ }
72838
+ /**
72839
+ * Number of voxels along the Y axis.
72840
+ *
72841
+ * @returns {number} The voxel count on Y.
72842
+ */
72843
+ get numVoxelsY() {
72844
+ return this._numVoxelsY;
72845
+ }
72846
+ /**
72847
+ * Number of voxels along the Z axis.
72848
+ *
72849
+ * @returns {number} The voxel count on Z.
72850
+ */
72851
+ get numVoxelsZ() {
72852
+ return this._numVoxelsZ;
72853
+ }
72854
+ /**
72855
+ * Size of each voxel in world units.
72856
+ *
72857
+ * @returns {number} The voxel resolution.
72858
+ */
72859
+ get voxelResolution() {
72860
+ return this._voxelResolution;
72861
+ }
72862
+ /**
72863
+ * Voxels per leaf dimension (always 4).
72864
+ *
72865
+ * @returns {number} The leaf size.
72866
+ */
72867
+ get leafSize() {
72868
+ return this._leafSize;
72869
+ }
72870
+ /**
72871
+ * Maximum tree depth (number of octree levels above the leaf level).
72872
+ *
72873
+ * @returns {number} The tree depth.
72874
+ */
72875
+ get treeDepth() {
72876
+ return this._treeDepth;
72877
+ }
72878
+ /**
72879
+ * Flat Laine-Karras node array (read-only access for GPU upload).
72880
+ *
72881
+ * @returns {Uint32Array} The node array.
72882
+ */
72883
+ get nodes() {
72884
+ return this._nodes;
72885
+ }
72886
+ /**
72887
+ * Leaf voxel masks: pairs of (lo, hi) Uint32 per mixed leaf (read-only access for GPU upload).
72888
+ *
72889
+ * @returns {Uint32Array} The leaf data array.
72890
+ */
72891
+ get leafData() {
72892
+ return this._leafData;
72893
+ }
72894
+ /**
72895
+ * Load a VoxelCollider from a .voxel.json URL.
72896
+ * The corresponding .voxel.bin is inferred by replacing the extension.
72897
+ *
72898
+ * @param jsonUrl - URL to the .voxel.json metadata file.
72899
+ * @returns A promise resolving to a VoxelCollider instance.
72900
+ */
72901
+ static async load(jsonUrl) {
72902
+ // Fetch metadata
72903
+ const metaResponse = await fetch(jsonUrl);
72904
+ if (!metaResponse.ok) {
72905
+ throw new Error(`Failed to fetch voxel metadata: ${metaResponse.statusText}`);
72906
+ }
72907
+ const metadata = await metaResponse.json();
72908
+ // Fetch binary data
72909
+ const binUrl = jsonUrl.replace('.voxel.json', '.voxel.bin');
72910
+ const binResponse = await fetch(binUrl);
72911
+ if (!binResponse.ok) {
72912
+ throw new Error(`Failed to fetch voxel binary: ${binResponse.statusText}`);
72913
+ }
72914
+ const buffer = await binResponse.arrayBuffer();
72915
+ const view = new Uint32Array(buffer);
72916
+ const nodes = view.slice(0, metadata.nodeCount);
72917
+ const leafData = view.slice(metadata.nodeCount, metadata.nodeCount + metadata.leafDataCount);
72918
+ return new VoxelCollider(metadata, nodes, leafData);
72919
+ }
72920
+ /**
72921
+ * Query whether a world-space point lies inside a solid voxel.
72922
+ *
72923
+ * @param x - World X coordinate.
72924
+ * @param y - World Y coordinate.
72925
+ * @param z - World Z coordinate.
72926
+ * @returns True if the point is inside a solid voxel.
72927
+ */
72928
+ queryPoint(x, y, z) {
72929
+ const ix = Math.floor((x - this.gridMinX) / this.voxelResolution);
72930
+ const iy = Math.floor((y - this.gridMinY) / this.voxelResolution);
72931
+ const iz = Math.floor((z - this.gridMinZ) / this.voxelResolution);
72932
+ return this.isVoxelSolid(ix, iy, iz);
72933
+ }
72934
+ /**
72935
+ * Query a sphere against the voxel grid and write a push-out vector to resolve penetration.
72936
+ * Uses iterative single-voxel resolution: each iteration finds the deepest penetrating voxel,
72937
+ * resolves it, then re-checks. This avoids over-push from summing multiple voxels and
72938
+ * naturally handles corners (2 iterations) and flat walls (1 iteration).
72939
+ *
72940
+ * @param cx - Sphere center X in world units.
72941
+ * @param cy - Sphere center Y in world units.
72942
+ * @param cz - Sphere center Z in world units.
72943
+ * @param radius - Sphere radius in world units.
72944
+ * @param out - Object to receive the push-out vector.
72945
+ * @returns True if a collision was detected and out was written.
72946
+ */
72947
+ querySphere(cx, cy, cz, radius, out) {
72948
+ if (this.nodes.length === 0) {
72949
+ return false;
72950
+ }
72951
+ const maxIterations = 4;
72952
+ let resolvedX = cx;
72953
+ let resolvedY = cy;
72954
+ let resolvedZ = cz;
72955
+ let totalPushX = 0;
72956
+ let totalPushY = 0;
72957
+ let totalPushZ = 0;
72958
+ let hadCollision = false;
72959
+ const push = this._push;
72960
+ // Constraint normals from previous iterations - prevents oscillation at corners
72961
+ // by ensuring subsequent pushes don't undo previous ones
72962
+ const normals = this._constraintNormals;
72963
+ let numNormals = 0;
72964
+ for (let iter = 0; iter < maxIterations; iter++) {
72965
+ if (!this.resolveDeepestPenetration(resolvedX, resolvedY, resolvedZ, radius)) {
72966
+ break;
72967
+ }
72968
+ hadCollision = true;
72969
+ let px = push.x;
72970
+ let py = push.y;
72971
+ let pz = push.z;
72972
+ // Project out components that contradict previous constraint normals
72973
+ for (let i = 0; i < numNormals; i++) {
72974
+ const n = normals[i];
72975
+ const dot = px * n.x + py * n.y + pz * n.z;
72976
+ if (dot < 0) {
72977
+ px -= dot * n.x;
72978
+ py -= dot * n.y;
72979
+ pz -= dot * n.z;
72980
+ }
72981
+ }
72982
+ // Record this push direction as a constraint normal
72983
+ const len = Math.sqrt(push.x * push.x + push.y * push.y + push.z * push.z);
72984
+ if (len > PENETRATION_EPSILON && numNormals < 3) {
72985
+ const invLen = 1.0 / len;
72986
+ const n = normals[numNormals];
72987
+ n.x = push.x * invLen;
72988
+ n.y = push.y * invLen;
72989
+ n.z = push.z * invLen;
72990
+ numNormals++;
72991
+ }
72992
+ resolvedX += px;
72993
+ resolvedY += py;
72994
+ resolvedZ += pz;
72995
+ totalPushX += px;
72996
+ totalPushY += py;
72997
+ totalPushZ += pz;
72998
+ }
72999
+ // Only report collision if the total push is meaningful
73000
+ const totalPushSq = totalPushX * totalPushX + totalPushY * totalPushY + totalPushZ * totalPushZ;
73001
+ const hasSignificantPush = hadCollision && totalPushSq > PENETRATION_EPSILON * PENETRATION_EPSILON;
73002
+ if (hasSignificantPush) {
73003
+ out.x = totalPushX;
73004
+ out.y = totalPushY;
73005
+ out.z = totalPushZ;
73006
+ }
73007
+ return hasSignificantPush;
73008
+ }
73009
+ /**
73010
+ * Query a vertical capsule against the voxel grid and write a push-out vector to resolve
73011
+ * penetration. The capsule is a line segment from (cx, cy - halfHeight, cz) to
73012
+ * (cx, cy + halfHeight, cz) swept by radius. Uses the same iterative deepest-penetration
73013
+ * approach as querySphere.
73014
+ *
73015
+ * @param cx - Capsule center X in world units.
73016
+ * @param cy - Capsule center Y in world units.
73017
+ * @param cz - Capsule center Z in world units.
73018
+ * @param halfHeight - Half-height of the capsule's inner line segment in world units.
73019
+ * @param radius - Capsule radius in world units.
73020
+ * @param out - Object to receive the push-out vector.
73021
+ * @returns True if a collision was detected and out was written.
73022
+ */
73023
+ queryCapsule(cx, cy, cz, halfHeight, radius, out) {
73024
+ if (this.nodes.length === 0) {
73025
+ return false;
73026
+ }
73027
+ const maxIterations = 4;
73028
+ let resolvedX = cx;
73029
+ let resolvedY = cy;
73030
+ let resolvedZ = cz;
73031
+ let totalPushX = 0;
73032
+ let totalPushY = 0;
73033
+ let totalPushZ = 0;
73034
+ let hadCollision = false;
73035
+ const push = this._push;
73036
+ // Constraint normals from previous iterations - prevents oscillation at corners
73037
+ // by ensuring subsequent pushes don't undo previous ones
73038
+ const normals = this._constraintNormals;
73039
+ let numNormals = 0;
73040
+ for (let iter = 0; iter < maxIterations; iter++) {
73041
+ if (!this.resolveDeepestPenetrationCapsule(resolvedX, resolvedY, resolvedZ, halfHeight, radius)) {
73042
+ break;
73043
+ }
73044
+ hadCollision = true;
73045
+ let px = push.x;
73046
+ let py = push.y;
73047
+ let pz = push.z;
73048
+ // Project out components that contradict previous constraint normals
73049
+ for (let i = 0; i < numNormals; i++) {
73050
+ const n = normals[i];
73051
+ const dot = px * n.x + py * n.y + pz * n.z;
73052
+ if (dot < 0) {
73053
+ px -= dot * n.x;
73054
+ py -= dot * n.y;
73055
+ pz -= dot * n.z;
73056
+ }
73057
+ }
73058
+ // Record this push direction as a constraint normal
73059
+ const len = Math.sqrt(push.x * push.x + push.y * push.y + push.z * push.z);
73060
+ if (len > PENETRATION_EPSILON && numNormals < 3) {
73061
+ const invLen = 1.0 / len;
73062
+ const n = normals[numNormals];
73063
+ n.x = push.x * invLen;
73064
+ n.y = push.y * invLen;
73065
+ n.z = push.z * invLen;
73066
+ numNormals++;
73067
+ }
73068
+ resolvedX += px;
73069
+ resolvedY += py;
73070
+ resolvedZ += pz;
73071
+ totalPushX += px;
73072
+ totalPushY += py;
73073
+ totalPushZ += pz;
73074
+ }
73075
+ // Only report collision if the total push is meaningful
73076
+ const totalPushSq = totalPushX * totalPushX + totalPushY * totalPushY + totalPushZ * totalPushZ;
73077
+ const hasSignificantPush = hadCollision && totalPushSq > PENETRATION_EPSILON * PENETRATION_EPSILON;
73078
+ if (hasSignificantPush) {
73079
+ out.x = totalPushX;
73080
+ out.y = totalPushY;
73081
+ out.z = totalPushZ;
73082
+ }
73083
+ return hasSignificantPush;
73084
+ }
73085
+ /**
73086
+ * Find the single deepest penetrating voxel for the given sphere.
73087
+ * Writes the push-out vector into this._push.
73088
+ *
73089
+ * @param cx - Sphere center X.
73090
+ * @param cy - Sphere center Y.
73091
+ * @param cz - Sphere center Z.
73092
+ * @param radius - Sphere radius.
73093
+ * @returns True if a penetrating voxel was found.
73094
+ */
73095
+ resolveDeepestPenetration(cx, cy, cz, radius) {
73096
+ const { voxelResolution, gridMinX, gridMinY, gridMinZ } = this;
73097
+ const radiusSq = radius * radius;
73098
+ // Compute bounding box of the sphere in voxel indices
73099
+ const ixMin = Math.floor((cx - radius - gridMinX) / voxelResolution);
73100
+ const iyMin = Math.floor((cy - radius - gridMinY) / voxelResolution);
73101
+ const izMin = Math.floor((cz - radius - gridMinZ) / voxelResolution);
73102
+ const ixMax = Math.floor((cx + radius - gridMinX) / voxelResolution);
73103
+ const iyMax = Math.floor((cy + radius - gridMinY) / voxelResolution);
73104
+ const izMax = Math.floor((cz + radius - gridMinZ) / voxelResolution);
73105
+ let bestPushX = 0;
73106
+ let bestPushY = 0;
73107
+ let bestPushZ = 0;
73108
+ let bestPenetration = PENETRATION_EPSILON;
73109
+ let found = false;
73110
+ for (let iz = izMin; iz <= izMax; iz++) {
73111
+ for (let iy = iyMin; iy <= iyMax; iy++) {
73112
+ for (let ix = ixMin; ix <= ixMax; ix++) {
73113
+ if (!this.isVoxelSolid(ix, iy, iz)) {
73114
+ continue;
73115
+ }
73116
+ // Compute the world-space AABB of this voxel
73117
+ const vMinX = gridMinX + ix * voxelResolution;
73118
+ const vMinY = gridMinY + iy * voxelResolution;
73119
+ const vMinZ = gridMinZ + iz * voxelResolution;
73120
+ const vMaxX = vMinX + voxelResolution;
73121
+ const vMaxY = vMinY + voxelResolution;
73122
+ const vMaxZ = vMinZ + voxelResolution;
73123
+ // Find the nearest point on the voxel AABB to the sphere center
73124
+ const nearX = Math.max(vMinX, Math.min(cx, vMaxX));
73125
+ const nearY = Math.max(vMinY, Math.min(cy, vMaxY));
73126
+ const nearZ = Math.max(vMinZ, Math.min(cz, vMaxZ));
73127
+ // Vector from nearest point to sphere center
73128
+ const dx = cx - nearX;
73129
+ const dy = cy - nearY;
73130
+ const dz = cz - nearZ;
73131
+ const distSq = dx * dx + dy * dy + dz * dz;
73132
+ if (distSq >= radiusSq) {
73133
+ continue;
73134
+ }
73135
+ let px;
73136
+ let py;
73137
+ let pz;
73138
+ let penetration;
73139
+ if (distSq > 1e-12) {
73140
+ // Center is outside the voxel: push radially outward
73141
+ const dist = Math.sqrt(distSq);
73142
+ penetration = radius - dist;
73143
+ const invDist = 1.0 / dist;
73144
+ px = dx * invDist * penetration;
73145
+ py = dy * invDist * penetration;
73146
+ pz = dz * invDist * penetration;
73147
+ }
73148
+ else {
73149
+ // Center is inside the voxel: push to nearest face + radius
73150
+ // so the sphere surface ends up flush with the face
73151
+ const distNegX = cx - vMinX;
73152
+ const distPosX = vMaxX - cx;
73153
+ const distNegY = cy - vMinY;
73154
+ const distPosY = vMaxY - cy;
73155
+ const distNegZ = cz - vMinZ;
73156
+ const distPosZ = vMaxZ - cz;
73157
+ const escapeX = distNegX < distPosX ? -(distNegX + radius) : (distPosX + radius);
73158
+ const escapeY = distNegY < distPosY ? -(distNegY + radius) : (distPosY + radius);
73159
+ const escapeZ = distNegZ < distPosZ ? -(distNegZ + radius) : (distPosZ + radius);
73160
+ const absX = Math.abs(escapeX);
73161
+ const absY = Math.abs(escapeY);
73162
+ const absZ = Math.abs(escapeZ);
73163
+ px = 0;
73164
+ py = 0;
73165
+ pz = 0;
73166
+ if (absX <= absY && absX <= absZ) {
73167
+ px = escapeX;
73168
+ penetration = absX;
73169
+ }
73170
+ else if (absY <= absZ) {
73171
+ py = escapeY;
73172
+ penetration = absY;
73173
+ }
73174
+ else {
73175
+ pz = escapeZ;
73176
+ penetration = absZ;
73177
+ }
73178
+ }
73179
+ if (penetration > bestPenetration) {
73180
+ bestPenetration = penetration;
73181
+ bestPushX = px;
73182
+ bestPushY = py;
73183
+ bestPushZ = pz;
73184
+ found = true;
73185
+ }
73186
+ }
73187
+ }
73188
+ }
73189
+ if (found) {
73190
+ this._push.x = bestPushX;
73191
+ this._push.y = bestPushY;
73192
+ this._push.z = bestPushZ;
73193
+ }
73194
+ return found;
73195
+ }
73196
+ /**
73197
+ * Find the single deepest penetrating voxel for the given vertical capsule.
73198
+ * The capsule is a line segment from (cx, cy - halfHeight, cz) to (cx, cy + halfHeight, cz)
73199
+ * swept by radius. For each voxel, the closest point on the segment to the AABB is found,
73200
+ * then a sphere-AABB penetration test is performed from that point.
73201
+ * Writes the push-out vector into this._push.
73202
+ *
73203
+ * @param cx - Capsule center X.
73204
+ * @param cy - Capsule center Y.
73205
+ * @param cz - Capsule center Z.
73206
+ * @param halfHeight - Half-height of the capsule's inner line segment.
73207
+ * @param radius - Capsule radius.
73208
+ * @returns True if a penetrating voxel was found.
73209
+ */
73210
+ resolveDeepestPenetrationCapsule(cx, cy, cz, halfHeight, radius) {
73211
+ const { voxelResolution, gridMinX, gridMinY, gridMinZ } = this;
73212
+ const radiusSq = radius * radius;
73213
+ const segBottomY = cy - halfHeight;
73214
+ const segTopY = cy + halfHeight;
73215
+ // Compute bounding box of the capsule in voxel indices
73216
+ const ixMin = Math.floor((cx - radius - gridMinX) / voxelResolution);
73217
+ const iyMin = Math.floor((segBottomY - radius - gridMinY) / voxelResolution);
73218
+ const izMin = Math.floor((cz - radius - gridMinZ) / voxelResolution);
73219
+ const ixMax = Math.floor((cx + radius - gridMinX) / voxelResolution);
73220
+ const iyMax = Math.floor((segTopY + radius - gridMinY) / voxelResolution);
73221
+ const izMax = Math.floor((cz + radius - gridMinZ) / voxelResolution);
73222
+ let bestPushX = 0;
73223
+ let bestPushY = 0;
73224
+ let bestPushZ = 0;
73225
+ let bestPenetration = PENETRATION_EPSILON;
73226
+ let found = false;
73227
+ for (let iz = izMin; iz <= izMax; iz++) {
73228
+ for (let iy = iyMin; iy <= iyMax; iy++) {
73229
+ for (let ix = ixMin; ix <= ixMax; ix++) {
73230
+ if (!this.isVoxelSolid(ix, iy, iz)) {
73231
+ continue;
73232
+ }
73233
+ // Compute the world-space AABB of this voxel
73234
+ const vMinX = gridMinX + ix * voxelResolution;
73235
+ const vMinY = gridMinY + iy * voxelResolution;
73236
+ const vMinZ = gridMinZ + iz * voxelResolution;
73237
+ const vMaxX = vMinX + voxelResolution;
73238
+ const vMaxY = vMinY + voxelResolution;
73239
+ const vMaxZ = vMinZ + voxelResolution;
73240
+ // Find the closest Y on the capsule segment to this AABB.
73241
+ // For a vertical segment, X and Z are fixed so we only optimize Y.
73242
+ let segY;
73243
+ if (segTopY < vMinY) {
73244
+ // segment entirely below AABB
73245
+ segY = segTopY;
73246
+ }
73247
+ else if (segBottomY > vMaxY) {
73248
+ // segment entirely above AABB
73249
+ segY = segBottomY;
73250
+ }
73251
+ else {
73252
+ // ranges overlap - pick segment Y closest to AABB center
73253
+ const aabbCenterY = (vMinY + vMaxY) * 0.5;
73254
+ segY = Math.max(segBottomY, Math.min(segTopY, aabbCenterY));
73255
+ }
73256
+ // Now do sphere-AABB penetration from (cx, segY, cz)
73257
+ const nearX = Math.max(vMinX, Math.min(cx, vMaxX));
73258
+ const nearY = Math.max(vMinY, Math.min(segY, vMaxY));
73259
+ const nearZ = Math.max(vMinZ, Math.min(cz, vMaxZ));
73260
+ // Vector from nearest point to sphere center on segment
73261
+ const dx = cx - nearX;
73262
+ const dy = segY - nearY;
73263
+ const dz = cz - nearZ;
73264
+ const distSq = dx * dx + dy * dy + dz * dz;
73265
+ if (distSq >= radiusSq) {
73266
+ continue;
73267
+ }
73268
+ let px;
73269
+ let py;
73270
+ let pz;
73271
+ let penetration;
73272
+ if (distSq > 1e-12) {
73273
+ // Sphere center is outside the voxel: push radially outward
73274
+ const dist = Math.sqrt(distSq);
73275
+ penetration = radius - dist;
73276
+ const invDist = 1.0 / dist;
73277
+ px = dx * invDist * penetration;
73278
+ py = dy * invDist * penetration;
73279
+ pz = dz * invDist * penetration;
73280
+ }
73281
+ else {
73282
+ // Segment point is inside the voxel: push to nearest face + radius
73283
+ // so the capsule surface ends up flush with the face
73284
+ const distNegX = cx - vMinX;
73285
+ const distPosX = vMaxX - cx;
73286
+ const distNegY = segY - vMinY;
73287
+ const distPosY = vMaxY - segY;
73288
+ const distNegZ = cz - vMinZ;
73289
+ const distPosZ = vMaxZ - cz;
73290
+ const escapeX = distNegX < distPosX ? -(distNegX + radius) : (distPosX + radius);
73291
+ const escapeY = distNegY < distPosY ? -(distNegY + radius) : (distPosY + radius);
73292
+ const escapeZ = distNegZ < distPosZ ? -(distNegZ + radius) : (distPosZ + radius);
73293
+ const absX = Math.abs(escapeX);
73294
+ const absY = Math.abs(escapeY);
73295
+ const absZ = Math.abs(escapeZ);
73296
+ px = 0;
73297
+ py = 0;
73298
+ pz = 0;
73299
+ if (absX <= absY && absX <= absZ) {
73300
+ px = escapeX;
73301
+ penetration = absX;
73302
+ }
73303
+ else if (absY <= absZ) {
73304
+ py = escapeY;
73305
+ penetration = absY;
73306
+ }
73307
+ else {
73308
+ pz = escapeZ;
73309
+ penetration = absZ;
73310
+ }
73311
+ }
73312
+ if (penetration > bestPenetration) {
73313
+ bestPenetration = penetration;
73314
+ bestPushX = px;
73315
+ bestPushY = py;
73316
+ bestPushZ = pz;
73317
+ found = true;
73318
+ }
73319
+ }
73320
+ }
73321
+ }
73322
+ if (found) {
73323
+ this._push.x = bestPushX;
73324
+ this._push.y = bestPushY;
73325
+ this._push.z = bestPushZ;
73326
+ }
73327
+ return found;
73328
+ }
73329
+ /**
73330
+ * Test whether a voxel at the given grid indices is solid.
73331
+ *
73332
+ * @param ix - Global voxel X index.
73333
+ * @param iy - Global voxel Y index.
73334
+ * @param iz - Global voxel Z index.
73335
+ * @returns True if the voxel is solid.
73336
+ */
73337
+ isVoxelSolid(ix, iy, iz) {
73338
+ if (this.nodes.length === 0 ||
73339
+ ix < 0 || iy < 0 || iz < 0 ||
73340
+ ix >= this.numVoxelsX || iy >= this.numVoxelsY || iz >= this.numVoxelsZ) {
73341
+ return false;
73342
+ }
73343
+ const { leafSize, treeDepth } = this;
73344
+ // Convert voxel indices to block coordinates
73345
+ const blockX = Math.floor(ix / leafSize);
73346
+ const blockY = Math.floor(iy / leafSize);
73347
+ const blockZ = Math.floor(iz / leafSize);
73348
+ // Traverse octree from root to leaf
73349
+ let nodeIndex = 0;
73350
+ for (let level = treeDepth - 1; level >= 0; level--) {
73351
+ const node = this.nodes[nodeIndex] >>> 0;
73352
+ // Check for solid leaf sentinel first (has nonzero high byte)
73353
+ if (node === SOLID_LEAF_MARKER) {
73354
+ return true;
73355
+ }
73356
+ const childMask = (node >>> 24) & 0xFF;
73357
+ // If childMask is 0, this is a mixed leaf node
73358
+ if (childMask === 0) {
73359
+ return this.checkLeafByIndex(node, ix, iy, iz);
73360
+ }
73361
+ // Determine which octant the block falls into at this level
73362
+ const bitX = (blockX >>> level) & 1;
73363
+ const bitY = (blockY >>> level) & 1;
73364
+ const bitZ = (blockZ >>> level) & 1;
73365
+ const octant = (bitZ << 2) | (bitY << 1) | bitX;
73366
+ // Check if this octant has a child
73367
+ if ((childMask & (1 << octant)) === 0) {
73368
+ return false;
73369
+ }
73370
+ // Calculate child offset using popcount of lower bits
73371
+ const baseOffset = node & 0x00FFFFFF;
73372
+ const prefix = (1 << octant) - 1;
73373
+ const childOffset = popcount(childMask & prefix);
73374
+ nodeIndex = baseOffset + childOffset;
73375
+ }
73376
+ // We've reached the leaf level
73377
+ const node = this.nodes[nodeIndex] >>> 0;
73378
+ if (node === SOLID_LEAF_MARKER) {
73379
+ return true;
73380
+ }
73381
+ return this.checkLeafByIndex(node, ix, iy, iz);
73382
+ }
73383
+ /**
73384
+ * Check a mixed leaf node using voxel grid indices.
73385
+ * The solid leaf sentinel must be checked before calling this method.
73386
+ *
73387
+ * @param node - The mixed leaf node value (lower 24 bits = leafData index).
73388
+ * @param ix - Global voxel X index.
73389
+ * @param iy - Global voxel Y index.
73390
+ * @param iz - Global voxel Z index.
73391
+ * @returns True if the voxel is solid.
73392
+ */
73393
+ checkLeafByIndex(node, ix, iy, iz) {
73394
+ const leafDataIndex = node & 0x00FFFFFF;
73395
+ // Compute voxel coordinates within the 4x4x4 block
73396
+ const vx = ix & 3;
73397
+ const vy = iy & 3;
73398
+ const vz = iz & 3;
73399
+ // Bit index within the 64-bit mask: z * 16 + y * 4 + x
73400
+ const bitIndex = vz * 16 + vy * 4 + vx;
73401
+ // Read the appropriate 32-bit word (lo or hi)
73402
+ if (bitIndex < 32) {
73403
+ const lo = this.leafData[leafDataIndex * 2] >>> 0;
73404
+ return ((lo >>> bitIndex) & 1) === 1;
73405
+ }
73406
+ const hi = this.leafData[leafDataIndex * 2 + 1] >>> 0;
73407
+ return ((hi >>> (bitIndex - 32)) & 1) === 1;
73408
+ }
73409
+ }
73410
+
71837
73411
  /** @import { XrInputSource } from 'playcanvas' */
71838
73412
 
71839
73413
  /**
@@ -72740,7 +74314,7 @@ const initXr = (global) => {
72740
74314
  });
72741
74315
  };
72742
74316
 
72743
- var version = "1.14.2";
74317
+ var version = "1.15.0";
72744
74318
 
72745
74319
  const loadGsplat = async (app, config, progressCallback) => {
72746
74320
  const { contents, contentUrl, unified, aa } = config;
@@ -72898,6 +74472,9 @@ const main = async (canvas, settingsJson, config) => {
72898
74472
  animationPaused: true,
72899
74473
  hasAR: false,
72900
74474
  hasVR: false,
74475
+ hasCollision: false,
74476
+ hasVoxelOverlay: false,
74477
+ voxelOverlayEnabled: false,
72901
74478
  isFullscreen: false,
72902
74479
  controlsHidden: false
72903
74480
  });
@@ -72932,6 +74509,12 @@ const main = async (canvas, settingsJson, config) => {
72932
74509
  loadSkybox(app, config.skyboxUrl).then((asset) => {
72933
74510
  app.scene.envAtlas = asset.resource;
72934
74511
  });
74512
+ // Load voxel collision data
74513
+ const voxelLoad = config.voxelUrl &&
74514
+ VoxelCollider.load(config.voxelUrl).catch((err) => {
74515
+ console.warn('Failed to load voxel data:', err);
74516
+ return null;
74517
+ });
72935
74518
  // Load and play sound
72936
74519
  if (global.settings.soundUrl) {
72937
74520
  const sound = new Audio(global.settings.soundUrl);
@@ -72946,7 +74529,7 @@ const main = async (canvas, settingsJson, config) => {
72946
74529
  });
72947
74530
  }
72948
74531
  // Create the viewer
72949
- return new Viewer(global, gsplatLoad, skyboxLoad);
74532
+ return new Viewer(global, gsplatLoad, skyboxLoad, voxelLoad);
72950
74533
  };
72951
74534
  console.log(`SuperSplat Viewer v${version} | Engine v${version$1} (${revision})`);
72952
74535