{
  "name": "create-viewer",
  "description": "Create a renderer, a camera and a control, along basic rendering loop logic.",
  "dependencies": [
    "three"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "registryDependencies": [
    "dispose-tracker"
  ],
  "files": [
    {
      "path": "create-viewer.ts",
      "content": "import { Clock, EventDispatcher, Scene, WebGLRenderer } from 'three';\nimport createRenderer from './create-renderer';\nimport { createCamera } from './create-camera/create-camera';\nimport OffsetCamera from './create-camera/offset-camera';\nimport { disposeTracked } from '@3dvf/dispose-tracker/dispose-tracked';\nimport { OrbitControls } from './create-camera/orbit-controls';\n\nexport type Task = () => Promise<void>;\n\nexport type ViewerEvent = {\n  taskCompleted: { progression: number };\n  updated: object;\n  updatePreprocesses: {\n    camera: OffsetCamera;\n    renderer: WebGLRenderer;\n  };\n  resize: {\n    width: number;\n    height: number;\n  };\n  animate: {\n    delta: number;\n  };\n};\n\nexport type CreateViewerReturnType = {\n  launch: () => void,\n  addTasks: (tasks: Task[]) => void,\n  launchTasks: () => Promise<void>,\n  pause: () => void,\n  play: () => void,\n  dispose: () => void,\n  disableScene: () => void,\n  enableScene: () => void,\n  eventDispatcher: EventDispatcher<ViewerEvent>,\n  renderer: WebGLRenderer,\n  scene: Scene,\n  camera: OffsetCamera,\n  controls: OrbitControls\n}\n\nexport const createViewer = (element: HTMLElement) => {\n  if (!element) {\n    throw new Error('init: element not found');\n  }\n\n  const clock = new Clock();\n  const eventDispatcher = new EventDispatcher<ViewerEvent>();\n  let animationFrameHandle: number = -1;\n\n  const renderer = createRenderer(element);\n  const { camera, controls } = createCamera(renderer);\n\n  const scene = new Scene();\n\n  const tasks: Task[] = [];\n\n  const disableScene = () => {\n    scene.userData[\"disabled\"] = true;\n  }\n\n  const enableScene = () => {\n    scene.userData[\"disabled\"] = false;\n  }\n\n  const render = () => {\n    eventDispatcher.dispatchEvent({\n      type: 'updatePreprocesses',\n      camera,\n      renderer\n    });\n\n    if (scene.userData[\"disabled\"]) {\n      return;\n    }\n\n    renderer.render(scene, camera);\n  };\n\n  const update = () => {\n    // 1. Update animations\n    const delta = clock.getDelta();\n    eventDispatcher.dispatchEvent({ type: 'animate', delta });\n\n    // 2. Update controls after animations in case camera itself is animated\n    controls.update(0);\n\n    // 3. Render the scene\n    render();\n\n    eventDispatcher.dispatchEvent({ type: 'updated' });\n  };\n\n  const requestUpdate = () => {\n    animationFrameHandle = requestAnimationFrame(() => update());\n  };\n\n  const resize = () => {\n    const { parentElement } = renderer.domElement;\n    if (!parentElement) {\n      throw new Error('dom element has no parent');\n    }\n    const { clientWidth, clientHeight } = parentElement;\n    camera.aspect = clientWidth / clientHeight;\n    const isHorizontal = camera.aspect <= camera.verticalRatio;\n    camera.fov = isHorizontal\n      ? (Math.atan(\n        (Math.tan((camera.absoluteFov * Math.PI) / 360) * camera.verticalRatio) / camera.aspect\n      ) *\n        360) /\n      Math.PI\n      : camera.absoluteFov;\n    camera.updateProjectionMatrix();\n    renderer.setSize(clientWidth, clientHeight);\n\n    eventDispatcher.dispatchEvent({\n      type: 'resize',\n      width: clientWidth,\n      height: clientHeight\n    });\n    render();\n  };\n\n  // Enable looping behaviour but does not actually call the render loop\n  const activateRenderLoop = () => {\n    eventDispatcher.addEventListener('updated', requestUpdate);\n    clock.getDelta();\n  };\n\n  const launch = () => {\n    activateRenderLoop();\n\n    window.addEventListener('resize', resize, false);\n    resize();\n    update();\n  };\n\n  const pause = () => {\n    eventDispatcher.removeEventListener('updated', requestUpdate);\n    cancelAnimationFrame(animationFrameHandle);\n  };\n\n  const play = () => {\n    activateRenderLoop();\n    update();\n  };\n\n  const dispose = () => {\n    pause();\n    window.removeEventListener('resize', resize, false);\n\n    disposeTracked(scene);\n\n    controls.disconnect();\n    controls.dispose();\n\n    renderer.dispose();\n  };\n\n  const addTasks = (addedTasks: Task[]) => {\n    tasks.push(...addedTasks);\n  }\n\n  const launchTasks = async () => {\n    const taskCount = tasks.length;\n    let completedTaskCount = 0;\n    eventDispatcher.dispatchEvent({\n      type: \"taskCompleted\",\n      progression: 0,\n    });\n    await Promise.all(tasks.map(async (task: Task) => {\n      await task();\n      completedTaskCount++;\n      eventDispatcher.dispatchEvent({\n        type: \"taskCompleted\",\n        progression: completedTaskCount / taskCount,\n      });\n    }));\n\n    tasks.length = 0;\n  }\n\n  return {\n    launch,\n    addTasks,\n    launchTasks,\n    pause,\n    play,\n    dispose,\n    eventDispatcher,\n    renderer,\n    scene,\n    disableScene,\n    enableScene,\n    camera,\n    controls\n  };\n};\n"
    },
    {
      "path": "create-renderer.ts",
      "content": "import {\n  Color,\n  LinearSRGBColorSpace,\n  NoToneMapping,\n  WebGLRenderer,\n} from \"three\";\n\nexport default function createRenderer(element: HTMLElement): WebGLRenderer {\n  const renderer = new WebGLRenderer({\n    antialias: true,\n    alpha: true,\n    preserveDrawingBuffer: true,\n    stencil: true\n  });\n\n  renderer.setSize(element.clientWidth, element.clientHeight);\n  renderer.setClearColor(new Color(0, 0, 0), 0);\n\n  renderer.outputColorSpace = LinearSRGBColorSpace;\n  renderer.toneMapping = NoToneMapping;\n\n  renderer.clearColor();\n\n  element.appendChild(renderer.domElement);\n\n  return renderer;\n}\n"
    },
    {
      "path": "create-camera/create-camera.ts",
      "content": "import { WebGLRenderer } from \"three\";\nimport OffsetCamera from \"./offset-camera\";\nimport { OrbitControls } from \"./orbit-controls\";\n\nexport const createCamera = (renderer: WebGLRenderer) => {\n  const camera = new OffsetCamera(\n    75,\n    window.innerWidth / window.innerHeight,\n    0.1,\n    100,\n  );\n\n  const controls = new OrbitControls(camera, renderer.domElement);\n  controls.enableDamping = true;\n  controls.enablePan = false;\n  controls.minDistance = 1;\n  controls.maxDistance = 100;\n  controls.maxPolarAngle = 1.5;\n\n  camera.position.set(0, 1, 5);\n  controls.update(0);\n\n  return { camera, controls };\n};\n"
    },
    {
      "path": "create-camera/orbit-controls.ts",
      "content": "import {\n  EventDispatcher,\n  Matrix4,\n  MOUSE,\n  PerspectiveCamera,\n  Quaternion,\n  Spherical,\n  TOUCH,\n  Vector2,\n  Vector3\n} from 'three';\n\ntype OrbitControlsEvent = {\n  type: 'change' | 'start' | 'end';\n};\n\n/**\n * Fires when the camera has been transformed by the controls.\n *\n * @event OrbitControls#change\n */\nconst _changeEvent: OrbitControlsEvent = { type: 'change' };\n\n/**\n * Fires when an interaction was initiated.\n *\n * @event OrbitControls#start\n */\nconst _startEvent: OrbitControlsEvent = { type: 'start' };\n\n/**\n * Fires when an interaction has finished.\n *\n * @event OrbitControls#end\n */\nconst _endEvent: OrbitControlsEvent = { type: 'end' };\n\nconst _v = new Vector3();\nconst _twoPI = 2 * Math.PI;\n\nconst _STATE = {\n  NONE: -1,\n  ROTATE: 0,\n  DOLLY: 1,\n  PAN: 2,\n  TOUCH_ROTATE: 3,\n  TOUCH_PAN: 4,\n  TOUCH_DOLLY_PAN: 5,\n  TOUCH_DOLLY_ROTATE: 6\n};\nconst _EPS = 0.00001;\n\nconst MOUSE_MOVE_DOLLY_FACTOR = 0.03;\n\n/**\n * Orbit controls allow the camera to orbit around a target.\n *\n * Modified from https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js\n *\n * The coordinates system is as follow :\n * - right-handed, with Y as up, X as right and Z as backward\n * - Pitch goes to from PI when facing up, to 0 when facing down\n * - Yaw is at 0 when looking at origin from +Z axis, and goes to -PI when rotating left, and PI when rotating right. A yaw of -PI or PI is therefore equivalent, when looking at origin from the -Z axis.\n *\n * OrbitControls performs orbiting, dollying (zooming), and panning. Unlike {@link TrackballControls},\n * it maintains the \"up\" direction `object.up` (+Y by default).\n *\n * - Orbit: Left mouse / touch: one-finger move.\n * - Zoom: Middle mouse, or mousewheel / touch: two-finger spread or squish.\n * - Pan: Right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move.\n *\n * ```js\n * const controls = new OrbitControls( camera, renderer.domElement );\n *\n * // controls.update() must be called after any manual changes to the camera's transform\n * camera.position.set( 0, 20, 100 );\n * controls.update();\n *\n * function animate() {\n *\n * \t// required if controls.enableDamping or controls.autoRotate are set to true\n * \tcontrols.update();\n *\n * \trenderer.render( scene, camera );\n *\n * }\n *\n */\nclass OrbitControls extends EventDispatcher<{\n  change: OrbitControlsEvent;\n  start: OrbitControlsEvent;\n  end: OrbitControlsEvent;\n}> {\n  public camera: PerspectiveCamera;\n\n  public domElement: HTMLElement | null = null;\n\n  public state = _STATE.NONE;\n\n  /**\n   * The focus point of the controls, the `object` orbits around this.\n   * It can be updated manually at any point to change the focus of the controls.\n   */\n  public target = new Vector3();\n\n  /**\n   * How far you can dolly in (perspective camera only).\n   */\n  public minDistance = 0;\n\n  /**\n   * How far you can dolly out (perspective camera only).\n   */\n  public maxDistance = Infinity;\n\n  /**\n   * How far you can zoom in (orthographic camera only).\n   */\n  public minZoom = 0;\n\n  /**\n   * How far you can zoom out (orthographic camera only).\n   */\n  public maxZoom = Infinity;\n\n  /**\n   * The scene reference center, from which the target bounding box revolve around\n   */\n  public sceneCenter = new Vector3(0, 0, 0);\n\n  public sceneSize = 1;\n\n  /**\n   * The rotation of the target bounding box around the up axis\n   *\n   * @type {number}\n   */\n  public targetYaw = 0;\n\n  public minTarget = new Vector3(-Infinity, -Infinity, -Infinity);\n  public maxTarget = new Vector3(Infinity, Infinity, Infinity);\n\n  /**\n   * How far you can orbit vertically, lower limit. Range is `[0, Math.PI]` radians.\n   */\n  public minPolarAngle = 0;\n\n  /**\n   * How far you can orbit vertically, upper limit. Range is `[0, Math.PI]` radians.\n   */\n  public maxPolarAngle = Math.PI;\n\n  /**\n   * How far you can orbit horizontally, lower limit. If set, the interval `[ min, max ]`\n   * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`.\n   */\n  public minAzimuthAngle = -Infinity;\n\n  /**\n   * How far you can orbit horizontally, upper limit. If set, the interval `[ min, max ]`\n   * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`.\n   */\n  public maxAzimuthAngle = Infinity;\n\n  /**\n   * Set to `true` to enable damping (inertia), which can be used to give a sense of weight\n   * to the controls. Note that if this is enabled, you must call `update()` in your animation\n   * loop.\n   */\n  public enableDamping = false;\n\n  /**\n   * The damping inertia used if `enableDamping` is set to `true`.\n   *\n   * Note that for this to work, you must call `update()` in your animation loop.\n   */\n  public dampingFactor = 0.05;\n\n  /**\n   * The zoom damping inertia used if `enableDamping` is set to `true`.\n   *\n   * Note that for this to work, you must call `update()` in your animation loop.\n   */\n  public zoomDampingFactor = 0.05;\n\n  /**\n   * Enable or disable zooming (dollying) of the camera.\n   */\n  public enableZoom = true;\n\n  /**\n   * Speed of zooming / dollying.\n   */\n  public zoomSpeed = 1.0;\n\n  /**\n   * Enable or disable horizontal and vertical rotation of the camera.\n   *\n   * Note that it is possible to disable a single axis by setting the min and max of the\n   * `minPolarAngle` or `minAzimuthAngle` to the same value, which will cause the vertical\n   * or horizontal rotation to be fixed at that value.\n   */\n  public enableRotate = true;\n\n  /**\n   * Speed of rotation.\n   */\n  public rotateSpeed = 1.0;\n\n  /**\n   * How fast to rotate the camera when the keyboard is used.\n   */\n  public keyRotateSpeed = 1.0;\n\n  /**\n   * Enable or disable camera panning.\n   */\n  public enablePan = true;\n\n  /**\n   * Speed of panning.\n   */\n  public panSpeed = 1.0;\n\n  /**\n   * How fast to pan the camera when the keyboard is used in\n   * pixels per keypress.\n   */\n  public keyPanSpeed = 7.0;\n\n  /**\n   * Set to true to automatically rotate around the target\n   *\n   * Note that if this is enabled, you must call `update()` in your animation loop.\n   * If you want the auto-rotate speed to be independent of the frame rate (the refresh\n   * rate of the display), you must pass the time `deltaTime`, in seconds, to `update()`.\n   */\n  public autoRotate = false;\n\n  /**\n   * How fast to rotate around the target if `autoRotate` is `true`. The default  equates to 30 seconds\n   * per orbit at 60fps.\n   *\n   * Note that if `autoRotate` is enabled, you must call `update()` in your animation loop.\n   */\n  public autoRotateSpeed = 2.0;\n\n  /**\n   * This object contains references to the keycodes for controlling camera panning.\n   *\n   * ```js\n   * controls.keys = {\n   * \tLEFT: 'ArrowLeft', //left arrow\n   * \tUP: 'ArrowUp', // up arrow\n   * \tRIGHT: 'ArrowRight', // right arrow\n   * \tBOTTOM: 'ArrowDown' // down arrow\n   * }\n   * ```\n   */\n  public keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };\n\n  /**\n   * This object contains references to the mouse actions used by the controls.\n   *\n   * ```js\n   * controls.mouseButtons = {\n   * \tLEFT: THREE.MOUSE.ROTATE,\n   * \tMIDDLE: THREE.MOUSE.DOLLY,\n   * \tRIGHT: THREE.MOUSE.PAN\n   * }\n   * ```\n   */\n  public mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };\n\n  /**\n   * This object contains references to the touch actions used by the controls.\n   *\n   * ```js\n   * controls.mouseButtons = {\n   * \tONE: THREE.TOUCH.ROTATE,\n   * \tTWO: THREE.TOUCH.DOLLY_PAN\n   * }\n   * ```\n   */\n  public touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };\n\n  // the target DOM element for key events\n  private _domElementKeyEvents: HTMLElement | null = null;\n\n  // internals\n\n  private _lastPosition = new Vector3();\n  private _lastQuaternion = new Quaternion();\n  private _lastTargetPosition = new Vector3();\n\n  // so camera.up is the orbit axis\n  private _quat = new Quaternion();\n  private _quatInverse = new Quaternion();\n\n  // current position in spherical coordinates\n  private _spherical = new Spherical();\n  private _sphericalDelta = new Spherical();\n\n  private _scale = 1;\n  private _scaleDelta = 0;\n  private _panOffset = new Vector3();\n\n  private _rotateStart = new Vector2();\n  private _rotateEnd = new Vector2();\n  private _rotateDelta = new Vector2();\n\n  private _panStart = new Vector2();\n  private _panEnd = new Vector2();\n  private _panDelta = new Vector2();\n\n  private _dollyStart = new Vector2();\n  private _dollyEnd = new Vector2();\n  private _dollyDelta = new Vector2();\n\n  private _pointers: number[] = [];\n  private _pointerPositions: Record<number, Vector2> = {};\n\n  private _controlActive = false;\n\n  /**\n   * Constructs a new controls instance.\n   *\n   * @param {PerspectiveCamera} camera - The camera that is managed by the controls.\n   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.\n   */\n  constructor(camera: PerspectiveCamera, domElement: HTMLElement | null = null) {\n    super();\n\n    this.camera = camera;\n\n    this._quat = new Quaternion().setFromUnitVectors(camera.up, new Vector3(0, 1, 0));\n    this._quatInverse = this._quat.clone().invert();\n\n    if (domElement !== null) {\n      this.connect(domElement);\n    }\n\n    this.update(0);\n  }\n\n  private _onPointerDownListener = (event: PointerEvent) => {\n    this._onPointerDown(event);\n  };\n\n  private _onPointerMoveListener = (event: PointerEvent) => {\n    this._onPointerMove(event);\n  };\n\n  private _onPointerUpListener = (event: PointerEvent) => {\n    this._onPointerUp(event);\n  };\n\n  private _onContextMenuListener = (event: MouseEvent) => {\n    this._onContextMenu(event);\n  };\n\n  private _onMouseWheelListener = (event: WheelEvent) => {\n    this._onMouseWheel(event);\n  };\n\n  private _interceptControlDownListener = (event: KeyboardEvent) => {\n    this._interceptControlDown(event);\n  };\n\n  private _interceptControlUpListener = (event: KeyboardEvent) => {\n    this._interceptControlUp(event);\n  };\n\n  private _onKeyDownListener = (event: KeyboardEvent) => {\n    this._onKeyDown(event);\n  };\n\n  public connect(element: HTMLElement) {\n    this.domElement = element;\n\n    element.addEventListener('pointerdown', this._onPointerDownListener);\n    element.addEventListener('pointermove', this._onPointerMoveListener);\n    element.addEventListener('pointerup', this._onPointerUpListener);\n    element.addEventListener('pointercancel', this._onPointerUpListener);\n\n    element.addEventListener('contextmenu', this._onContextMenuListener);\n    element.addEventListener('wheel', this._onMouseWheelListener, { passive: false });\n\n    window.addEventListener('keydown', this._interceptControlDownListener, {\n      passive: true,\n      capture: true\n    });\n\n    element.style.touchAction = 'none'; // disable touch scroll\n  }\n\n  public disconnect() {\n    if (!this.domElement) {\n      return;\n    }\n\n    this.domElement.removeEventListener('pointerdown', this._onPointerDownListener);\n    this.domElement.removeEventListener('pointermove', this._onPointerMoveListener);\n    this.domElement.removeEventListener('pointerup', this._onPointerUpListener);\n    this.domElement.removeEventListener('pointercancel', this._onPointerUpListener);\n\n    this.domElement.removeEventListener('wheel', this._onMouseWheelListener);\n    this.domElement.removeEventListener('contextmenu', this._onContextMenuListener);\n\n    this.stopListenToKeyEvents();\n\n    window.removeEventListener('keydown', this._interceptControlDownListener, { capture: true });\n\n    this.domElement.style.touchAction = 'auto';\n  }\n\n  public dispose() {\n    this.disconnect();\n  }\n\n  /**\n   * Get the current vertical rotation, in radians.\n   *\n   * @return The current vertical rotation, in radians.\n   */\n  public getPolarAngle() {\n    return this._spherical.phi;\n  }\n\n  /**\n   * Get the current horizontal rotation, in radians.\n   *\n   * @return The current horizontal rotation, in radians.\n   */\n  public getAzimuthalAngle() {\n    return this._spherical.theta;\n  }\n\n  /**\n   * Returns the distance from the camera to the target.\n   *\n   * @return The distance from the camera to the target.\n   */\n  public getDistance() {\n    return this.camera.position.distanceTo(this.target);\n  }\n\n  /**\n   * Adds key event listeners to the given DOM element.\n   * `window` is a recommended argument for using this method.\n   *\n   * @param domElement - The DOM element\n   */\n  public listenToKeyEvents(domElement: HTMLElement) {\n    domElement.addEventListener('keydown', this._onKeyDownListener);\n    this._domElementKeyEvents = domElement;\n  }\n\n  /**\n   * Removes the key event listener previously defined with `listenToKeyEvents()`.\n   */\n  public stopListenToKeyEvents() {\n    if (this._domElementKeyEvents !== null) {\n      this._domElementKeyEvents.removeEventListener('keydown', this._onKeyDownListener);\n      this._domElementKeyEvents = null;\n    }\n  }\n\n  /**\n   * @param deltaTime - The time since the last update in seconds.\n   */\n  public update(deltaTime: number) {\n    const position = this.camera.position;\n\n    _v.copy(position).sub(this.target);\n\n    // rotate offset to \"y-axis-is-up\" space\n    _v.applyQuaternion(this._quat);\n\n    // angle from z-axis around y-axis\n    this._spherical.setFromVector3(_v);\n\n    if (this.autoRotate && this.state === _STATE.NONE) {\n      this._rotateLeft(this._getAutoRotationAngle(deltaTime));\n    }\n\n    let min = this.minAzimuthAngle;\n    let max = this.maxAzimuthAngle;\n\n    if (isFinite(min) && isFinite(max)) {\n      if (min < -Math.PI) min += _twoPI;\n      else if (min > Math.PI) min -= _twoPI;\n\n      if (max < -Math.PI) max += _twoPI;\n      else if (max > Math.PI) max -= _twoPI;\n\n      if (min <= max) {\n        this._spherical.theta = Math.max(min, Math.min(max, this._spherical.theta));\n      } else {\n        this._spherical.theta =\n          this._spherical.theta > (min + max) / 2\n            ? Math.max(min, this._spherical.theta)\n            : Math.min(max, this._spherical.theta);\n      }\n    }\n\n    // Since we do integrations AFTER contraints, they will act as a spring effect.\n\n    // restrict phi to be between desired limits\n    this._spherical.phi = Math.max(\n      this.minPolarAngle,\n      Math.min(this.maxPolarAngle, this._spherical.phi)\n    );\n\n    // restrict theta to be between desired limits\n    if (this.enableDamping) {\n      this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor;\n      this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor;\n    } else {\n      this._spherical.theta += this._sphericalDelta.theta;\n      this._spherical.phi += this._sphericalDelta.phi;\n    }\n\n    this._spherical.makeSafe();\n\n    this.target.sub(this.sceneCenter);\n    this.target.applyAxisAngle(new Vector3(0, 1, 0), -this.targetYaw);\n    this.target.clamp(this.minTarget, this.maxTarget);\n    this.target.applyAxisAngle(new Vector3(0, 1, 0), this.targetYaw);\n    this.target.add(this.sceneCenter);\n\n    // move target to panned location\n\n    if (this.enableDamping === true) {\n      this.target.addScaledVector(this._panOffset, this.dampingFactor);\n    } else {\n      this.target.add(this._panOffset);\n    }\n\n    let zoomChanged = false;\n    const zoomDampingFactor = this.enableDamping ? this.zoomDampingFactor : 1;\n\n    const prevRadius = this._spherical.radius;\n    this._spherical.radius = this._clampDistance(this._spherical.radius);\n    this._scale =\n      this._scaleDelta > 0\n        ? this._scale / (1 + this._scaleDelta * zoomDampingFactor)\n        : this._scale * (1 - this._scaleDelta * zoomDampingFactor);\n    this._spherical.radius = this._spherical.radius * this._scale;\n    zoomChanged = Math.abs(prevRadius - this._spherical.radius) > _EPS * this.sceneSize;\n\n    _v.setFromSpherical(this._spherical);\n\n    // rotate offset back to \"camera-up-vector-is-up\" space\n    _v.applyQuaternion(this._quatInverse);\n\n    position.copy(this.target).add(_v);\n\n    this.camera.lookAt(this.target);\n\n    if (this.enableDamping === true) {\n      this._sphericalDelta.theta *= 1 - this.dampingFactor;\n      this._sphericalDelta.phi *= 1 - this.dampingFactor;\n\n      this._scaleDelta *= 1 - zoomDampingFactor;\n\n      this._panOffset.multiplyScalar(1 - this.dampingFactor);\n    } else {\n      this._sphericalDelta.set(0, 0, 0);\n\n      this._scaleDelta = 0;\n\n      this._panOffset.set(0, 0, 0);\n    }\n\n    this._scale = 1;\n\n    // update condition is:\n    // min(camera displacement, camera rotation in radians)^2 > EPS\n    // using small-angle approximation cos(x/2) = 1 - x^2 / 8\n\n    if (\n      zoomChanged ||\n      this._lastPosition.distanceToSquared(this.camera.position) > _EPS * this.sceneSize ||\n      8 * (1 - this._lastQuaternion.dot(this.camera.quaternion)) > _EPS * this.sceneSize ||\n      this._lastTargetPosition.distanceToSquared(this.target) > _EPS * this.sceneSize\n    ) {\n      this.dispatchEvent(_changeEvent);\n\n      this._lastPosition.copy(this.camera.position);\n      this._lastQuaternion.copy(this.camera.quaternion);\n      this._lastTargetPosition.copy(this.target);\n\n      return true;\n    }\n\n    return false;\n  }\n\n  private _getAutoRotationAngle(deltaTime: number) {\n    if (deltaTime !== null) {\n      return (_twoPI / 60) * this.autoRotateSpeed * deltaTime;\n    } else {\n      return (_twoPI / 60 / 60) * this.autoRotateSpeed;\n    }\n  }\n\n  private _getZoomScale(delta: number) {\n    const normalizedDelta = Math.abs(delta * 0.01);\n    return Math.pow(0.95, this.zoomSpeed * normalizedDelta);\n  }\n\n  private _rotateLeft(angle: number) {\n    this._sphericalDelta.theta -= angle;\n  }\n\n  private _rotateUp(angle: number) {\n    this._sphericalDelta.phi -= angle;\n  }\n\n  private _panLeft(distance: number, objectMatrix: Matrix4) {\n    _v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix\n    _v.multiplyScalar(-distance);\n\n    this._panOffset.add(_v);\n  }\n\n  private _panUp(distance: number, objectMatrix: Matrix4) {\n    _v.setFromMatrixColumn(objectMatrix, 1);\n\n    _v.multiplyScalar(distance);\n\n    this._panOffset.add(_v);\n  }\n\n  // deltaX and deltaY are in pixels; right and down are positive\n  private _pan(deltaX: number, deltaY: number) {\n    const element = this.domElement;\n\n    if (!element) {\n      return;\n    }\n\n    // perspective\n    const position = this.camera.position;\n    _v.copy(position).sub(this.target);\n    let targetDistance = _v.length();\n\n    // half of the fov is center to top of screen\n    targetDistance *= Math.tan(((this.camera.fov / 2) * Math.PI) / 180.0);\n\n    // we use only clientHeight here so aspect ratio does not distort speed\n    this._panLeft((2 * deltaX * targetDistance) / element.clientHeight, this.camera.matrix);\n    this._panUp((2 * deltaY * targetDistance) / element.clientHeight, this.camera.matrix);\n  }\n\n  private _dollyOut(dollyScale: number) {\n    this._scaleDelta -= dollyScale;\n  }\n\n  private _dollyIn(dollyScale: number) {\n    this._scaleDelta += dollyScale;\n  }\n\n  private _clampDistance(dist: number) {\n    return Math.max(this.minDistance, Math.min(this.maxDistance, dist));\n  }\n\n  //\n  // event callbacks - update the object state\n  //\n\n  private _handleMouseDownRotate(event: MouseEvent) {\n    this._rotateStart.set(event.clientX, event.clientY);\n  }\n\n  private _handleMouseDownDolly(event: MouseEvent) {\n    this._dollyStart.set(event.clientX, event.clientY);\n  }\n\n  private _handleMouseDownPan(event: MouseEvent) {\n    this._panStart.set(event.clientX, event.clientY);\n  }\n\n  private _handleMouseMoveRotate(event: MouseEvent) {\n    const element = this.domElement;\n\n    if (!element) {\n      return;\n    }\n\n    this._rotateEnd.set(event.clientX, event.clientY);\n\n    this._rotateDelta\n      .subVectors(this._rotateEnd, this._rotateStart)\n      .multiplyScalar(this.rotateSpeed);\n\n    this._rotateLeft((_twoPI * this._rotateDelta.x) / element.clientHeight); // yes, height\n\n    this._rotateUp((_twoPI * this._rotateDelta.y) / element.clientHeight);\n\n    this._rotateStart.copy(this._rotateEnd);\n\n    this.update(0);\n  }\n\n  private _handleMouseMoveDolly(event: MouseEvent) {\n    this._dollyEnd.set(event.clientX, event.clientY);\n\n    this._dollyDelta.subVectors(this._dollyEnd, this._dollyStart);\n\n    if (this._dollyDelta.y > 0) {\n      this._dollyOut(this._getZoomScale(this._dollyDelta.y) * MOUSE_MOVE_DOLLY_FACTOR);\n    } else if (this._dollyDelta.y < 0) {\n      this._dollyIn(this._getZoomScale(this._dollyDelta.y) * MOUSE_MOVE_DOLLY_FACTOR);\n    }\n\n    this._dollyStart.copy(this._dollyEnd);\n\n    this.update(0);\n  }\n\n  private _handleMouseMovePan(event: MouseEvent) {\n    this._panEnd.set(event.clientX, event.clientY);\n\n    this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed);\n\n    this._pan(this._panDelta.x, this._panDelta.y);\n\n    this._panStart.copy(this._panEnd);\n\n    this.update(0);\n  }\n\n  private _handleMouseWheel(event: { deltaY: number }) {\n    if (event.deltaY < 0) {\n      this._dollyIn(this._getZoomScale(event.deltaY));\n    } else if (event.deltaY > 0) {\n      this._dollyOut(this._getZoomScale(event.deltaY));\n    }\n\n    this.update(0);\n  }\n\n  private _handleKeyDown(event: KeyboardEvent) {\n    let needsUpdate = false;\n\n    const element = this.domElement;\n    if (!element) {\n      return;\n    }\n\n    switch (event.code) {\n      case this.keys.UP:\n        if (event.ctrlKey || event.metaKey || event.shiftKey) {\n          if (this.enableRotate) {\n            this._rotateUp((_twoPI * this.keyRotateSpeed) / element.clientHeight);\n          }\n        } else {\n          if (this.enablePan) {\n            this._pan(0, this.keyPanSpeed);\n          }\n        }\n\n        needsUpdate = true;\n        break;\n\n      case this.keys.BOTTOM:\n        if (event.ctrlKey || event.metaKey || event.shiftKey) {\n          if (this.enableRotate) {\n            this._rotateUp((-_twoPI * this.keyRotateSpeed) / element.clientHeight);\n          }\n        } else {\n          if (this.enablePan) {\n            this._pan(0, -this.keyPanSpeed);\n          }\n        }\n\n        needsUpdate = true;\n        break;\n\n      case this.keys.LEFT:\n        if (event.ctrlKey || event.metaKey || event.shiftKey) {\n          if (this.enableRotate) {\n            this._rotateLeft((_twoPI * this.keyRotateSpeed) / element.clientHeight);\n          }\n        } else {\n          if (this.enablePan) {\n            this._pan(this.keyPanSpeed, 0);\n          }\n        }\n\n        needsUpdate = true;\n        break;\n\n      case this.keys.RIGHT:\n        if (event.ctrlKey || event.metaKey || event.shiftKey) {\n          if (this.enableRotate) {\n            this._rotateLeft((-_twoPI * this.keyRotateSpeed) / element.clientHeight);\n          }\n        } else {\n          if (this.enablePan) {\n            this._pan(-this.keyPanSpeed, 0);\n          }\n        }\n\n        needsUpdate = true;\n        break;\n    }\n\n    if (needsUpdate) {\n      // prevent the browser from scrolling on cursor keys\n      event.preventDefault();\n\n      this.update(0);\n    }\n  }\n\n  private _handleTouchStartRotate(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this._pointers.length === 1) {\n      this._rotateStart.set(event.pageX, event.pageY);\n    } else {\n      const position = this._getSecondPointerPosition(event);\n\n      const x = 0.5 * (event.pageX + position.x);\n      const y = 0.5 * (event.pageY + position.y);\n\n      this._rotateStart.set(x, y);\n    }\n  }\n\n  private _handleTouchStartPan(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this._pointers.length === 1) {\n      this._panStart.set(event.pageX, event.pageY);\n    } else {\n      const position = this._getSecondPointerPosition(event);\n\n      const x = 0.5 * (event.pageX + position.x);\n      const y = 0.5 * (event.pageY + position.y);\n\n      this._panStart.set(x, y);\n    }\n  }\n\n  private _handleTouchStartDolly(event: { pointerId: number; pageX: number; pageY: number }) {\n    const position = this._getSecondPointerPosition(event);\n\n    const dx = event.pageX - position.x;\n    const dy = event.pageY - position.y;\n\n    const distance = Math.sqrt(dx * dx + dy * dy);\n\n    this._dollyStart.set(0, distance);\n  }\n\n  private _handleTouchStartDollyPan(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this.enableZoom) this._handleTouchStartDolly(event);\n\n    if (this.enablePan) this._handleTouchStartPan(event);\n  }\n\n  private _handleTouchStartDollyRotate(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this.enableZoom) this._handleTouchStartDolly(event);\n\n    if (this.enableRotate) this._handleTouchStartRotate(event);\n  }\n\n  private _handleTouchMoveRotate(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this._pointers.length == 1) {\n      this._rotateEnd.set(event.pageX, event.pageY);\n    } else {\n      const position = this._getSecondPointerPosition(event);\n\n      const x = 0.5 * (event.pageX + position.x);\n      const y = 0.5 * (event.pageY + position.y);\n\n      this._rotateEnd.set(x, y);\n    }\n\n    this._rotateDelta\n      .subVectors(this._rotateEnd, this._rotateStart)\n      .multiplyScalar(this.rotateSpeed);\n\n    const element = this.domElement;\n\n    if (!element) {\n      return;\n    }\n\n    this._rotateLeft((_twoPI * this._rotateDelta.x) / element.clientHeight); // yes, height\n\n    this._rotateUp((_twoPI * this._rotateDelta.y) / element.clientHeight);\n\n    this._rotateStart.copy(this._rotateEnd);\n  }\n\n  private _handleTouchMovePan(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this._pointers.length === 1) {\n      this._panEnd.set(event.pageX, event.pageY);\n    } else {\n      const position = this._getSecondPointerPosition(event);\n\n      const x = 0.5 * (event.pageX + position.x);\n      const y = 0.5 * (event.pageY + position.y);\n\n      this._panEnd.set(x, y);\n    }\n\n    this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed);\n\n    this._pan(this._panDelta.x, this._panDelta.y);\n\n    this._panStart.copy(this._panEnd);\n  }\n\n  private _handleTouchMoveDolly(event: { pointerId: number; pageX: number; pageY: number }) {\n    const position = this._getSecondPointerPosition(event);\n\n    const dx = event.pageX - position.x;\n    const dy = event.pageY - position.y;\n\n    const distance = Math.sqrt(dx * dx + dy * dy);\n\n    this._dollyEnd.set(0, distance);\n\n    this._dollyDelta.set(0, (this._dollyEnd.y - this._dollyStart.y) / distance);\n\n    this._dollyIn(this._dollyDelta.y);\n\n    this._dollyStart.copy(this._dollyEnd);\n  }\n\n  private _handleTouchMoveDollyPan(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this.enableZoom) this._handleTouchMoveDolly(event);\n\n    if (this.enablePan) this._handleTouchMovePan(event);\n  }\n\n  private _handleTouchMoveDollyRotate(event: { pointerId: number; pageX: number; pageY: number }) {\n    if (this.enableZoom) this._handleTouchMoveDolly(event);\n\n    if (this.enableRotate) this._handleTouchMoveRotate(event);\n  }\n\n  // pointers\n\n  private _addPointer(event: { pointerId: number }) {\n    this._pointers.push(event.pointerId);\n  }\n\n  private _removePointer(event: { pointerId: number }) {\n    delete this._pointerPositions[event.pointerId];\n\n    for (let i = 0; i < this._pointers.length; i++) {\n      if (this._pointers[i] == event.pointerId) {\n        this._pointers.splice(i, 1);\n        return;\n      }\n    }\n  }\n\n  private _isTrackingPointer(event: { pointerId: number }) {\n    for (let i = 0; i < this._pointers.length; i++) {\n      if (this._pointers[i] == event.pointerId) return true;\n    }\n\n    return false;\n  }\n\n  private _trackPointer(event: { pointerId: number; pageX: number; pageY: number }) {\n    let position = this._pointerPositions[event.pointerId];\n\n    if (position === undefined) {\n      position = new Vector2();\n      this._pointerPositions[event.pointerId] = position;\n    }\n\n    position.set(event.pageX, event.pageY);\n  }\n\n  private _getSecondPointerPosition(event: { pointerId: number; pageX: number; pageY: number }) {\n    const pointerId = event.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0];\n\n    return this._pointerPositions[pointerId];\n  }\n\n  //\n\n  private _customWheelEvent(event: WheelEvent) {\n    const mode = event.deltaMode;\n\n    // minimal wheel event altered to meet delta-zoom demand\n    const newEvent = {\n      clientX: event.clientX,\n      clientY: event.clientY,\n      deltaY: event.deltaY\n    };\n\n    switch (mode) {\n      case 1: // LINE_MODE\n        newEvent.deltaY *= 16;\n        break;\n\n      case 2: // PAGE_MODE\n        newEvent.deltaY *= 100;\n        break;\n    }\n\n    // detect if event was triggered by pinching\n    if (event.ctrlKey && !this._controlActive) {\n      newEvent.deltaY *= 10;\n    }\n\n    return newEvent;\n  }\n\n  private _onPointerDown = (event: PointerEvent) => {\n    if (this._pointers.length === 0) {\n      if (!this.domElement) {\n        return;\n      }\n\n      this.domElement.setPointerCapture(event.pointerId);\n\n      this.domElement.addEventListener('pointermove', this._onPointerMoveListener);\n      this.domElement.addEventListener('pointerup', this._onPointerUpListener);\n    }\n\n    //\n\n    if (this._isTrackingPointer(event)) return;\n\n    //\n\n    this._addPointer(event);\n\n    if (event.pointerType === 'touch') {\n      this._onTouchStart(event);\n    } else {\n      this._onMouseDown(event);\n    }\n  };\n\n  private _onPointerMove(event: PointerEvent) {\n    if (event.pointerType === 'touch') {\n      this._onTouchMove(event);\n    } else {\n      this._onMouseMove(event);\n    }\n  }\n\n  private _onPointerUp(event: PointerEvent) {\n    this._removePointer(event);\n\n    switch (this._pointers.length) {\n      case 0:\n        if (!this.domElement) {\n          return;\n        }\n\n        this.domElement.releasePointerCapture(event.pointerId);\n\n        this.domElement.removeEventListener('pointermove', this._onPointerMove);\n        this.domElement.removeEventListener('pointerup', this._onPointerUp);\n\n        this.dispatchEvent(_endEvent);\n\n        this.state = _STATE.NONE;\n\n        break;\n\n      case 1: {\n        const pointerId = this._pointers[0];\n        const position = this._pointerPositions[pointerId];\n\n        // minimal placeholder event - allows state correction on pointer-up\n        this._onTouchStart({ pointerId: pointerId, pageX: position.x, pageY: position.y });\n\n        break;\n      }\n    }\n  }\n\n  private _onMouseDown(event: MouseEvent) {\n    let mouseAction;\n\n    switch (event.button) {\n      case 0:\n        mouseAction = this.mouseButtons.LEFT;\n        break;\n\n      case 1:\n        mouseAction = this.mouseButtons.MIDDLE;\n        break;\n\n      case 2:\n        mouseAction = this.mouseButtons.RIGHT;\n        break;\n\n      default:\n        mouseAction = -1;\n    }\n\n    switch (mouseAction) {\n      case MOUSE.DOLLY:\n        if (this.enableZoom === false) return;\n\n        this._handleMouseDownDolly(event);\n\n        this.state = _STATE.DOLLY;\n\n        break;\n\n      case MOUSE.ROTATE:\n        if (event.ctrlKey || event.metaKey || event.shiftKey) {\n          if (this.enablePan === false) return;\n\n          this._handleMouseDownPan(event);\n\n          this.state = _STATE.PAN;\n        } else {\n          if (this.enableRotate === false) return;\n\n          this._handleMouseDownRotate(event);\n\n          this.state = _STATE.ROTATE;\n        }\n\n        break;\n\n      case MOUSE.PAN:\n        if (event.ctrlKey || event.metaKey || event.shiftKey) {\n          if (this.enableRotate === false) return;\n\n          this._handleMouseDownRotate(event);\n\n          this.state = _STATE.ROTATE;\n        } else {\n          if (this.enablePan === false) return;\n\n          this._handleMouseDownPan(event);\n\n          this.state = _STATE.PAN;\n        }\n\n        break;\n\n      default:\n        this.state = _STATE.NONE;\n    }\n\n    if (this.state !== _STATE.NONE) {\n      this.dispatchEvent(_startEvent);\n    }\n  }\n\n  private _onMouseMove(event: MouseEvent) {\n    switch (this.state) {\n      case _STATE.ROTATE:\n        if (this.enableRotate === false) return;\n\n        this._handleMouseMoveRotate(event);\n\n        break;\n\n      case _STATE.DOLLY:\n        if (this.enableZoom === false) return;\n\n        this._handleMouseMoveDolly(event);\n\n        break;\n\n      case _STATE.PAN:\n        if (this.enablePan === false) return;\n\n        this._handleMouseMovePan(event);\n\n        break;\n    }\n  }\n\n  private _onMouseWheel(event: WheelEvent) {\n    if (this.enableZoom === false || (this.state !== _STATE.NONE && this.state !== _STATE.DOLLY))\n      return;\n\n    event.preventDefault();\n\n    this.dispatchEvent(_startEvent);\n\n    this._handleMouseWheel(this._customWheelEvent(event));\n\n    this.dispatchEvent(_endEvent);\n  }\n\n  private _onKeyDown(event: KeyboardEvent) {\n    this._handleKeyDown(event);\n  }\n\n  private _onTouchStart(event: { pointerId: number; pageX: number; pageY: number }) {\n    this._trackPointer(event);\n\n    switch (this._pointers.length) {\n      case 1:\n        switch (this.touches.ONE) {\n          case TOUCH.ROTATE:\n            if (this.enableRotate === false) return;\n\n            this._handleTouchStartRotate(event);\n\n            this.state = _STATE.TOUCH_ROTATE;\n\n            break;\n\n          case TOUCH.PAN:\n            if (this.enablePan === false) return;\n\n            this._handleTouchStartPan(event);\n\n            this.state = _STATE.TOUCH_PAN;\n\n            break;\n\n          default:\n            this.state = _STATE.NONE;\n        }\n\n        break;\n\n      case 2:\n        switch (this.touches.TWO) {\n          case TOUCH.DOLLY_PAN:\n            if (this.enableZoom === false && this.enablePan === false) return;\n\n            this._handleTouchStartDollyPan(event);\n\n            this.state = _STATE.TOUCH_DOLLY_PAN;\n\n            break;\n\n          case TOUCH.DOLLY_ROTATE:\n            if (this.enableZoom === false && this.enableRotate === false) return;\n\n            this._handleTouchStartDollyRotate(event);\n\n            this.state = _STATE.TOUCH_DOLLY_ROTATE;\n\n            break;\n\n          default:\n            this.state = _STATE.NONE;\n        }\n\n        break;\n\n      default:\n        this.state = _STATE.NONE;\n    }\n\n    if (this.state !== _STATE.NONE) {\n      this.dispatchEvent(_startEvent);\n    }\n  }\n\n  private _onTouchMove(event: { pointerId: number; pageX: number; pageY: number }) {\n    this._trackPointer(event);\n\n    switch (this.state) {\n      case _STATE.TOUCH_ROTATE:\n        if (this.enableRotate === false) return;\n\n        this._handleTouchMoveRotate(event);\n\n        this.update(0);\n\n        break;\n\n      case _STATE.TOUCH_PAN:\n        if (this.enablePan === false) return;\n\n        this._handleTouchMovePan(event);\n\n        this.update(0);\n\n        break;\n\n      case _STATE.TOUCH_DOLLY_PAN:\n        if (this.enableZoom === false && this.enablePan === false) return;\n\n        this._handleTouchMoveDollyPan(event);\n\n        this.update(0);\n\n        break;\n\n      case _STATE.TOUCH_DOLLY_ROTATE:\n        if (this.enableZoom === false && this.enableRotate === false) return;\n\n        this._handleTouchMoveDollyRotate(event);\n\n        this.update(0);\n\n        break;\n\n      default:\n        this.state = _STATE.NONE;\n    }\n  }\n\n  private _onContextMenu(event: MouseEvent) {\n    event.preventDefault();\n  }\n\n  private _interceptControlDown(event: KeyboardEvent) {\n    if (event.key === 'Control') {\n      this._controlActive = true;\n\n      window.addEventListener('keyup', this._interceptControlUpListener, {\n        passive: true,\n        capture: true\n      });\n    }\n  }\n\n  private _interceptControlUp(event: KeyboardEvent) {\n    if (event.key === 'Control') {\n      this._controlActive = false;\n\n      window.removeEventListener('keyup', this._interceptControlUpListener, {\n        capture: true\n      });\n    }\n  }\n}\n\nexport { OrbitControls };\n"
    },
    {
      "path": "create-camera/offset-camera.ts",
      "content": "import { MathUtils, Matrix4, PerspectiveCamera, Vector3 } from \"three\";\n\nexport default class OffsetCamera extends PerspectiveCamera {\n  public verticalRatio: number = 1.0;\n  public absoluteFov: number = 75;\n\n  public xOffset: number = 0;\n  public yOffset: number = 0;\n\n  override updateProjectionMatrix() {\n    const near = this.near;\n    let top = (near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov)) / this.zoom;\n    let height = 2 * top;\n    let width = this.aspect * height;\n    let left = -0.5 * width;\n\n    if (this.view !== null && this.view.enabled) {\n      const view = this.view;\n      const fullWidth = view.fullWidth,\n        fullHeight = view.fullHeight;\n\n      left += (view.offsetX * width) / fullWidth;\n      top -= (view.offsetY * height) / fullHeight;\n      width *= view.width / fullWidth;\n      height *= view.height / fullHeight;\n    }\n\n    const skew = this.filmOffset;\n    if (skew !== 0) left += (near * skew) / this.getFilmWidth();\n\n    this.projectionMatrix.makePerspective(\n      left,\n      left + width,\n      top,\n      top - height,\n      near,\n      this.far,\n      this.coordinateSystem,\n    );\n\n    const offsetMatrix = new Matrix4().makeTranslation(\n      new Vector3(this.xOffset, this.yOffset, 0),\n    );\n\n    this.projectionMatrix.premultiply(offsetMatrix);\n\n    this.projectionMatrixInverse.copy(this.projectionMatrix).invert();\n  }\n}\n"
    }
  ]
}