All files / src/components/VirtualWalkthrough walkthrough-camera.ts

0% Statements 0/183
0% Branches 0/74
0% Functions 0/28
0% Lines 0/180

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { Quat, Script, Vec3, math } from 'playcanvas';
 
import { computeGroundPlane, yOnPlane } from './groundPlane';
 
/**
 * First-person walkthrough camera for Gaussian Splat scenes.
 *
 * - Pointer drag (mouse or touch) rotates the camera (pitch + yaw) with damping
 *   matching PlayCanvas CameraControls' rotateDamping=0.98.
 * - WASD / arrow keys move along the XZ plane using yaw-only direction, so
 *   movement is always horizontal regardless of where the camera is pointing.
 * - Mouse wheel moves forward/backward along the XZ plane.
 * - Y position is clamped between boundsMin.y and boundsMax.y; set them equal
 *   to lock vertical position entirely.
 * - Exposes reset() and focusPoint to stay compatible with useCameraPosition.
 */
 
const _quat = new Quat();
const _flatForward = new Vec3();
const _flatRight = new Vec3();
 
/** Frame-rate-independent damping lerp rate — matches PlayCanvas CameraControls. */
const dampRate = (damping: number, dt: number) => 1 - Math.pow(damping, dt * 1000);
 
/** Below this angular delta (degrees) the damped lerp snaps to its target and stops writing. */
const ANGLE_EPSILON = 1e-3;
 
/** Below this positional delta (world units) an idle frame skips the transform write. */
const POSITION_EPSILON = 1e-5;
 
export class WalkthroughCamera extends Script {
  static scriptName = 'walkthroughCamera';
 
  /** @attribute */
  moveSpeed = 0.3;
 
  /** @attribute */
  moveFastSpeed = 0.5;
 
  /** @attribute */
  moveSlowSpeed = 0.15;
 
  /** @attribute */
  lookSensitivity = 0.1;
 
  /** @attribute */
  rotateDamping = 0.98;
 
  /** @attribute */
  pitchMin = -85;
 
  /** @attribute */
  pitchMax = 85;
 
  /** @attribute */
  scrollSpeed = 0.001;
 
  /** @attribute */
  boundsCenter = new Vec3(0, 0, 0);
 
  /** @attribute */
  boundsRadius = 10;
 
  /** @attribute */
  freeFly = false;
 
  /** @attribute */
  enableFly = true;
 
  /** @attribute */
  averageCameraHeight = 0;
 
  /**
   * Three world-space points defining the ground plane.
   * When provided, the camera Y position is derived from this plane during non-freeFly movement.
   *
   * Not a React prop — must be set directly on the script instance via useEffect. The @playcanvas/react
   * Script component is wrapped in memo() whose shallowEquals comparator returns early on the first prop
   * with a .equals() method (Vec3), so any prop listed after boundsCenter is never compared and the
   * component won't re-render when it changes. Set via:
   *   app.root.findByName('camera')?.script?.walkthroughCamera.groundPlane = points
   * Should be updated if shallowEquals is fixed (see https://github.com/playcanvas/react/pull/298)
   */
  groundPlane: Vec3[] = [];
 
  // Current (damped) angles applied to the entity each frame.
  private _pitch = 0;
  private _yaw = 0;
 
  // Target angles — updated immediately on pointer move, entity lerps toward them.
  private _targetPitch = 0;
  private _targetYaw = 0;
 
  private _isDragging = false;
  private _lastX = 0;
  private _lastY = 0;
  private _scrollDelta = 0;
  private _keys: Partial<Record<string, boolean>> = {};
  private _removeListeners: (() => void)[] = [];
 
  // Cached plane derived from groundPlane attribute. Computed once when 3 points become available.
  private _planeNormal = new Vec3(0, 1, 0);
  private _planePoint = new Vec3(0, 0, 0);
  private _hasGroundPlane = false;
 
  private _syncGroundPlane() {
    if (this._hasGroundPlane || this.groundPlane.length < 3) {
      return;
    }
    const plane = computeGroundPlane(this.groundPlane);
    if (!plane) {
      return;
    }
    this._planeNormal.copy(plane.normal);
    this._planePoint.copy(plane.point);
    this._hasGroundPlane = true;
  }
 
