{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dream-cat",
  "title": "Dream Cat",
  "description": "The mewo cat in a dream, its outline fraying into a slowly drifting fog: its round hand reaches for the pointer wherever it is, the arm stretching as far as it must, and stirs the fog as it goes; its eyes follow and its body leans in. Drawn with WebGL 2 on ogl; the drift can be stopped, and then it is idle while the pointer rests.",
  "dependencies": [
    "ogl"
  ],
  "files": [
    {
      "path": "registry/mewo/ui/dream-cat.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { Camera, Euler, GLTFLoader, Mat4, Mesh, Program, Quat, RenderTarget, Renderer, Texture, Transform, Triangle, Vec3, type GLTFMaterial, type OGLRenderingContext } from \"ogl\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface DreamCatProps extends Omit<React.ComponentProps<\"div\">, \"children\" | \"onLoad\" | \"onError\"> {\n  /** Address of the character's model: a .glb, y up, facing +z. Same-origin or served with CORS. */\n  src?: string\n  /** Accessible description of the character. Without it the character is decorative. */\n  alt?: string\n  /** Fur colour, any CSS colour. An empty string keeps the model's own blue. */\n  color?: string\n  /** Follow the pointer anywhere on the page: the hand reaches for it, the eyes look at it, the body leans toward it. */\n  track?: boolean\n  /** How far the arm can turn from its rest pose, in degrees. 180 lets it point anywhere. */\n  reach?: number\n  /** How far the forearm can stretch to bring the hand under the pointer, as a multiple of its length. 1 keeps it as modelled. */\n  stretch?: number\n  /** How far the eyes can roll, in degrees. 0 holds them still. */\n  gaze?: number\n  /** How far the body turns toward the pointer, in degrees. */\n  lean?: number\n  /** Seconds the pose takes to catch up with the pointer (about two thirds of the way). */\n  smoothing?: number\n  /** Size of the character in its box: 1 fits it whole, 2 fills the box with its head and hand. */\n  zoom?: number\n  /** Where the character's middle sits across its box: 0 at the left edge, 0.5 in the middle, 1 at the right edge. */\n  x?: number\n  /** Where the character's middle sits down its box: 0 at the top edge, 0.5 in the middle, 1 at the bottom edge. */\n  y?: number\n  /** Strength of the velvet sheen along the edges. */\n  sheen?: number\n  /** Overall brightness. */\n  exposure?: number\n  /** How thick the dream's fog is, 0 to 1. 0 for no fog. */\n  fog?: number\n  /** Colour of the fog and of the light along the character's fraying outline, any CSS colour. */\n  fogColor?: string\n  /** How strongly the hand stirs the fog as it moves through it. 0 leaves it still. */\n  swirl?: number\n  /** How much the character's outline blurs and comes apart into rising dots, 0 to 1. 0 keeps a clean outline. */\n  dissolve?: number\n  /** The pupils: rings that ripple outward with the dream, or plain. */\n  eyes?: DreamCatEyes\n  /** Speed of the dream's slow motion: the fog drifting and the wisps rising. 0 holds it still and costs nothing at rest. */\n  drift?: number\n  /** Render scale cap. The device pixel ratio is also capped at 2 and by a pixel budget. */\n  dpr?: number\n  /** Content layered above the character. */\n  children?: React.ReactNode\n  /** The model loaded and the first frame is drawn. */\n  onLoad?: () => void\n  /** The model could not be loaded. */\n  onError?: (error: Error) => void\n}\n\ntype Settings = Required<Pick<DreamCatProps, \"track\" | \"reach\" | \"stretch\" | \"gaze\" | \"lean\" | \"smoothing\" | \"zoom\" | \"x\" | \"y\" | \"sheen\" | \"exposure\" | \"fog\" | \"fogColor\" | \"swirl\" | \"dissolve\" | \"drift\" | \"eyes\" | \"dpr\">> &\n  Pick<DreamCatProps, \"src\" | \"color\" | \"onLoad\" | \"onError\">\n\nexport type Bounds = { min: [number, number, number]; max: [number, number, number] }\n\nexport type DreamCatEyes = \"rings\" | \"plain\"\n\nconst PIXEL_BUDGET = 4.5e6\n// the fog: a coarse grid over the box, about this many cells whatever its shape\nconst FOG_CELLS = 9000\n// the fog's motion fades in a few seconds and the fog fills back in where the hand pushed it away; the swirl\n// feeds its eddies back so it curls like smoke; the pressure steps keep it flowing without piling up\nconst FOG_DRAG = 1.6\nconst FOG_REFILL = 0.7\nconst FOG_SWIRL = 1.5\nconst FOG_PRESSURE_STEPS = 16\n// below these the fog is left as it is and the loop may stop\nconst FOG_CALM_SPEED = 0.03\nconst FOG_CALM_THICKNESS = 0.02\nconst FOV = 22\n// the box around the character, as a share of its size, so the ears and the hand never touch the edges\nconst MARGIN = 1.12\n// Must match what ogl's Renderer passes to getContext(), so the probe below and ogl share one context.\nconst CONTEXT_ATTRIBUTES = {\n  alpha: true,\n  depth: true,\n  stencil: false,\n  antialias: false,\n  premultipliedAlpha: true,\n  preserveDrawingBuffer: false,\n  powerPreference: \"default\" as const,\n}\n// how many dark rings cross a ringed pupil, from its middle to its rim\nconst PUPIL_RINGS = 3\n// the parts the pose drives, by node name; a model without them still renders, standing still\nconst NODES = { body: \"mewo\", arm: \"arm.R\", pupils: [\"pupil.L\", \"pupil.R\"] }\n\nconst clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max)\nconst toRadians = (degrees: number) => (degrees * Math.PI) / 180\n\n/** How far an eased value moves toward its target this frame, for a time constant in seconds. */\nexport function followStep(smoothing: number, dt: number) {\n  return smoothing <= 0 ? 1 : 1 - Math.exp(-dt / smoothing)\n}\n\n/**\n * Where the camera stands to frame the character: its x and y, and its distance in front of the character's\n * middle. `zoom` sets the size, then the camera moves so the character's middle lands at (`across`, `down`) in\n * the box, each 0 to 1 from the top left; past 0 or 1, the character goes partly out of the box.\n */\nexport function fitView(bounds: Bounds, aspect: number, zoom: number, across = 0.5, down = 0.5) {\n  const t = Math.tan(toRadians(FOV) / 2)\n  const halfWidth = ((bounds.max[0] - bounds.min[0]) / 2) * MARGIN\n  const halfHeight = ((bounds.max[1] - bounds.min[1]) / 2) * MARGIN\n  const distance = Math.max(halfHeight / t, halfWidth / (t * Math.max(aspect, 1e-3))) / zoom\n  // half the view at the character's middle; the camera moves the opposite way to the character\n  const viewX = t * distance * aspect\n  const viewY = t * distance\n  return {\n    x: (bounds.min[0] + bounds.max[0]) / 2 - (across * 2 - 1) * viewX,\n    y: (bounds.min[1] + bounds.max[1]) / 2 + (down * 2 - 1) * viewY,\n    distance,\n  }\n}\n\n/** The rotation that turns `from` toward `to`, by at most `limit` radians, scaled by `amount` (0 to 1). */\nexport function turnToward(from: Vec3, to: Vec3, limit: number, amount: number, out = new Quat()) {\n  const a = from.clone().normalize()\n  const b = to.clone().normalize()\n  const axis = new Vec3().cross(a, b)\n  const sin = axis.len()\n  const angle = Math.atan2(sin, a.dot(b))\n  if (sin < 1e-6 || amount <= 0) return out.identity()\n  return out.fromAxisAngle(axis.scale(1 / sin), Math.min(angle, limit) * clamp(amount, 0, 1))\n}\n\n/**\n * Where a ray first meets a sphere, or, when it passes by, its point nearest the sphere's centre. The hand is\n * aimed at it: within the arm's length the hand lands under the pointer, and beyond it the forearm stretches.\n */\nexport function reachPoint(origin: Vec3, direction: Vec3, centre: Vec3, radius: number, out = new Vec3()) {\n  const offset = new Vec3().sub(origin, centre)\n  const b = offset.dot(direction)\n  const disc = b * b - (offset.squaredLen() - radius * radius)\n  const t = disc >= 0 ? -b - Math.sqrt(disc) : -b\n  return out.copy(direction).scale(Math.max(t, 0)).add(origin)\n}\n\n/**\n * How much the forearm grows so that the hand's middle, `length` from the shoulder as modelled, lands `distance`\n * away. Only the part up to the wrist grows, so the hand keeps its round shape.\n */\nexport function stretchFor(distance: number, length: number, wrist: number, max: number) {\n  return clamp(1 + (distance - length) / Math.max(wrist, 1e-3), 1, Math.max(1, max))\n}\n\n/**\n * The arm a joint moves, in the model's saved pose: the direction from the shoulder to its hand's middle, how far\n * that middle is, where the hand begins (the forearm stretches up to there), and how far forward the rest of the\n * body comes, so the hand can be kept in front of it.\n */\nfunction armShape(mesh: Mesh, joint: Transform, shoulder: Vec3) {\n  const joints = (mesh as Mesh & { skeleton?: { joints: Transform[] } }).skeleton?.joints ?? []\n  const index = joints.indexOf(joint)\n  const { position: positions, skinIndex: indices, skinWeight: weights } = mesh.geometry.attributes\n  const position = positions?.data\n  const joint4 = indices?.data\n  const weight4 = weights?.data\n  if (index < 0 || !position || !joint4 || !weight4) return null\n  // weights stored as integers are fractions of their type's largest value\n  const scale = weight4 instanceof Float32Array ? 1 : weight4 instanceof Uint8Array ? 1 / 255 : 1 / 65535\n  const arm: number[] = []\n  const reach: number[] = []\n  let farthest = 0\n  let front = -Infinity\n  const q = new Vec3()\n  for (let v = 0; v < position.length / 3; v++) {\n    let weight = 0\n    for (let k = 0; k < 4; k++) if (joint4[v * 4 + k] === index) weight += weight4[v * 4 + k] * scale\n    if (weight < 0.05) front = Math.max(front, position[v * 3 + 2])\n    if (weight < 0.95) continue\n    const d = q.fromArray(position, v * 3).sub(shoulder).len()\n    arm.push(v)\n    reach.push(d)\n    farthest = Math.max(farthest, d)\n  }\n  if (!arm.length) return null\n  // a first direction, toward the middle of the far end\n  const axis = new Vec3()\n  arm.forEach((v, i) => {\n    if (reach[i] >= farthest * 0.75) axis.add(q.fromArray(position, v * 3).sub(shoulder))\n  })\n  axis.normalize()\n  // the hand's radius: the widest the arm gets around that line, out past its middle\n  let radius = 0\n  for (const v of arm) {\n    q.fromArray(position, v * 3).sub(shoulder)\n    const along = q.dot(axis)\n    if (along < farthest * 0.5) continue\n    radius = Math.max(radius, q.sub(axis.clone().scale(along)).len())\n  }\n  const length = farthest - radius\n  return { index, axis, length, radius, wrist: Math.max(length - radius, length * 0.3), front: front + radius * 0.5 }\n}\n\nexport type Fog = {\n  width: number\n  height: number\n  /** The fog's motion, in cells a second, y up. */\n  u: Float32Array\n  v: Float32Array\n  /** How thick the fog is in each cell, and how thick it is at rest. */\n  density: Float32Array\n  rest: Float32Array\n  scratch: [Float32Array, Float32Array, Float32Array, Float32Array]\n  calm: boolean\n}\n\n/**\n * The fog's grid over a box `aspect` times wider than tall, still and full everywhere. It holds what the hand\n * does to the fog (where it cleared it, and how it set it moving); the fog's look is drawn over it.\n */\nexport function createFog(aspect: number): Fog {\n  const height = Math.max(8, Math.round(Math.sqrt(FOG_CELLS / Math.max(aspect, 0.1))))\n  const width = Math.max(8, Math.round(height * aspect))\n  const n = width * height\n  const field = () => new Float32Array(n)\n  const rest = field().fill(1)\n  return { width, height, u: field(), v: field(), density: rest.slice(), rest, scratch: [field(), field(), field(), field()], calm: true }\n}\n\n/** The fog's grid as texels: how much fog is left, and its motion in box widths and heights a second. */\nexport function packFog(fog: Fog, out: Float32Array) {\n  const { width, height, u, v, density } = fog\n  for (let c = 0; c < width * height; c++) {\n    out[c * 4] = density[c]\n    out[c * 4 + 1] = u[c] / width\n    out[c * 4 + 2] = v[c] / height\n    out[c * 4 + 3] = 1\n  }\n  return out\n}\n\n/** A field read between its cells, its edge cells standing in past the edges. */\nfunction sample(field: Float32Array, width: number, height: number, x: number, y: number) {\n  const cx = clamp(x, 0, width - 1)\n  const cy = clamp(y, 0, height - 1)\n  const i = Math.min(Math.floor(cx), width - 2)\n  const j = Math.min(Math.floor(cy), height - 2)\n  const fx = cx - i\n  const fy = cy - j\n  const a = field[j * width + i]\n  const b = field[j * width + i + 1]\n  const c = field[(j + 1) * width + i]\n  const d = field[(j + 1) * width + i + 1]\n  return a + (b - a) * fx + (c - a) * fy + (a - b - c + d) * fx * fy\n}\n\n/**\n * The hand moving through the fog at (`x`, `y`) (0 to 1 from the box's bottom left), `radius` box heights wide,\n * at (`vx`, `vy`) box widths and heights a second. The fog round it is carried along by `amount` (0 to 1),\n * pushed a little outward and thinned, so the hand opens a clear path that the fog curls into behind it.\n */\nexport function stirFog(fog: Fog, x: number, y: number, radius: number, vx: number, vy: number, amount: number) {\n  const { width, height, u, v, density } = fog\n  const cx = x * (width - 1)\n  const cy = y * (height - 1)\n  const r = Math.max(radius * height, 1.5)\n  const tx = vx * width\n  const ty = vy * height\n  const speed = Math.hypot(tx, ty)\n  const k = clamp(amount, 0, 1)\n  // a hand crossing the box in a second clears most of the fog it passes through\n  const clearing = clamp(speed / Math.max(width, height), 0, 1) * 0.35\n  for (let j = Math.max(0, Math.floor(cy - 3 * r)); j <= Math.min(height - 1, Math.ceil(cy + 3 * r)); j++) {\n    for (let i = Math.max(0, Math.floor(cx - 3 * r)); i <= Math.min(width - 1, Math.ceil(cx + 3 * r)); i++) {\n      const dx = i - cx\n      const dy = j - cy\n      const g = Math.exp(-(dx * dx + dy * dy) / (r * r)) * k\n      if (g < 1e-4) continue\n      const d = Math.hypot(dx, dy) || 1\n      const c = j * width + i\n      u[c] += (tx + (dx / d) * speed * 0.3 - u[c]) * g\n      v[c] += (ty + (dy / d) * speed * 0.3 - v[c]) * g\n      density[c] *= 1 - g * clearing\n    }\n  }\n  if (k > 0) fog.calm = false\n}\n\n/**\n * One step of the fog: its eddies are fed back so it curls like smoke, its motion carries itself along and\n * fades, a pressure solve keeps it flowing without piling up, and it carries the fog, which drifts back toward\n * its resting pattern. Returns true once it is calm; a calm fog costs nothing to step.\n */\nexport function stepFog(fog: Fog, dt: number) {\n  if (fog.calm) return true\n  const { width: w, height: h, u, v, density, rest } = fog\n  const [u0, v0, curl, pressure] = fog.scratch\n\n  for (let j = 1; j < h - 1; j++)\n    for (let i = 1; i < w - 1; i++) {\n      const c = j * w + i\n      curl[c] = 0.5 * (v[c + 1] - v[c - 1] - (u[c + w] - u[c - w]))\n    }\n  for (let j = 2; j < h - 2; j++)\n    for (let i = 2; i < w - 2; i++) {\n      const c = j * w + i\n      const gx = 0.5 * (Math.abs(curl[c + 1]) - Math.abs(curl[c - 1]))\n      const gy = 0.5 * (Math.abs(curl[c + w]) - Math.abs(curl[c - w]))\n      const length = Math.hypot(gx, gy) + 1e-5\n      u[c] += FOG_SWIRL * (gy / length) * curl[c] * dt\n      v[c] -= FOG_SWIRL * (gx / length) * curl[c] * dt\n    }\n\n  u0.set(u)\n  v0.set(v)\n  const fade = Math.exp(-FOG_DRAG * dt)\n  for (let j = 0; j < h; j++)\n    for (let i = 0; i < w; i++) {\n      const c = j * w + i\n      const x = i - dt * u0[c]\n      const y = j - dt * v0[c]\n      u[c] = sample(u0, w, h, x, y) * fade\n      v[c] = sample(v0, w, h, x, y) * fade\n    }\n\n  // the box's edges are open: the fog may flow out, and comes back as it refills\n  const divergence = curl\n  for (let j = 1; j < h - 1; j++)\n    for (let i = 1; i < w - 1; i++) {\n      const c = j * w + i\n      divergence[c] = 0.5 * (u[c + 1] - u[c - 1] + v[c + w] - v[c - w])\n    }\n  pressure.fill(0)\n  for (let k = 0; k < FOG_PRESSURE_STEPS; k++)\n    for (let j = 1; j < h - 1; j++)\n      for (let i = 1; i < w - 1; i++) {\n        const c = j * w + i\n        pressure[c] = (pressure[c - 1] + pressure[c + 1] + pressure[c - w] + pressure[c + w] - divergence[c]) / 4\n      }\n  for (let j = 1; j < h - 1; j++)\n    for (let i = 1; i < w - 1; i++) {\n      const c = j * w + i\n      u[c] -= 0.5 * (pressure[c + 1] - pressure[c - 1])\n      v[c] -= 0.5 * (pressure[c + w] - pressure[c - w])\n    }\n\n  u0.set(density)\n  const refill = 1 - Math.exp(-FOG_REFILL * dt)\n  let fastest = 0\n  let farthest = 0\n  for (let j = 0; j < h; j++)\n    for (let i = 0; i < w; i++) {\n      const c = j * w + i\n      const carried = sample(u0, w, h, i - dt * u[c], j - dt * v[c])\n      density[c] = carried + (rest[c] - carried) * refill\n      fastest = Math.max(fastest, Math.abs(u[c]), Math.abs(v[c]))\n      farthest = Math.max(farthest, Math.abs(density[c] - rest[c]))\n    }\n  if (fastest < FOG_CALM_SPEED && farthest < FOG_CALM_THICKNESS) {\n    u.fill(0)\n    v.fill(0)\n    density.set(rest)\n    fog.calm = true\n  }\n  return fog.calm\n}\n\n/** A CSS colour as linear RGB, or null when the browser can't read it. */\nfunction linearColor(value: string | undefined): [number, number, number] | null {\n  if (!value) return null\n  const context = document.createElement(\"canvas\").getContext(\"2d\")\n  if (!context) return null\n  context.fillStyle = \"#000\"\n  context.fillStyle = value\n  const parsed = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(context.fillStyle)\n  const channels = parsed\n    ? parsed.slice(1).map((hex) => parseInt(hex, 16) / 255)\n    : (/rgba?\\(([^)]+)\\)/.exec(context.fillStyle)?.[1].split(\",\").slice(0, 3).map((part) => parseFloat(part) / 255) ?? null)\n  if (!channels) return null\n  const linear = channels.map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4))\n  return [linear[0], linear[1], linear[2]]\n}\n\nconst VERTEX = /* glsl */ `#version 300 es\nin vec3 position;\nin vec3 normal;\n#ifdef SKINNED\nin vec4 skinIndex;\nin vec4 skinWeight;\nuniform sampler2D boneTexture;\nuniform int boneTextureSize;\nuniform vec3 uShoulder;\nuniform vec3 uAxis;\nuniform float uWrist;\nuniform float uStretch;\nuniform float uArmJoint;\nmat4 bone(float index) {\n  int i = int(index) * 4;\n  return mat4(\n    texelFetch(boneTexture, ivec2(i % boneTextureSize, i / boneTextureSize), 0),\n    texelFetch(boneTexture, ivec2((i + 1) % boneTextureSize, (i + 1) / boneTextureSize), 0),\n    texelFetch(boneTexture, ivec2((i + 2) % boneTextureSize, (i + 2) / boneTextureSize), 0),\n    texelFetch(boneTexture, ivec2((i + 3) % boneTextureSize, (i + 3) / boneTextureSize), 0)\n  );\n}\n#endif\nuniform mat4 modelMatrix;\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\nout vec3 vNormal;\nout vec3 vWorld;\nout vec3 vLocal;\nvoid main() {\n  mat4 world = modelMatrix;\n  vec3 at = position;\n#ifdef SKINNED\n  // the forearm grows along its length up to the wrist, and the hand moves out with it, keeping its shape\n  float arm = dot(skinWeight, vec4(equal(skinIndex, vec4(uArmJoint))));\n  float along = dot(position - uShoulder, uAxis);\n  float grown = along < uWrist ? along * uStretch : along + uWrist * (uStretch - 1.0);\n  at += uAxis * max(grown - along, 0.0) * arm;\n  world = skinWeight.x * bone(skinIndex.x) + skinWeight.y * bone(skinIndex.y) + skinWeight.z * bone(skinIndex.z) + skinWeight.w * bone(skinIndex.w);\n#endif\n  vec4 p = world * vec4(at, 1.0);\n  vWorld = p.xyz;\n  vLocal = position;\n  vNormal = mat3(world) * normal;\n  gl_Position = projectionMatrix * viewMatrix * p;\n}`\n\n// A soft studio light on a velvet surface: wrapped diffuse from a key, a fill and a rim light, a sky-to-floor\n// ambient, a sheen that brightens the surface where it turns away from the eye, and a gloss for the eyes.\nconst FRAGMENT = /* glsl */ `#version 300 es\nprecision highp float;\nin vec3 vNormal;\nin vec3 vWorld;\nin vec3 vLocal;\nuniform vec3 cameraPosition;\nuniform float uRings;\nuniform vec3 uRingAxis;\nuniform float uRingScale;\nuniform vec3 uRingLight;\nuniform float uTime;\nuniform vec3 uColor;\nuniform vec3 uSheenColor;\nuniform float uSheen;\nuniform float uRoughness;\nuniform float uGloss;\nuniform vec3 uEmissive;\nuniform float uExposure;\nout vec4 fragColor;\n\nconst vec3 KEY = vec3(-0.42, 0.72, 0.55);\nconst vec3 FILL = vec3(0.75, 0.15, 0.6);\nconst vec3 RIM = vec3(0.2, 0.55, -0.8);\n\nfloat wrapped(vec3 n, vec3 l, float wrap) {\n  return max((dot(n, l) + wrap) / (1.0 + wrap), 0.0);\n}\n\nfloat gloss(vec3 n, vec3 v, vec3 l, float roughness) {\n  vec3 h = normalize(v + l);\n  float a = roughness * roughness;\n  float a2 = a * a;\n  float nh = max(dot(n, h), 0.0);\n  float d = nh * nh * (a2 - 1.0) + 1.0;\n  return a2 / (3.14159 * d * d) * max(dot(n, l), 0.0);\n}\n\nvec3 tonemap(vec3 c) {\n  // a filmic curve that keeps saturated blues blue, then sRGB\n  c = (c * (2.51 * c + 0.03)) / (c * (2.43 * c + 0.59) + 0.14);\n  return pow(clamp(c, 0.0, 1.0), vec3(1.0 / 2.2));\n}\n\nvoid main() {\n  vec3 n = normalize(vNormal);\n  if (!gl_FrontFacing) n = -n;\n  vec3 v = normalize(cameraPosition - vWorld);\n  vec3 key = normalize(KEY);\n  vec3 fill = normalize(FILL);\n  vec3 rim = normalize(RIM);\n  float nv = clamp(dot(n, v), 0.0, 1.0);\n\n  vec3 ambient = mix(vec3(0.16, 0.17, 0.22), vec3(0.62, 0.68, 0.8), n.y * 0.5 + 0.5);\n  vec3 light = ambient + vec3(1.0, 0.97, 0.92) * 2.1 * wrapped(n, key, 0.35) + vec3(0.7, 0.78, 1.0) * 0.55 * wrapped(n, fill, 0.5);\n  vec3 base = uColor;\n  if (uRings > 0.0) {\n    // rings round the pupil's middle out to its rim, dark and light, rippling outward as the dream drifts\n    float d = acos(clamp(dot(normalize(vLocal), uRingAxis), -1.0, 1.0)) * uRingScale - uTime * 0.6;\n    float band = abs(fract(d) - 0.5) * 2.0;\n    float w = fwidth(d) * 2.0;\n    base = mix(uColor, uRingLight, smoothstep(0.5 - w, 0.5 + w, band) * uRings);\n  }\n  vec3 color = base * light;\n\n  // velvet: the fibres catch the light at grazing angles, so the edges glow in a lighter tint\n  float edge = pow(1.0 - nv, 2.2);\n  vec3 sheen = uSheenColor * uSheen * (edge * (0.55 * ambient + 0.9 * wrapped(n, key, 0.6)) + 1.6 * pow(1.0 - nv, 4.0) * wrapped(n, rim, 0.8));\n  color += sheen;\n\n  if (uGloss > 0.0) {\n    float spec = gloss(n, v, key, uRoughness) * 2.0 + gloss(n, v, fill, uRoughness) * 0.5;\n    float fresnel = 0.04 + 0.96 * pow(1.0 - nv, 5.0);\n    color += uGloss * (spec * 0.25 + fresnel * 0.35 * ambient);\n  }\n\n  color += uEmissive;\n  fragColor = vec4(tonemap(color * uExposure), 1.0);\n}`\n\nconst COMPOSE_VERTEX = /* glsl */ `#version 300 es\nin vec2 position;\nin vec2 uv;\nout vec2 vUv;\nvoid main() {\n  vUv = uv;\n  gl_Position = vec4(position, 0.0, 1.0);\n}`\n\n// The dream, composed from the character drawn on its own: a luminous fog of slowly folding light behind it,\n// the character blurring and turning to light toward its outline, which breaks into dots that drift upward, an\n// aura and rising streaks round it, and thin veils of fog in front. Where the hand went the fog is thinner, and\n// while the fog moves it drags the folds along.\nconst COMPOSE_FRAGMENT = /* glsl */ `#version 300 es\nprecision highp float;\nin vec2 vUv;\nuniform sampler2D uScene;\nuniform sampler2D uStir;\nuniform vec2 uResolution;\nuniform float uTime;\nuniform float uFog;\nuniform vec3 uFogColor;\nuniform float uDissolve;\nuniform float uPixelRatio;\nout vec4 fragColor;\n\nfloat hash(vec2 p) {\n  vec3 q = fract(vec3(p.xyx) * 0.1031);\n  q += dot(q, q.yzx + 33.33);\n  return fract((q.x + q.y) * q.z);\n}\n\nfloat noise(vec2 p) {\n  vec2 i = floor(p);\n  vec2 f = fract(p);\n  vec2 s = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);\n  float a = hash(i);\n  float b = hash(i + vec2(1.0, 0.0));\n  float c = hash(i + vec2(0.0, 1.0));\n  float d = hash(i + vec2(1.0, 1.0));\n  return mix(mix(a, b, s.x), mix(c, d, s.x), s.y);\n}\n\nfloat fbm(vec2 p) {\n  float sum = 0.0;\n  float amp = 0.5;\n  mat2 turn = mat2(1.6, 1.2, -1.2, 1.6);\n  for (int i = 0; i < 4; i++) {\n    sum += amp * noise(p);\n    p = turn * p;\n    amp *= 0.5;\n  }\n  return sum;\n}\n\nvoid main() {\n  float aspect = uResolution.x / uResolution.y;\n  vec2 uv = vUv;\n  vec2 p = uv * vec2(aspect, 1.0);\n  float t = uTime;\n  vec4 stir = texture(uStir, uv);\n  float left = stir.r;\n  vec2 drag = stir.gb * vec2(aspect, 1.0) * 0.08;\n\n  // the fog: noise folded through itself, drifting; a fuller layer behind, thin veils in front\n  vec2 q = p * 1.2 - drag;\n  vec2 fold = vec2(fbm(q + vec2(0.0, t * 0.05)), fbm(q + vec2(5.2, 1.3) - vec2(t * 0.04, 0.0)));\n  float back = smoothstep(0.25, 0.85, fbm(q + 1.7 * fold + vec2(t * 0.02, 0.0))) * left;\n  float front = smoothstep(0.5, 0.9, fbm(p * 2.2 - drag * 1.5 + 1.3 * fold + vec2(-t * 0.06, t * 0.03) + 7.0)) * left;\n\n  // how far inside the character this pixel is: the share of a disc round it that the character covers,\n  // 1 deep inside, about half on the outline, falling to 0 a disc away; the same taps give its blurred colour\n  float radius = 0.02 + 0.08 * uDissolve;\n  vec4 blur = vec4(0.0);\n  for (int k = 0; k < 16; k++) {\n    float a = float(k) * 2.39996;\n    float r = sqrt((float(k) + 0.5) / 16.0) * radius;\n    blur += texture(uScene, uv + vec2(cos(a) / aspect, sin(a)) * r);\n  }\n  blur /= 16.0;\n  float cover = blur.a;\n  float edge = 1.0 - smoothstep(0.4, 0.98, cover);\n  float wisp = fbm(p * 4.5 + vec2(0.0, -t * 0.22) + fold * 0.6);\n  float wisp2 = fbm(p * 4.5 + vec2(3.7, -t * 0.18));\n  vec2 smear = (vec2(wisp, wisp2) - 0.5) * radius * 0.7 * edge;\n  smear.y -= radius * 0.4 * edge;\n  smear.x /= aspect;\n  // toward its outline the character comes apart into round dots, one to a small cell: nearly touching where\n  // the character is, smaller and rarer further out, each a little off its cell's middle and there or not by\n  // chance; the cells drift upward, so the dots rise\n  float size = 8.0 * uPixelRatio;\n  vec2 dp = vUv * uResolution - vec2(0.0, t * 16.0 * uPixelRatio);\n  vec2 cell = floor(dp / size);\n  vec2 inCell = dp - (cell + 0.5) * size;\n  float chance = hash(cell);\n  vec2 jitter = (vec2(hash(cell + 17.3), hash(cell + 41.7)) - 0.5) * size * 0.3;\n  float dotRadius = size * mix(0.1, 0.5, smoothstep(0.15, 0.9, cover)) * (0.8 + 0.4 * hash(cell + 7.1));\n  float dotShape = 1.0 - smoothstep(dotRadius - uPixelRatio, dotRadius, length(inCell - jitter));\n  float band = smoothstep(0.0, 0.3, cover);\n  float dots = dotShape * step(chance, band * uDissolve * 1.6);\n  // the solid character gives way to the dots toward its outline; what is left blurs and turns to the light\n  vec4 body = mix(texture(uScene, uv + smear), blur, edge * uDissolve);\n  // the outline itself is worn away: bitten into by a finer noise that drifts up with the dream, and soft where\n  // it gives, like fog; only along the outline: well inside, the character stays whole\n  float wear = (fbm(p * 16.0 + vec2(0.0, -t * 0.3)) - 0.5) * 1.5 + (wisp - 0.5) * 0.7;\n  float rim = 1.0 - smoothstep(0.88, 1.0, cover);\n  float solid = uDissolve > 0.0 ? smoothstep(0.6, 0.95, cover + wear * uDissolve * rim) : 1.0;\n  float bodyAlpha = body.a * solid;\n  vec3 light = pow(uFogColor, vec3(1.0 / 2.2));\n  vec3 bodyColor = mix(body.rgb, light * body.a, edge * 0.45 * uDissolve);\n  float aura = uDissolve * smoothstep(0.0, 0.45, cover) * (1.0 - smoothstep(0.45, 1.0, cover)) * 0.7;\n  vec3 dotColor = mix(blur.rgb / max(blur.a, 0.05), light, 0.1 + 0.65 * (1.0 - smoothstep(0.2, 0.9, cover)));\n  // just outside the outline, tall streaks of noise rising: smoke leaving the character, its colour turning to light\n  float streak = smoothstep(0.5, 0.82, fbm(p * vec2(7.0, 2.6) + vec2(0.0, -t * 0.35) + fold * 0.8));\n  float smoke = uDissolve * streak * smoothstep(0.02, 0.35, cover) * (1.0 - smoothstep(0.35, 0.7, cover)) * 0.6;\n  vec3 smokeColor = mix(blur.rgb / max(blur.a, 0.05), light, 0.55);\n\n  float alpha = uFog * (0.22 + 0.6 * back);\n  vec3 color = light * (0.75 + 0.7 * back) * alpha;\n  color = bodyColor * solid + color * (1.0 - bodyAlpha);\n  alpha = bodyAlpha + alpha * (1.0 - bodyAlpha);\n  color += light * aura * 0.4;\n  alpha = min(1.0, alpha + aura * 0.25);\n  color = smokeColor * smoke + color * (1.0 - smoke);\n  alpha = smoke + alpha * (1.0 - smoke);\n  // only where the solid character has given way\n  float dotAlpha = dots * 0.95 * (1.0 - solid);\n  color = dotColor * dotAlpha + color * (1.0 - dotAlpha);\n  alpha = dotAlpha + alpha * (1.0 - dotAlpha);\n  float veil = uFog * 0.4 * front;\n  color = light * (0.9 + 0.3 * front) * veil + color * (1.0 - veil);\n  alpha = veil + alpha * (1.0 - veil);\n  fragColor = vec4(color, alpha);\n}`\n\ntype Part = { program: Program; fur: boolean; base: [number, number, number]; sheen: [number, number, number] }\n\n/** A program for one of the model's materials, its uniforms set from the material's own factors. */\nfunction makePart(gl: OGLRenderingContext, material: GLTFMaterial | undefined, skinned: boolean): Part {\n  const fur = skinned || material?.name === \"fur\"\n  const base = (material?.baseColorFactor?.slice(0, 3) ?? [0.8, 0.8, 0.8]) as [number, number, number]\n  const sheenExtension = material?.extensions?.KHR_materials_sheen\n  const sheen = (sheenExtension?.sheenColorFactor ?? (fur ? base.map((c) => c * 0.4 + 0.08) : [0, 0, 0])) as [number, number, number]\n  const roughness = material?.roughnessFactor ?? 0.8\n  const program = new Program(gl, {\n    vertex: skinned ? VERTEX.replace(\"#version 300 es\", \"#version 300 es\\n#define SKINNED\") : VERTEX,\n    fragment: FRAGMENT,\n    cullFace: material?.doubleSided ? false : gl.BACK,\n    uniforms: {\n      uColor: { value: base.slice() },\n      uSheenColor: { value: sheen.slice() },\n      uSheen: { value: 1 },\n      uRoughness: { value: Math.max(0.08, roughness) },\n      // the eyes and pupils are smooth: they get the gloss, the fur gets none\n      uGloss: { value: roughness < 0.6 ? 1 : 0 },\n      uEmissive: { value: (material?.emissiveFactor ?? [0, 0, 0]).slice() },\n      uExposure: { value: 1 },\n      // rings on the pupils, set per pupil as it is drawn; off elsewhere\n      uRings: { value: 0 },\n      uRingAxis: { value: [0, 0, 1] },\n      uRingScale: { value: 1 },\n      uRingLight: { value: [0.81, 0.81, 0.86] },\n      uTime: { value: 0 },\n      // the arm's stretch, set once the arm is found; at rest it changes nothing\n      ...(skinned ? { uShoulder: { value: [0, 0, 0] }, uAxis: { value: [0, 0, 1] }, uWrist: { value: 1 }, uStretch: { value: 1 }, uArmJoint: { value: -1 } } : {}),\n    },\n  })\n  return { program, fur, base, sheen }\n}\n\n/** The world-space box around every mesh, in the pose the model was saved in. */\nfunction measure(scene: Transform): Bounds {\n  const min = new Vec3(Infinity, Infinity, Infinity)\n  const max = new Vec3(-Infinity, -Infinity, -Infinity)\n  const corner = new Vec3()\n  scene.updateMatrixWorld(true)\n  scene.traverse((node) => {\n    const mesh = node as Mesh\n    if (!mesh.geometry) return\n    mesh.geometry.computeBoundingBox()\n    const box = mesh.geometry.bounds\n    // a skinned mesh is placed by its bones, not by its node\n    const matrix = \"skeleton\" in mesh ? new Mat4() : mesh.worldMatrix\n    for (let i = 0; i < 8; i++) {\n      corner.set(i & 1 ? box.max[0] : box.min[0], i & 2 ? box.max[1] : box.min[1], i & 4 ? box.max[2] : box.min[2]).applyMatrix4(matrix)\n      for (let a = 0; a < 3; a++) {\n        min[a] = Math.min(min[a], corner[a])\n        max[a] = Math.max(max[a], corner[a])\n      }\n    }\n  })\n  return { min: [min[0], min[1], min[2]], max: [max[0], max[1], max[2]] }\n}\n\n/**\n * A 3D character in a dream, for the background of a section: its outline frays into wisps in a slowly drifting\n * fog, its round hand reaches for the pointer wherever it is on the page (the arm stretching as far as it must)\n * and stirs the fog as it goes, the eyes follow the pointer and the body leans toward it. Drawn with WebGL 2, only while the pose is still catching up.\n */\nexport function DreamCat({\n  src = \"/models/mewo.glb\",\n  alt,\n  color = \"#000000\",\n  track = true,\n  reach = 60,\n  stretch = 2.3,\n  gaze = 4,\n  lean = 10,\n  smoothing = 0.54,\n  zoom = 2.15,\n  x = 0.84,\n  y = 0.71,\n  sheen = 1.8,\n  exposure = 0.7,\n  fog = 0.5,\n  fogColor = \"#c6c6c6\",\n  swirl = 2.9,\n  dissolve = 1,\n  drift = 1.55,\n  eyes = \"rings\",\n  dpr = 1.5,\n  onLoad,\n  onError,\n  className,\n  children,\n  ...props\n}: DreamCatProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const settings: Settings = { src, color, track, reach, stretch, gaze, lean, smoothing, zoom, x, y, sheen, exposure, fog, fogColor, swirl, dissolve, drift, eyes, dpr, onLoad, onError }\n  const settingsRef = React.useRef(settings)\n  const wakeRef = React.useRef<(() => void) | null>(null)\n\n  // The context and the scene are built once. A prop change only updates the ref and wakes the loop, and a new\n  // model replaces the scene, never the context.\n  React.useEffect(() => {\n    const root = rootRef.current\n    if (!root) return\n\n    // The canvas is made here, not in JSX: React Strict Mode runs this effect twice in development, and the\n    // context the first cleanup loses would come straight back from getContext() on the same element. ogl throws\n    // when no context can be made (jsdom, a GPU-less browser), so the probe goes first, with ogl's own attributes.\n    const canvas = document.createElement(\"canvas\")\n    if (!canvas.getContext(\"webgl2\", CONTEXT_ATTRIBUTES)) return\n    const renderer = new Renderer({ canvas, ...CONTEXT_ATTRIBUTES })\n    const gl = renderer.gl\n    if (!renderer.isWebgl2) {\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n      return\n    }\n    gl.clearColor(0, 0, 0, 0)\n    canvas.className = \"absolute inset-0 block h-full w-full opacity-0 transition-opacity duration-700 motion-reduce:transition-none\"\n    canvas.setAttribute(\"aria-hidden\", \"true\")\n    root.prepend(canvas)\n\n    const camera = new Camera(gl, { fov: FOV, near: 0.3, far: 40 })\n    const scene = new Transform()\n\n    // the hand's middle on screen (0 to 1 from the bottom left) and its radius in box heights, and where it was\n    const onScreen = { hand: { x: 0, y: 0, r: 0, seen: false }, last: { x: 0, y: 0, seen: false } }\n    // the character is drawn into this target, then composed into the dream on the canvas\n    // (with a stencil, its depth buffer has 24 bits, enough to keep the pupils in front of the eyes)\n    const sceneTarget = new RenderTarget(gl, { width: 1, height: 1, depth: true, stencil: true })\n    // the fog's grid: simulated on the CPU, a cell per texel\n    let fog = createFog(1)\n    let fogTexels = packFog(fog, new Float32Array(fog.width * fog.height * 4))\n    const fogTexture = new Texture(gl, {\n      image: fogTexels,\n      width: fog.width,\n      height: fog.height,\n      type: gl.FLOAT,\n      format: gl.RGBA,\n      // half floats filter linearly in every WebGL 2 browser; full floats need an extension\n      internalFormat: (gl as WebGL2RenderingContext).RGBA16F,\n      generateMipmaps: false,\n      minFilter: gl.LINEAR,\n      magFilter: gl.LINEAR,\n      wrapS: gl.CLAMP_TO_EDGE,\n      wrapT: gl.CLAMP_TO_EDGE,\n      flipY: false,\n    })\n    const composeProgram = new Program(gl, {\n      vertex: COMPOSE_VERTEX,\n      fragment: COMPOSE_FRAGMENT,\n      depthTest: false,\n      depthWrite: false,\n      cullFace: false,\n      uniforms: {\n        uScene: { value: sceneTarget.texture },\n        uStir: { value: fogTexture },\n        uResolution: { value: [1, 1] },\n        uTime: { value: 0 },\n        uFog: { value: 0 },\n        uFogColor: { value: [0.6, 0.5, 1] },\n        uDissolve: { value: 0 },\n        uPixelRatio: { value: 1 },\n      },\n    })\n    const composeGeometry = new Triangle(gl)\n    const composeMesh = new Mesh(gl, { geometry: composeGeometry, program: composeProgram })\n    // a box of another shape gets a fog grid of its own, at rest\n    const fitFog = (aspect: number) => {\n      const next = createFog(aspect)\n      if (next.width === fog.width && next.height === fog.height) return\n      fog = next\n      fogTexels = packFog(fog, new Float32Array(fog.width * fog.height * 4))\n      fogTexture.image = fogTexels\n      fogTexture.width = fog.width\n      fogTexture.height = fog.height\n      fogTexture.needsUpdate = true\n    }\n    // the dream's own clock, which runs only while it drifts\n    let time = 0\n    const motionQuery = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\")\n    const dreaming = () => {\n      const s = settingsRef.current\n      return s.drift > 0 && (s.fog > 0 || s.dissolve > 0) && !(motionQuery?.matches ?? false)\n    }\n    let model: {\n      parts: Part[]\n      meshes: Mesh[]\n      bounds: Bounds\n      body: Transform | null\n      arm: { node: Transform; rest: Quat; axis: Vec3; length: number; radius: number; wrist: number; front: number; uniforms: Program[\"uniforms\"] } | null\n      pupils: { node: Transform; rest: Quat; look: Vec3 }[]\n      ringed: Program[]\n    } | null = null\n    let loaded = \"\"\n    let generation = 0\n    let planeZ = 1\n\n    // the pointer in the box's clip space, and how much the pose follows it (0 at rest, 1 tracking)\n    const aim = { x: 0, y: 0, weight: 0, tx: 0, ty: 0, tw: 0 }\n    let raf = 0\n    let last = 0\n    let visible = true\n\n    const target = new Vec3()\n    const local = new Vec3()\n    const direction = new Vec3()\n    const origin = new Vec3()\n    const hand = new Vec3()\n    const inverse = new Mat4()\n    const turn = new Quat()\n    const euler = new Euler()\n\n    const frameCamera = () => {\n      if (!model) return\n      const s = settingsRef.current\n      const aspect = canvas.width / Math.max(1, canvas.height)\n      const view = fitView(model.bounds, aspect, clamp(s.zoom, 0.3, 2.2), s.x, s.y)\n      const middle = (model.bounds.min[2] + model.bounds.max[2]) / 2\n      camera.perspective({ aspect })\n      camera.position.set(view.x, view.y, middle + view.distance)\n      // the eyes and the lean read the pointer where it crosses the front of the character\n      planeZ = model.bounds.max[2]\n      // a new framing moves the hand on screen without it moving: no stir from that\n      onScreen.last.seen = false\n      fitFog(aspect)\n    }\n\n    let colorKey: string | undefined\n    let custom: [number, number, number] | null = null\n    let fogKey: string | undefined\n    const applyLook = () => {\n      if (!model) return\n      const s = settingsRef.current\n      if (s.color !== colorKey) {\n        colorKey = s.color\n        custom = linearColor(s.color)\n      }\n      if (s.fogColor !== fogKey) {\n        fogKey = s.fogColor\n        const tint = linearColor(s.fogColor)\n        if (tint) composeProgram.uniforms.uFogColor.value = tint\n      }\n      for (const program of model.ringed) program.uniforms.uRings.value = s.eyes === \"plain\" ? 0 : 1\n      for (const part of model.parts) {\n        const u = part.program.uniforms\n        u.uExposure.value = s.exposure\n        u.uSheen.value = s.sheen\n        if (part.fur) {\n          u.uColor.value = custom ?? part.base\n          u.uSheenColor.value = custom ? custom.map((c) => c * 0.4 + 0.08) : part.sheen\n        }\n      }\n    }\n\n    // The pose for the eased pointer. The camera looks straight down -z, so the pointer is a ray from it; the body\n    // leans and the eyes look toward where that ray crosses the character's front, and the hand goes where the\n    // ray meets the arm's reach, the forearm stretching when the ray passes beyond it.\n    const pose = () => {\n      if (!model) return\n      const s = settingsRef.current\n      const t = Math.tan(toRadians(FOV) / 2)\n      const aspect = canvas.width / Math.max(1, canvas.height)\n      direction.set(aim.x * t * aspect, aim.y * t, -1).normalize()\n      const depth = camera.position[2] - planeZ\n      target.copy(direction).scale(depth / -direction[2]).add(camera.position)\n      const middle = [(model.bounds.min[0] + model.bounds.max[0]) / 2, (model.bounds.min[1] + model.bounds.max[1]) / 2]\n\n      if (model.body) {\n        const limit = toRadians(s.lean)\n        const yaw = clamp(Math.atan2(target[0] - middle[0], target[2]), -limit, limit)\n        const pitch = clamp(-Math.atan2(target[1] - middle[1], target[2]), -limit, limit)\n        model.body.quaternion.fromEuler(euler.set(pitch * aim.weight, yaw * aim.weight, 0))\n      }\n      scene.updateMatrixWorld(true)\n\n      if (model.arm) {\n        const { node, rest, axis, length, wrist, front, uniforms } = model.arm\n        // in the arm's parent space: the ray against a sphere round the shoulder as wide as the arm is long, the\n        // point slid along the ray to stay in front of the body, so the hand never sinks into it\n        inverse.inverse(node.parent!.worldMatrix)\n        origin.copy(camera.position).applyMatrix4(inverse)\n        local.copy(direction).transformDirection(inverse)\n        reachPoint(origin, local, node.position, length, hand)\n        if (hand[2] < front && local[2] < 0) hand.copy(local).scale((front - origin[2]) / local[2]).add(origin)\n        hand.sub(node.position)\n        uniforms.uStretch.value = 1 + (stretchFor(hand.len(), length, wrist, s.stretch) - 1) * aim.weight\n        turnToward(axis, hand, toRadians(s.reach), aim.weight, turn)\n        node.quaternion.multiply(turn, rest)\n        // where the hand's middle now is on screen, for the fog\n        const out = length + wrist * (uniforms.uStretch.value - 1)\n        hand.copy(axis).applyQuaternion(turn).scale(out).add(node.position).applyMatrix4(node.parent!.worldMatrix)\n        const away = Math.max(camera.position[2] - hand[2], 1e-3)\n        onScreen.hand.x = 0.5 + (hand[0] - camera.position[0]) / (t * aspect * away) / 2\n        onScreen.hand.y = 0.5 + (hand[1] - camera.position[1]) / (t * away) / 2\n        onScreen.hand.r = model.arm.radius / (t * away) / 2\n        onScreen.hand.seen = true\n      }\n      for (const pupil of model.pupils) {\n        local.copy(target).applyMatrix4(inverse.inverse(pupil.node.parent!.worldMatrix))\n        turnToward(pupil.look, local, toRadians(s.gaze), aim.weight, turn)\n        pupil.node.quaternion.multiply(turn, pupil.rest)\n      }\n      scene.updateMatrixWorld(true)\n    }\n\n    const render = () => {\n      const s = settingsRef.current\n      // the pupils' rings ripple on the dream's clock\n      for (const program of model?.ringed ?? []) program.uniforms.uTime.value = time\n      renderer.render({ scene, camera, target: sceneTarget })\n      const u = composeProgram.uniforms\n      u.uResolution.value = [canvas.width, canvas.height]\n      u.uTime.value = time\n      u.uFog.value = clamp(s.fog, 0, 1)\n      u.uDissolve.value = clamp(s.dissolve, 0, 1)\n      u.uPixelRatio.value = renderer.dpr\n      renderer.render({ scene: composeMesh })\n    }\n\n    const draw = () => {\n      if (!model) return\n      pose()\n      render()\n    }\n\n    // The hand stirs the fog round it as it moves, then the fog is stepped. Returns true once it is calm.\n    const stir = (dt: number) => {\n      const s = settingsRef.current\n      const { hand, last } = onScreen\n      if (s.fog <= 0 || !hand.seen) {\n        last.seen = false\n        return true\n      }\n      if (last.seen && s.swirl > 0) {\n        const vx = (hand.x - last.x) / dt\n        const vy = (hand.y - last.y) / dt\n        const inside = hand.x > -hand.r && hand.x < 1 + hand.r && hand.y > -hand.r && hand.y < 1 + hand.r\n        if (inside && Math.abs(vx) + Math.abs(vy) > 1e-3) stirFog(fog, hand.x, hand.y, hand.r, vx, vy, s.swirl * Math.min(1, 20 * dt))\n      }\n      last.x = hand.x\n      last.y = hand.y\n      last.seen = true\n      if (fog.calm) return true\n      const calm = stepFog(fog, dt)\n      packFog(fog, fogTexels)\n      fogTexture.needsUpdate = true\n      return calm\n    }\n\n    const frame = (now: number) => {\n      raf = 0\n      const s = settingsRef.current\n      const dt = last ? clamp((now - last) / 1000, 1 / 240, 0.05) : 1 / 60\n      last = now\n      const k = followStep(s.smoothing, dt)\n      aim.x += (aim.tx - aim.x) * k\n      aim.y += (aim.ty - aim.y) * k\n      aim.weight += (aim.tw - aim.weight) * k\n      // an eased value crosses a tiny epsilon late: snap it, so the loop ends when the motion visibly has\n      const settled = Math.abs(aim.tx - aim.x) + Math.abs(aim.ty - aim.y) + Math.abs(aim.tw - aim.weight) < 2e-4\n      if (settled) {\n        aim.x = aim.tx\n        aim.y = aim.ty\n        aim.weight = aim.tw\n      }\n      const drifting = dreaming()\n      if (drifting) time += dt * s.drift\n      let calm = true\n      if (model) {\n        pose()\n        calm = stir(dt)\n        render()\n      }\n      // the loop runs while the pose catches up, the fog still moves or the dream drifts, never off screen\n      if (visible && (!settled || !calm || drifting)) raf = requestAnimationFrame(frame)\n      else last = 0\n    }\n\n    // Nothing is scheduled before the model is in, while the box is off screen or while the tab is hidden.\n    const wake = () => {\n      if (!raf && model && visible && !document.hidden) raf = requestAnimationFrame(frame)\n    }\n\n    const resize = () => {\n      const s = settingsRef.current\n      const width = root.clientWidth\n      const height = root.clientHeight\n      // The device pixel ratio, capped by `dpr`, by 2 and by the fragment budget.\n      renderer.dpr = Math.min(window.devicePixelRatio || 1, s.dpr > 0 ? s.dpr : 2, 2, Math.sqrt(PIXEL_BUDGET / Math.max(1, width * height)))\n      renderer.setSize(Math.max(1, width), Math.max(1, height))\n      canvas.style.width = \"\"\n      canvas.style.height = \"\"\n      sceneTarget.setSize(canvas.width, canvas.height)\n      frameCamera()\n      // a resized canvas is blank, so it is drawn again at once rather than on the next frame\n      draw()\n    }\n\n    const dispose = () => {\n      if (!model) return\n      for (const mesh of model.meshes) mesh.geometry.remove()\n      for (const part of model.parts) part.program.remove()\n      for (const mesh of model.meshes) if (\"boneTexture\" in mesh) gl.deleteTexture((mesh as unknown as { boneTexture: { texture: WebGLTexture } }).boneTexture.texture)\n      scene.children.slice().forEach((child) => scene.removeChild(child))\n      model = null\n    }\n\n    const load = () => {\n      const s = settingsRef.current\n      if (!s.src || s.src === loaded) return\n      loaded = s.src\n      const ticket = ++generation\n      GLTFLoader.load(gl, s.src)\n        .then((gltf) => {\n          if (ticket !== generation) return\n          dispose()\n          const parts: Part[] = []\n          const meshes: Mesh[] = []\n          const originals = new Set<Program>()\n          const byMaterial = new Map<string, Part>()\n          for (const node of gltf.scene) node.setParent(scene)\n          scene.traverse((node) => {\n            const mesh = node as Mesh & { program: Program & { gltfMaterial?: GLTFMaterial } }\n            if (!mesh.geometry) return\n            const skinned = \"skeleton\" in mesh\n            const material = mesh.program.gltfMaterial\n            originals.add(mesh.program)\n            const key = `${material?.name ?? \"default\"}|${skinned}`\n            let part = byMaterial.get(key)\n            if (!part) {\n              part = makePart(gl, material, skinned)\n              byMaterial.set(key, part)\n              parts.push(part)\n            }\n            mesh.program = part.program\n            // the bones move the skinned mesh past the bounds it was saved with\n            mesh.frustumCulled = false\n            meshes.push(mesh)\n          })\n          // the loader's own programs are replaced: one program per material, shared by the meshes that wear it\n          for (const program of originals) program.remove()\n\n          const named = (name: string) => {\n            let found: Transform | null = null\n            scene.traverse((node) => {\n              if (!found && (node as Transform & { name?: string }).name === name) found = node\n            })\n            return found as Transform | null\n          }\n          const bounds = measure(scene)\n          const arm = named(NODES.arm)\n          const skin = meshes.find((mesh) => \"skeleton\" in mesh)\n          // the arm turns its hand, not its bone, toward the pointer: the line from the shoulder to the hand's middle\n          let reach: { axis: Vec3; length: number; radius: number; wrist: number; front: number; uniforms: Program[\"uniforms\"] } | null = null\n          if (arm?.parent && skin) {\n            const shoulder = new Vec3().copy(arm.position).applyMatrix4(arm.parent.worldMatrix)\n            const shape = armShape(skin, arm, shoulder)\n            if (shape) {\n              // the stretch works in the mesh's own space, before the bones move it\n              const uniforms = skin.program.uniforms\n              uniforms.uShoulder.value = [shoulder[0], shoulder[1], shoulder[2]]\n              uniforms.uAxis.value = [shape.axis[0], shape.axis[1], shape.axis[2]]\n              uniforms.uWrist.value = shape.wrist\n              uniforms.uArmJoint.value = shape.index\n              // the pose turns the arm in its parent's space\n              const toParent = new Mat4().inverse(arm.parent.worldMatrix)\n              const axis = shape.axis.clone().transformDirection(toParent)\n              const front = new Vec3(shoulder[0], shoulder[1], shape.front).applyMatrix4(toParent)[2]\n              reach = { axis, length: shape.length, radius: shape.radius, wrist: shape.wrist, front, uniforms }\n            }\n          }\n          const ringed: Program[] = []\n          const pupils = NODES.pupils.flatMap((name) => {\n            const node = named(name)\n            const mesh = node?.children.find((child) => (child as Mesh).geometry) as Mesh | undefined\n            const data = mesh?.geometry.attributes.position?.data\n            if (!node || !mesh || !data) return []\n            // the pupil looks out through its own middle, from the eye's centre\n            const middle = new Vec3()\n            for (let i = 0; i < data.length; i += 3) middle.add(new Vec3(data[i], data[i + 1], data[i + 2]))\n            middle.normalize()\n            // its rim: the widest angle any of its points makes with its middle; the rings fit inside it\n            let rim = 1e-3\n            const point = new Vec3()\n            for (let i = 0; i < data.length; i += 3) rim = Math.max(rim, point.set(data[i], data[i + 1], data[i + 2]).normalize().angle(middle))\n            const axis = [middle[0], middle[1], middle[2]]\n            const scale = PUPIL_RINGS / rim\n            // the two pupils share a program, so each sets its own middle as it is drawn\n            mesh.onBeforeRender(() => {\n              mesh.program.uniforms.uRingAxis.value = axis\n              mesh.program.uniforms.uRingScale.value = scale\n            })\n            if (!ringed.includes(mesh.program)) ringed.push(mesh.program)\n            const look = middle.clone().applyQuaternion(node.quaternion).normalize()\n            return [{ node, rest: new Quat().copy(node.quaternion), look }]\n          })\n          model = {\n            parts,\n            meshes,\n            bounds,\n            body: named(NODES.body),\n            arm: arm && reach ? { node: arm, rest: new Quat().copy(arm.quaternion), ...reach } : null,\n            pupils,\n            ringed,\n          }\n          applyLook()\n          resize()\n          if (dreaming()) wake()\n          canvas.style.opacity = \"1\"\n          settingsRef.current.onLoad?.()\n        })\n        .catch((error: unknown) => {\n          if (ticket !== generation) return\n          settingsRef.current.onError?.(error instanceof Error ? error : new Error(String(error)))\n        })\n    }\n\n    const rest = () => {\n      if (aim.tw === 0) return\n      aim.tw = 0\n      wake()\n    }\n\n    const onPointerMove = (event: PointerEvent) => {\n      if (!visible || !settingsRef.current.track) return\n      const rect = root.getBoundingClientRect()\n      if (!rect.width || !rect.height) return\n      // anywhere on the page; past the box, the hand waits at its edge\n      aim.tx = clamp(((event.clientX - rect.left) / rect.width) * 2 - 1, -1, 1)\n      aim.ty = clamp(1 - ((event.clientY - rect.top) / rect.height) * 2, -1, 1)\n      aim.tw = 1\n      wake()\n    }\n\n    // The pointer left the window, or a finger or pen lifted.\n    const onPointerOut = (event: PointerEvent) => {\n      if (!event.relatedTarget) rest()\n    }\n\n    const onVisibility = () => {\n      last = 0\n      wake()\n    }\n\n    window.addEventListener(\"pointermove\", onPointerMove, { passive: true })\n    window.addEventListener(\"pointerdown\", onPointerMove, { passive: true })\n    window.addEventListener(\"pointerout\", onPointerOut, { passive: true })\n    document.addEventListener(\"visibilitychange\", onVisibility)\n    const resizeObserver = new ResizeObserver(resize)\n    resizeObserver.observe(root)\n    // against the window, so the loop also stops when a scrolling parent carries the box off the page\n    const intersection = new IntersectionObserver((entries) => {\n      visible = entries.some((entry) => entry.isIntersecting)\n      if (visible) {\n        last = 0\n        wake()\n      }\n    })\n    intersection.observe(root)\n    load()\n    wakeRef.current = () => {\n      const s = settingsRef.current\n      load()\n      if (!s.track) rest()\n      applyLook()\n      frameCamera()\n      draw()\n      // a dream set drifting starts its clock\n      if (dreaming()) wake()\n    }\n\n    // Everything is released, then the context, then the element.\n    return () => {\n      cancelAnimationFrame(raf)\n      // a model still loading is ignored when it arrives\n      generation++\n      wakeRef.current = null\n      resizeObserver.disconnect()\n      intersection.disconnect()\n      window.removeEventListener(\"pointermove\", onPointerMove)\n      window.removeEventListener(\"pointerdown\", onPointerMove)\n      window.removeEventListener(\"pointerout\", onPointerOut)\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      dispose()\n      composeGeometry.remove()\n      composeProgram.remove()\n      gl.deleteTexture(fogTexture.texture)\n      gl.deleteTexture(sceneTarget.texture.texture)\n      gl.deleteFramebuffer(sceneTarget.buffer)\n      if (sceneTarget.depthStencilBuffer) gl.deleteRenderbuffer(sceneTarget.depthStencilBuffer)\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n      canvas.remove()\n    }\n  }, [])\n\n  // Props reach the loop through a ref written here, never in render, and a change draws one frame.\n  React.useEffect(() => {\n    settingsRef.current = settings\n    wakeRef.current?.()\n  })\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"dream-cat\"\n      role={alt ? \"img\" : undefined}\n      aria-label={alt}\n      className={cn(\"relative h-full w-full touch-pan-y overflow-hidden\", className)}\n      {...props}\n    >\n      {children ? <div className=\"relative z-1 h-full\">{children}</div> : null}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-28",
    "downloads": [
      "models/mewo.glb"
    ]
  },
  "categories": [
    "background"
  ],
  "type": "registry:ui"
}