16.6 KiB · text History 44bc4f7
// A photo sphere viewer (CartosnapAppWeb.PhotoComponents.photo_stage/1):
// an equirectangular photo -- longitude across, latitude down -- seen from
// inside, to drag around, zoom and go full screen in. One full-screen
// quad and a fragment shader that turns each pixel's view ray into a
// longitude and latitude and looks it up in the photo; no library.
//
// data-src      the full-size photo
// data-preview  a small one, shown while the full one loads
// data-pano     where the photo sits in the full sphere (Photos.Panorama):
//               {full_width, full_height, left, top, width, height,
//                heading, initial_heading, initial_pitch, initial_fov}
//
// A partial sphere (a Google Camera panorama covers a band of it) keeps
// the view inside what was photographed.

const VERTEX = `
attribute vec2 position;
varying vec2 screen;
void main() {
  screen = position;
  gl_Position = vec4(position, 0.0, 1.0);
}`

const FRAGMENT = `
precision highp float;
varying vec2 screen;
uniform sampler2D photo;
uniform float yaw;
uniform float pitch;
uniform float tanHalf;
uniform float aspect;
// Where the photo sits in the full sphere, as fractions of it:
// left, top, width, height.
uniform vec4 crop;
uniform vec3 background;
const float PI = 3.141592653589793;

void main() {
  vec3 ray = normalize(vec3(screen.x * tanHalf * aspect, screen.y * tanHalf, -1.0));

  // Look up (around x), then turn (around y).
  float cp = cos(pitch), sp = sin(pitch);
  ray = vec3(ray.x, ray.y * cp - ray.z * sp, ray.y * sp + ray.z * cp);
  float cy = cos(yaw), sy = sin(yaw);
  ray = vec3(ray.x * cy - ray.z * sy, ray.y, ray.x * sy + ray.z * cy);

  float lon = atan(ray.x, -ray.z);
  float lat = asin(clamp(ray.y, -1.0, 1.0));
  float u = fract(lon / (2.0 * PI) + 0.5);
  float v = 0.5 - lat / PI;

  float cu = crop.z > 0.999 ? fract(u - crop.x) : (u - crop.x) / crop.z;
  float cv = (v - crop.y) / crop.w;

  if (cu < 0.0 || cu > 1.0 || cv < 0.0 || cv > 1.0) {
    gl_FragColor = vec4(background, 1.0);
  } else {
    gl_FragColor = texture2D(photo, vec2(cu, cv));
  }
}`

const DEG = Math.PI / 180
const MIN_FOV = 20 * DEG
const MAX_FOV = 110 * DEG
const DEFAULT_FOV = 75 * DEG

const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x))

const compass = degrees => {
  const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
  return names[Math.round((((degrees % 360) + 360) % 360) / 45) % 8]
}

const BUTTON = "grid size-9 place-items-center rounded-full bg-black/45 text-white backdrop-blur transition hover:bg-black/65 focus-visible:outline-2 focus-visible:outline-white"