  initialize() {
    // Start horizontal; reset() will set the correct pose once splat data loads.
    this._pitch = 0;
    this._yaw = 0;
    this._targetPitch = 0;
    this._targetYaw = 0;
 
    const canvas = this.app.graphicsDevice.canvas;
 
    const onPointerDown = (e: PointerEvent) => {
      this._isDragging = true;
      this._lastX = e.clientX;
      this._lastY = e.clientY;
      try {
        canvas.setPointerCapture(e.pointerId);
      } catch {
        // ignore — canvas may not be focusable yet
      }
    };
 
    const onPointerMove = (e: PointerEvent) => {
      if (!this._isDragging) {
        return;
      }
      const dx = e.clientX - this._lastX;
      const dy = e.clientY - this._lastY;
      this._lastX = e.clientX;
      this._lastY = e.clientY;
      this._targetYaw -= dx * this.lookSensitivity;
      this._targetPitch = math.clamp(this._targetPitch - dy * this.lookSensitivity, this.pitchMin, this.pitchMax);
    };
 
    const onPointerUp = (e: PointerEvent) => {
      this._isDragging = false;
      try {
        canvas.releasePointerCapture(e.pointerId);
      } catch {
        // ignore
      }
    };
 
    const onWheel = (e: WheelEvent) => {
      e.preventDefault();
      this._scrollDelta += e.deltaY;
    };
 
    const onContextMenu = (e: Event) => e.preventDefault();
 
    const onKeyDown = (e: KeyboardEvent) => {
      this._keys[e.code] = true;
    };
    const onKeyUp = (e: KeyboardEvent) => {
      this._keys[e.code] = false;
    };
    const onBlur = () => {
      this._keys = {};
      this._isDragging = false;
    };
 
    canvas.addEventListener('pointerdown', onPointerDown);
    canvas.addEventListener('pointermove', onPointerMove);
    canvas.addEventListener('pointerup', onPointerUp);
    canvas.addEventListener('pointercancel', onPointerUp);
    canvas.addEventListener('wheel', onWheel, { passive: false });
    canvas.addEventListener('contextmenu', onContextMenu);
    window.addEventListener('keydown', onKeyDown);
    window.addEventListener('keyup', onKeyUp);
    window.addEventListener('blur', onBlur);
 
    this._removeListeners = [
      () => canvas.removeEventListener('pointerdown', onPointerDown),
      () => canvas.removeEventListener('pointermove', onPointerMove),
      () => canvas.removeEventListener('pointerup', onPointerUp),
      () => canvas.removeEventListener('pointercancel', onPointerUp),
      () => canvas.removeEventListener('wheel', onWheel),
      () => canvas.removeEventListener('contextmenu', onContextMenu),
      () => window.removeEventListener('keydown', onKeyDown),
      () => window.removeEventListener('keyup', onKeyUp),
      () => window.removeEventListener('blur', onBlur),
    ];
  }
 
  /**
   * Position the camera at `position` looking toward `focus`.
   * Compatible with the useCameraPosition hook's reset() call.
   */
  reset(focus: Vec3, position: Vec3) {
    this.entity.setPosition(position);
 
    const dx = focus.x - position.x;
    const dy = focus.y - position.y;
    const dz = focus.z - position.z;
    const len = Math.sqrt(dx * dx + dy * dy + dz * dz);
    if (len > 0) {
      // PlayCanvas uses right-handed CCW Y rotation: forward = (-sinθ, 0, -cosθ),
      // so to look toward (dx, 0, dz): θ = atan2(-dx, -dz).
      this._yaw = Math.atan2(-dx, -dz) * (180 / Math.PI);
      this._pitch = Math.atan2(-dy, Math.sqrt(dx * dx + dz * dz)) * (180 / Math.PI);
      this._pitch = math.clamp(this._pitch, this.pitchMin, this.pitchMax);
    }
 
    // Snap targets so there's no damped drift from the previous pose.
    this._targetPitch = this._pitch;
    this._targetYaw = this._yaw;
 
    this.entity.setEulerAngles(this._pitch, this._yaw, 0);
  }
 
  get currentYaw(): number {
    return this._targetYaw;
  }
 
  get currentPitch(): number {
    return this._targetPitch;
  }
 
  /**
   * Orbit the camera by `yawDelta` degrees around `boundsCenter`.
   * Called by AutoRotator
   */
  orbitStep(yawDelta: number) {
    this._syncGroundPlane();
    const pos = this.entity.getPosition();
    const dx = pos.x - this.boundsCenter.x;
    const dz = pos.z - this.boundsCenter.z;
    const radius = Math.sqrt(dx * dx + dz * dz) || this.boundsRadius * 0.5;
    const currentAngle = Math.atan2(dz, dx);
    const newAngle = currentAngle + (yawDelta * Math.PI) / 180;
    const nx = this.boundsCenter.x + radius * Math.cos(newAngle);
    const nz = this.boundsCenter.z + radius * Math.sin(newAngle);
    const ny = this._hasGroundPlane
      ? yOnPlane(nx, nz, this._planeNormal, this._planePoint, this.boundsCenter.y) + this.averageCameraHeight
      : this.boundsCenter.y;
    this.entity.setPosition(nx, ny, nz);
 
    const faceDx = this.boundsCenter.x - nx;
    const faceDz = this.boundsCenter.z - nz;
    this._yaw = Math.atan2(-faceDx, -faceDz) * (180 / Math.PI);
    this._targetYaw = this._yaw;
    this.entity.setEulerAngles(this._pitch, this._yaw, 0);
  }
 
  /**
   * Returns the point directly in front of the camera.
   * Compatible with the useCameraPosition hook's focusPoint read.
   */
  get focusPoint(): Vec3 {
    const pos = this.entity.getPosition();
    _quat.setFromEulerAngles(this._pitch, this._yaw, 0);
    _quat.transformVector(Vec3.FORWARD, _flatForward);
 
    return new Vec3(pos.x + _flatForward.x, pos.y + _flatForward.y, pos.z + _flatForward.z);
  }
 
  update(dt: number) {
    this._syncGroundPlane();
 
    // Lerp current angles toward targets using the same damping as CameraControls.
    // Snap to the target once within ANGLE_EPSILON so the asymptotic lerp actually
    // settles instead of emitting ever-smaller micro-rotations for ~0.4s after each
    // drag. The gsplat sorter guards its own re-sorts with an epsilon, so this mainly
    // trims that sort tail; it does not affect per-frame rendering (autoRender does).
    const r = dampRate(this.rotateDamping, dt);
    let nextPitch = this._pitch + (this._targetPitch - this._pitch) * r;
    let nextYaw = this._yaw + (this._targetYaw - this._yaw) * r;
    if (Math.abs(this._targetPitch - nextPitch) < ANGLE_EPSILON) {
      nextPitch = this._targetPitch;
    }
    if (Math.abs(this._targetYaw - nextYaw) < ANGLE_EPSILON) {
      nextYaw = this._targetYaw;
    }
    nextPitch = math.clamp(nextPitch, this.pitchMin, this.pitchMax);
 
    // Only write the rotation when it actually changed, to avoid needlessly dirtying
    // the scene node once the angles have settled.
    const anglesChanged = nextPitch !== this._pitch || nextYaw !== this._yaw;
    this._pitch = nextPitch;
    this._yaw = nextYaw;
    if (anglesChanged) {
      this.entity.setEulerAngles(this._pitch, this._yaw, 0);
    }
 
    const pos = this.entity.getPosition();
    let nx = pos.x;
    let ny = pos.y;
    let nz = pos.z;
 
    if (this.enableFly) {
      const fast = this._keys.ShiftLeft || this._keys.ShiftRight;
      const slow = this._keys.ControlLeft || this._keys.ControlRight;
      const speed = (fast ? this.moveFastSpeed : slow ? this.moveSlowSpeed : this.moveSpeed) * dt;
 
      const fwd = (this._keys.KeyW || this._keys.ArrowUp ? 1 : 0) - (this._keys.KeyS || this._keys.ArrowDown ? 1 : 0);
      const strafe =
        (this._keys.KeyD || this._keys.ArrowRight ? 1 : 0) - (this._keys.KeyA || this._keys.ArrowLeft ? 1 : 0);
 
      const scrollFwd = -this._scrollDelta * this.scrollSpeed;
 
      if (fwd !== 0 || strafe !== 0 || scrollFwd !== 0) {
        // Use yaw-only rotation so movement is always horizontal.
        _quat.setFromEulerAngles(0, this._yaw, 0);
        _quat.transformVector(Vec3.FORWARD, _flatForward);
        _quat.transformVector(Vec3.RIGHT, _flatRight);
 
        nx += _flatForward.x * (fwd * speed + scrollFwd) + _flatRight.x * strafe * speed;
        nz += _flatForward.z * (fwd * speed + scrollFwd) + _flatRight.z * strafe * speed;
      }
 
      if (this.freeFly) {
        const up = (this._keys.KeyE ? 1 : 0) - (this._keys.KeyQ ? 1 : 0);
        if (up !== 0) {
          ny += up * speed;
        }
      }
    }
 
    this._scrollDelta = 0;
 
    if (!this.freeFly) {
      // Circular XZ clamp: project back onto the circle edge if outside.
      const cdx = nx - this.boundsCenter.x;
      const cdz = nz - this.boundsCenter.z;
      const dist = Math.sqrt(cdx * cdx + cdz * cdz);
      if (dist > this.boundsRadius) {
        const scale = this.boundsRadius / dist;
        nx = this.boundsCenter.x + cdx * scale;
        nz = this.boundsCenter.z + cdz * scale;
      }
    }
 
    const groundY = this._hasGroundPlane
      ? yOnPlane(nx, nz, this._planeNormal, this._planePoint, this.boundsCenter.y) + this.averageCameraHeight
      : this.boundsCenter.y;
    const targetY = this.freeFly ? ny : groundY;
    // Only write the position when it actually moved. This keeps the scene node clean on
    // idle frames; note it does not stop per-frame rasterization — while autoRender is on
    // the app renders every frame regardless of whether the transform changed.
    if (
      Math.abs(nx - pos.x) > POSITION_EPSILON ||
      Math.abs(targetY - pos.y) > POSITION_EPSILON ||
      Math.abs(nz - pos.z) > POSITION_EPSILON
    ) {
      this.entity.setPosition(nx, targetY, nz);
    }
  }
 
  destroy() {
    this._removeListeners.forEach((fn) => fn());
    this._removeListeners = [];
  }
}