export default {
  mounted() {
    const pano = JSON.parse(this.el.dataset.pano || "{}")
    const fullW = pano.full_width || pano.width || 2
    const fullH = pano.full_height || fullW / 2
    this.crop = [
      (pano.left || 0) / fullW,
      (pano.top || 0) / fullH,
      (pano.width || fullW) / fullW,
      (pano.height || fullH) / fullH
    ]
    this.heading = typeof pano.heading === "number" ? pano.heading : null

    this.el.innerHTML = `
      <canvas class="block h-full w-full cursor-grab touch-none outline-none active:cursor-grabbing" tabindex="0"
        aria-label="360° photo. Drag to look around, scroll or pinch to zoom."></canvas>
      <div class="pointer-events-none absolute left-3 top-3 flex items-center gap-1.5">
        <span class="rounded-full bg-black/45 px-2 py-0.5 text-[11px] font-semibold text-white backdrop-blur">360°</span>
        <span data-role="compass" class="hidden rounded-full bg-black/45 px-2 py-0.5 font-mono text-[11px] text-white backdrop-blur"></span>
      </div>
      <div class="absolute bottom-3 right-3 flex gap-1.5">
        <button type="button" data-action="out" class="${BUTTON}" aria-label="Zoom out"><span class="hero-minus-micro size-4"></span></button>
        <button type="button" data-action="in" class="${BUTTON}" aria-label="Zoom in"><span class="hero-plus-micro size-4"></span></button>
        <button type="button" data-action="reset" class="${BUTTON}" aria-label="Back to the start"><span class="hero-arrow-path-micro size-4"></span></button>
        <button type="button" data-action="fullscreen" class="${BUTTON}" aria-label="Full screen"><span class="hero-arrows-pointing-out-micro size-4"></span></button>
      </div>
      <div data-role="loading" class="pointer-events-none absolute inset-x-0 bottom-0 h-0.5 overflow-hidden">
        <div class="h-full w-1/3 animate-pulse bg-primary"></div>
      </div>`
    this.canvas = this.el.querySelector("canvas")
    this.compassEl = this.el.querySelector("[data-role=compass]")

    const gl = this.canvas.getContext("webgl", {antialias: false, preserveDrawingBuffer: false})
    if (!gl) return this.fallback("This browser can't show 360° photos")
    this.gl = gl
    if (!this.setUp()) return this.fallback("Couldn't start the 360° view")

    this.start = {
      yaw: typeof pano.initial_heading === "number" ? (pano.initial_heading / 360 - 0.5) * 2 * Math.PI : this.centreYaw(),
      pitch: typeof pano.initial_pitch === "number" ? pano.initial_pitch * DEG : this.centrePitch(),
      fov: DEFAULT_FOV
    }
    Object.assign(this, {yaw: this.start.yaw, pitch: this.start.pitch, fov: this.start.fov, vx: 0, vy: 0})
    if (typeof pano.initial_fov === "number") this.setHorizontalFov(pano.initial_fov * DEG)

    // A slow turn until it's touched: it says "drag me" without words.
    this.drifting = this.crop[2] > 0.999 && !matchMedia("(prefers-reduced-motion: reduce)").matches

    this.bind()
    this.resize()
    this.resizeObserver = new ResizeObserver(() => this.resize())
    this.resizeObserver.observe(this.el)

    // The small preview first, then the full photo when it's in.
    this.load(this.el.dataset.preview, () => this.load(this.el.dataset.src, () => this.loaded()), () =>
      this.load(this.el.dataset.src, () => this.loaded(), () => this.fallback("Couldn't load the photo")))
  },

  destroyed() {
    cancelAnimationFrame(this.frame)
    this.resizeObserver?.disconnect()
    document.removeEventListener("fullscreenchange", this.onFullscreen)
    this.gl?.getExtension("WEBGL_lose_context")?.loseContext()
  },

  setUp() {
    const gl = this.gl
    const shader = (type, source) => {
      const s = gl.createShader(type)
      gl.shaderSource(s, source)
      gl.compileShader(s)
      return gl.getShaderParameter(s, gl.COMPILE_STATUS) ? s : null
    }
    const vs = shader(gl.VERTEX_SHADER, VERTEX)
    const fs = shader(gl.FRAGMENT_SHADER, FRAGMENT)
    if (!vs || !fs) return false

    const program = gl.createProgram()
    gl.attachShader(program, vs)
    gl.attachShader(program, fs)
    gl.linkProgram(program)
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return false
    gl.useProgram(program)

    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer())
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW)
    const position = gl.getAttribLocation(program, "position")
    gl.enableVertexAttribArray(position)
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0)

    this.uniforms = {}
    for (const name of ["photo", "yaw", "pitch", "tanHalf", "aspect", "crop", "background"]) {
      this.uniforms[name] = gl.getUniformLocation(program, name)
    }
    gl.uniform4fv(this.uniforms.crop, this.crop)
    gl.uniform3fv(this.uniforms.background, [0.07, 0.07, 0.09])

    this.texture = gl.createTexture()
    gl.bindTexture(gl.TEXTURE_2D, this.texture)
    // Photos are rarely powers of two: no mipmaps, no repeat.
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
    // Phones' GPUs take smaller textures, and a sphere is big: 8192 across
    // is 128 MB on the GPU, more than a phone needs to fill its screen.
    const coarse = matchMedia("(pointer: coarse)").matches
    this.maxTexture = Math.min(gl.getParameter(gl.MAX_TEXTURE_SIZE), coarse ? 4096 : 8192)
    return true
  },

  load(url, done, failed = () => {}) {
    if (!url) return failed()
    const image = new Image()
    // Photos may come from the bucket's own host; WebGL needs CORS for them.
    if (new URL(url, location.href).origin !== location.origin) image.crossOrigin = "anonymous"
    image.decoding = "async"
    image.onload = () => {
      if (!this.gl) return
      try {
        this.upload(image)
        done()
      } catch (_error) {
        failed()
      }
    }
    image.onerror = () => failed()
    image.src = url
  },

  upload(image) {
    const gl = this.gl
    let source = image
    const scale = Math.min(1, this.maxTexture / Math.max(image.naturalWidth, image.naturalHeight))
    if (scale < 1) {
      source = document.createElement("canvas")
      source.width = Math.floor(image.naturalWidth * scale)
      source.height = Math.floor(image.naturalHeight * scale)
      source.getContext("2d").drawImage(image, 0, 0, source.width, source.height)
    }
    gl.bindTexture(gl.TEXTURE_2D, this.texture)
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source)
    this.ready = true
    this.render()
  },

  loaded() {
    this.el.querySelector("[data-role=loading]")?.remove()
  },

  // No WebGL, or the photo wouldn't load into it: the photo as it is.
  fallback(message) {
    this.gl = null
    const wrap = document.createElement("div")
    wrap.className = "flex h-full w-full flex-col items-center justify-center gap-2 p-4"
    const img = document.createElement("img")
    img.src = this.el.dataset.src
    img.alt = ""
    img.className = "min-h-0 max-h-full max-w-full object-contain"
    const note = document.createElement("p")
    note.className = "text-xs text-base-content/60"
    note.textContent = `${message}; this is the photo flat.`
    wrap.append(img, note)
    this.el.replaceChildren(wrap)
  },

  bind() {
    const pointers = new Map()
    let pinch = null
    let last = null

    this.canvas.addEventListener("pointerdown", e => {
      this.canvas.setPointerCapture(e.pointerId)
      pointers.set(e.pointerId, {x: e.clientX, y: e.clientY})
      this.drifting = false
      this.vx = this.vy = 0
      last = {x: e.clientX, y: e.clientY, t: performance.now()}
      if (pointers.size === 2) pinch = {distance: this.spread(pointers), fov: this.fov}
    })

    this.canvas.addEventListener("pointermove", e => {
      if (!pointers.has(e.pointerId)) return
      pointers.set(e.pointerId, {x: e.clientX, y: e.clientY})

      if (pointers.size >= 2 && pinch) {
        this.fov = clamp(pinch.fov * (pinch.distance / Math.max(1, this.spread(pointers))), MIN_FOV, this.maxFov())
      } else if (pointers.size === 1 && last) {
        // A drag moves the picture under the finger, as if holding it.
        const perPixel = this.fov / this.canvas.clientHeight
        const dx = e.clientX - last.x
        const dy = e.clientY - last.y
        const dt = Math.max(1, performance.now() - last.t)
        this.yaw -= dx * perPixel
        this.pitch += dy * perPixel
        this.vx = (-dx * perPixel) / dt
        this.vy = (dy * perPixel) / dt
        last = {x: e.clientX, y: e.clientY, t: performance.now()}
      }
      this.changed()
    })

    const release = e => {
      pointers.delete(e.pointerId)
      if (pointers.size < 2) pinch = null
      if (pointers.size === 1) {
        const [p] = pointers.values()
        last = {x: p.x, y: p.y, t: performance.now()}
      }
      if (pointers.size === 0) this.changed()
    }
    this.canvas.addEventListener("pointerup", release)
    this.canvas.addEventListener("pointercancel", release)

    this.canvas.addEventListener("wheel", e => {
      e.preventDefault()
      this.drifting = false
      this.fov = clamp(this.fov * Math.exp(e.deltaY * 0.0015), MIN_FOV, this.maxFov())
      this.changed()
    }, {passive: false})

    this.canvas.addEventListener("dblclick", () => this.reset())

    // With the view focused, the arrow keys look around rather than step
    // to the next photo; Escape hands them back.
    this.canvas.addEventListener("keydown", e => {
      const step = this.fov / 8
      const moves = {
        ArrowLeft: () => (this.yaw -= step),
        ArrowRight: () => (this.yaw += step),
        ArrowUp: () => (this.pitch += step),
        ArrowDown: () => (this.pitch -= step),
        "+": () => (this.fov = clamp(this.fov / 1.2, MIN_FOV, this.maxFov())),
        "=": () => (this.fov = clamp(this.fov / 1.2, MIN_FOV, this.maxFov())),
        "-": () => (this.fov = clamp(this.fov * 1.2, MIN_FOV, this.maxFov()))
      }
      if (e.key === "Escape") return this.canvas.blur()
      if (!moves[e.key]) return
      e.preventDefault()
      e.stopPropagation()
      this.drifting = false
      moves[e.key]()
      this.changed()
    })

    this.el.querySelectorAll("[data-action]").forEach(button =>
      button.addEventListener("click", () => {
        this.drifting = false
        switch (button.dataset.action) {
          case "in": this.fov = clamp(this.fov / 1.3, MIN_FOV, this.maxFov()); break
          case "out": this.fov = clamp(this.fov * 1.3, MIN_FOV, this.maxFov()); break
          case "reset": return this.reset()
          case "fullscreen": return this.toggleFullscreen()
        }
        this.changed()
      })
    )

    this.onFullscreen = () => this.resize()
    document.addEventListener("fullscreenchange", this.onFullscreen)
  },

  spread(pointers) {
    const [a, b] = [...pointers.values()]
    return Math.hypot(a.x - b.x, a.y - b.y)
  },

  reset() {
    Object.assign(this, {yaw: this.start.yaw, pitch: this.start.pitch, fov: this.start.fov, vx: 0, vy: 0})
    this.changed()
  },

  toggleFullscreen() {
    if (document.fullscreenElement) document.exitFullscreen?.()
    else this.el.requestFullscreen?.()
  },

  setHorizontalFov(h) {
    const aspect = this.canvas.clientWidth / Math.max(1, this.canvas.clientHeight)
    this.fov = clamp(2 * Math.atan(Math.tan(h / 2) / aspect), MIN_FOV, MAX_FOV)
  },

  // The latitudes and longitudes the photo covers.
  bounds() {
    const [left, top, width, height] = this.crop
    return {
      north: (0.5 - top) * Math.PI,
      south: (0.5 - top - height) * Math.PI,
      west: (left - 0.5) * 2 * Math.PI,
      east: (left + width - 0.5) * 2 * Math.PI,
      full: width > 0.999
    }
  },

  centreYaw() {
    const b = this.bounds()
    return b.full ? 0 : (b.west + b.east) / 2
  },

  centrePitch() {
    const b = this.bounds()
    return clamp(0, b.south, b.north)
  },

  maxFov() {
    const b = this.bounds()
    return Math.max(MIN_FOV, Math.min(MAX_FOV, b.north - b.south))
  },

  // Keeps the view inside what was photographed.
  constrain() {
    const b = this.bounds()
    this.fov = clamp(this.fov, MIN_FOV, this.maxFov())
    const half = this.fov / 2
    this.pitch = b.north - b.south <= this.fov ? (b.north + b.south) / 2 : clamp(this.pitch, b.south + half, b.north - half)

    if (!b.full) {
      const aspect = this.canvas.clientWidth / Math.max(1, this.canvas.clientHeight)
      const halfH = Math.atan(Math.tan(half) * aspect)
      this.yaw = b.east - b.west <= 2 * halfH ? (b.east + b.west) / 2 : clamp(this.yaw, b.west + halfH, b.east - halfH)
    }
  },

  resize() {
    const ratio = Math.min(window.devicePixelRatio || 1, 2)
    const w = Math.max(1, Math.round(this.canvas.clientWidth * ratio))
    const h = Math.max(1, Math.round(this.canvas.clientHeight * ratio))
    if (this.canvas.width !== w || this.canvas.height !== h) {
      this.canvas.width = w
      this.canvas.height = h
    }
    this.changed()
  },

  changed() {
    if (!this.frame) this.frame = requestAnimationFrame(() => this.tick())
  },

  tick() {
    this.frame = null
    const moving = Math.abs(this.vx) > 1e-5 || Math.abs(this.vy) > 1e-5
    if (moving) {
      // Let go mid-swipe and it glides to a stop.
      this.yaw += this.vx * 16
      this.pitch += this.vy * 16
      this.vx *= 0.92
      this.vy *= 0.92
    }
    if (this.drifting) this.yaw += 0.0006
    this.render()
    if (moving || this.drifting) this.changed()
  },

  render() {
    const gl = this.gl
    if (!gl || !this.ready) return
    this.constrain()
    gl.viewport(0, 0, this.canvas.width, this.canvas.height)
    gl.uniform1i(this.uniforms.photo, 0)
    gl.uniform1f(this.uniforms.yaw, this.yaw)
    gl.uniform1f(this.uniforms.pitch, this.pitch)
    gl.uniform1f(this.uniforms.tanHalf, Math.tan(this.fov / 2))
    gl.uniform1f(this.uniforms.aspect, this.canvas.width / this.canvas.height)
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)

    if (this.heading !== null && this.compassEl) {
      const facing = this.heading + this.yaw / DEG
      this.compassEl.textContent = `${compass(facing)} ${Math.round((((facing % 360) + 360) % 360))}°`
      this.compassEl.classList.remove("hidden")
    }
  }
}