{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"context-window","type":"registry:block","title":"Context window","description":"A living WebGL2 AI context budget: a real-time plush, clay or jelly creature physically inflates as tokens mount, presses flat against the glass past 90%, and squeezes down when compacted.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/status-button.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/context-window.tsx","type":"registry:component","content":"// Hairline UI · context-window · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { StatusButton, type ActionStatus } from \"./status-button\";\nimport { TextMorph } from \"./text-morph\";\nimport {\n  TactileCreatureEngine,\n  type ContextMaterial,\n  type ContextTone,\n  type CreatureMood,\n} from \"./tactile-creature-gl\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n} from \"./ui-interaction-motion\";\n\nexport type { ContextMaterial, ContextTone };\n\n/* ─────────────────────────────────────────────────────────\n * CONTEXT WINDOW: Munch, the living AI memory budget\n *\n *   light      small and nimble inside the glass alcove; eyes\n *              track the pointer and open wide to gulp new files\n *   heavy      75%+ — cheeks puff, brows knit, bar turns amber\n *   stuffed    90%+ — body swells until it presses flat against\n *              the alcove walls and puffs steam\n *   overflow   adding past the limit bounces off its belly\n *   hover ×    hovering a file's remove button makes it glance\n *              down hopefully and ease slightly\n *   compact    squeezes tight inward while pending, then pops\n *              free in a puff of relief as tokens roll back down\n *\n * Interactive directly on the stage too: pet to sweep plush fur,\n * click clay to leave healing thumbprint dents, drag and fling\n * jelly to watch its suspended inner eyes lag behind.\n * ───────────────────────────────────────────────────────── */\n\nexport interface ContextItem {\n  id: string;\n  label: string;\n  tokens: number;\n  /** Optional category tag (e.g. \"system\", \"file\", \"tool\", \"chat\"). */\n  kind?: string;\n  /** Pinned items stay through compaction and cannot be removed. */\n  pinned?: boolean;\n  /** Any CSS colour; defaults to --chart-1…5. */\n  color?: string;\n}\n\nexport interface ContextWindowProps {\n  /** Items currently held in the model's context window. */\n  items?: ContextItem[];\n  /** Model context limit in tokens (e.g. 200_000). */\n  limit: number;\n  /** Real-time WebGL2 surface for the creature. */\n  material?: ContextMaterial;\n  /** Colour tone (\"primary\" reads shadcn --primary). */\n  tone?: ContextTone;\n  /** Compact / summarise old context; update `items` once resolved. */\n  onCompact?: () => Promise<unknown>;\n  compactLabel?: string;\n  /** Drop one item from context. */\n  onRemove?: (id: string) => void | Promise<unknown>;\n  /** Quick-attach items shown below the list so users can feed context directly. */\n  suggestions?: Omit<ContextItem, \"pinned\">[];\n  /** Attach an item (or dropped file). Return `false` to play the belly-bounce rejection. */\n  onAdd?: (item: Omit<ContextItem, \"pinned\">) => boolean | void | Promise<boolean | void>;\n  /** Optional model badge in the header (e.g. \"200k window\" or \"Claude 4.5\"). */\n  model?: string;\n  /** Creature's name in status copy. */\n  name?: string;\n  className?: string;\n}\n\nconst EMPTY_ITEMS: ContextItem[] = [];\nconst EMPTY_SUGGESTIONS: Omit<ContextItem, \"pinned\">[] = [];\n\nconst mix = (color: string, amount: number, into = \"transparent\") =>\n  `color-mix(in oklab, ${color} ${amount}%, ${into})`;\nconst PF = \"var(--primary-foreground)\";\n\nconst CARD: React.CSSProperties = {\n  backgroundImage: `linear-gradient(180deg, var(--card), ${mix(\"var(--card)\", 96, \"var(--foreground)\")})`,\n  boxShadow: `0 0 0 1px var(--border), inset 0 1px 0 ${mix(\"var(--background)\", 85)}`,\n};\n\nconst LIT: React.CSSProperties = {\n  backgroundImage: `linear-gradient(180deg, ${mix(PF, 16)}, transparent 60%)`,\n  boxShadow: `inset 0 1px 0 ${mix(PF, 32)}, inset 0 0 0 1px ${mix(\"black\", 10)}`,\n};\n\nconst CHART = [\n  \"var(--chart-1, var(--primary))\",\n  \"var(--chart-2, #10b981)\",\n  \"var(--chart-3, #f59e0b)\",\n  \"var(--chart-4, #8b5cf6)\",\n  \"var(--chart-5, #ef4444)\",\n];\n\nfunction formatTokens(n: number) {\n  const v = Math.max(0, n);\n  if (v >= 1_000_000) return { value: v / 1_000_000, unit: \"M\", digits: 1 };\n  if (v >= 1_000) return { value: v / 1_000, unit: \"k\", digits: v < 10_000 ? 1 : 0 };\n  return { value: v, unit: \"\", digits: 0 };\n}\n\nfunction TokenFigure({ n }: { n: number }) {\n  const f = formatTokens(n);\n  return (\n    <span className=\"whitespace-nowrap tabular-nums\">\n      <NumberRoll value={f.value} format={{ maximumFractionDigits: f.digits, minimumFractionDigits: f.digits }} />\n      {f.unit}\n    </span>\n  );\n}\n\nfunction formatPlainTokens(n: number) {\n  const f = formatTokens(n);\n  return `${f.value.toFixed(f.digits)}${f.unit}`;\n}\n\nexport function ContextWindow({\n  items = EMPTY_ITEMS,\n  limit,\n  material = \"plush\",\n  tone = \"coral\",\n  onCompact,\n  compactLabel = \"Compact memory\",\n  onRemove,\n  suggestions = EMPTY_SUGGESTIONS,\n  onAdd,\n  model,\n  name = \"Munch\",\n  className = \"\",\n}: ContextWindowProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: activityRef, active } = useInteractionActivity<HTMLElement>();\n  const baseId = React.useId();\n\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const engineRef = React.useRef<TactileCreatureEngine | null>(null);\n  const timerRef = React.useRef<number | null>(null);\n\n  const [compactStatus, setCompactStatus] = React.useState<ActionStatus>(\"idle\");\n  const [hoverRemoveId, setHoverRemoveId] = React.useState<string | null>(null);\n  const [hoverCompact, setHoverCompact] = React.useState(false);\n  const [dragOver, setDragOver] = React.useState(false);\n  const [flash, setFlash] = React.useState<\"none\" | \"rejected\" | \"annoyed\" | \"relieved\" | \"gulped\">(\"none\");\n\n  const used = React.useMemo(() => items.reduce((sum, it) => sum + Math.max(0, it.tokens), 0), [items]);\n  const ratio = limit > 0 ? used / limit : 1;\n  const pct = Math.min(100, Math.round(ratio * 100));\n  const heavy = ratio >= 0.75;\n  const stuffed = ratio >= 0.9;\n  const compactableTokens = React.useMemo(\n    () => items.filter((it) => !it.pinned).reduce((sum, it) => sum + Math.max(0, it.tokens), 0),\n    [items],\n  );\n\n  const mood: CreatureMood =\n    compactStatus === \"pending\"\n      ? \"compacting\"\n      : flash === \"rejected\" || flash === \"annoyed\"\n        ? \"rejected\"\n        : flash === \"relieved\" || compactStatus === \"success\"\n          ? \"relieved\"\n          : flash === \"gulped\"\n            ? \"gulp\"\n            : stuffed\n              ? \"stuffed\"\n              : heavy\n                ? \"heavy\"\n                : \"idle\";\n\n  const triggerFlash = React.useCallback((kind: \"rejected\" | \"annoyed\" | \"relieved\" | \"gulped\", ms: number) => {\n    setFlash(kind);\n    if (timerRef.current !== null) window.clearTimeout(timerRef.current);\n    timerRef.current = window.setTimeout(() => {\n      setFlash(\"none\");\n      timerRef.current = null;\n    }, ms);\n  }, []);\n\n  React.useEffect(() => {\n    return () => {\n      if (timerRef.current !== null) window.clearTimeout(timerRef.current);\n    };\n  }, []);\n\n  // Mount WebGL2 creature once; update props imperatively without tearing down context\n  React.useEffect(() => {\n    const el = stageRef.current;\n    if (!el) return;\n    const engine = new TactileCreatureEngine(el, {\n      material,\n      tone,\n      fullness: Math.min(1.12, ratio),\n      mood,\n      reduced,\n      onPokeAnnoyed: () => triggerFlash(\"annoyed\", 2400),\n    });\n    engineRef.current = engine;\n    return () => {\n      engine.dispose();\n      engineRef.current = null;\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  React.useEffect(() => {\n    engineRef.current?.setProps({\n      material,\n      tone,\n      fullness: Math.min(1.12, ratio),\n      mood,\n      hoverRelief: Boolean(hoverRemoveId) || (hoverCompact && heavy),\n      reduced,\n    });\n  }, [material, tone, ratio, mood, hoverRemoveId, hoverCompact, heavy, reduced]);\n\n  React.useEffect(() => {\n    engineRef.current?.setActive(active);\n  }, [active]);\n\n  const handleAdd = async (candidate: Omit<ContextItem, \"pinned\">) => {\n    if (!onAdd) return;\n    if (used + candidate.tokens > limit) {\n      engineRef.current?.triggerReject();\n      triggerFlash(\"rejected\", 2100);\n      return;\n    }\n    const ok = await onAdd(candidate);\n    if (ok === false) {\n      engineRef.current?.triggerReject();\n      triggerFlash(\"rejected\", 2100);\n      return;\n    }\n    engineRef.current?.triggerGulp(candidate.tokens / Math.max(1, limit));\n    triggerFlash(\"gulped\", 700);\n  };\n\n  const handleRemove = async (id: string) => {\n    if (!onRemove) return;\n    setHoverRemoveId(null);\n    await onRemove(id);\n    engineRef.current?.triggerRelief();\n    triggerFlash(\"relieved\", 1200);\n  };\n\n  const handleCompact = async () => {\n    if (!onCompact || compactStatus === \"pending\") return;\n    setHoverCompact(false);\n    setCompactStatus(\"pending\");\n    try {\n      await onCompact();\n      setCompactStatus(\"success\");\n      triggerFlash(\"relieved\", 1800);\n      window.setTimeout(() => setCompactStatus(\"idle\"), 1700);\n    } catch {\n      setCompactStatus(\"error\");\n      engineRef.current?.triggerReject();\n    }\n  };\n\n  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {\n    e.preventDefault();\n    setDragOver(false);\n    if (!onAdd) return;\n    const file = e.dataTransfer.files?.[0];\n    if (!file) return;\n    const estTokens = Math.max(4_000, Math.min(Math.round(limit * 0.45), Math.round(file.size / 4)));\n    void handleAdd({\n      id: `drop-${file.name}-${file.size}`,\n      label: file.name,\n      tokens: estTokens,\n      kind: \"file\",\n    });\n  };\n\n  const statusLine =\n    compactStatus === \"pending\"\n      ? \"Squeezing old turns…\"\n      : flash === \"rejected\"\n        ? \"Too full — compact first\"\n        : flash === \"annoyed\"\n          ? `Hey, ${name} is full enough`\n          : flash === \"relieved\" || compactStatus === \"success\"\n            ? \"Phew. Light again\"\n            : hoverRemoveId\n              ? \"Drop that to free room\"\n              : dragOver\n                ? \"Drop to feed context\"\n                : stuffed\n                  ? \"Pressed against the glass\"\n                  : heavy\n                    ? \"Getting heavy · recall dips\"\n                    : ratio >= 0.45\n                      ? \"Comfortable headroom\"\n                      : \"Plenty of room\";\n\n  const stageStyle: React.CSSProperties = {\n    backgroundColor: mix(\"var(--foreground)\", 4, \"var(--card)\"),\n    backgroundImage: [\n      `radial-gradient(68% 72% at 50% 18%, ${mix(\"var(--background)\", 88)} 0%, transparent 74%)`,\n      stuffed || flash === \"rejected\"\n        ? `radial-gradient(80% 45% at 50% 0%, ${mix(\"#ef4444\", 12)} 0%, transparent 70%)`\n        : heavy\n          ? `radial-gradient(80% 45% at 50% 0%, ${mix(\"#f59e0b\", 10)} 0%, transparent 70%)`\n          : \"none\",\n    ]\n      .filter((layer) => layer !== \"none\")\n      .join(\", \"),\n    boxShadow: dragOver\n      ? `inset 0 0 0 1.5px var(--primary)`\n      : `inset 0 0 0 1px ${mix(\"var(--border)\", 100)}, inset 0 1px 0 ${mix(\"var(--background)\", 70)}`,\n  };\n\n  const availableSuggestions = suggestions.filter((s) => !items.some((it) => it.id === s.id));\n\n  return (\n    <section\n      ref={activityRef}\n      aria-labelledby={`${baseId}-title`}\n      className={`relative w-full max-w-[416px] rounded-[28px] p-2 text-card-foreground ${className}`}\n      style={CARD}\n    >\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 416px)\" }} />\n      <div className=\"@container w-full\">\n        {/* Lit glass alcove: the creature physically inflates and presses flat against its walls */}\n        <div\n          className=\"relative overflow-clip rounded-[22px] select-none transition-[box-shadow] duration-200\"\n          style={stageStyle}\n          onDragOver={(e) => {\n            if (!onAdd) return;\n            e.preventDefault();\n            setDragOver(true);\n          }}\n          onDragLeave={() => setDragOver(false)}\n          onDrop={handleDrop}\n        >\n          <div\n            ref={stageRef}\n            aria-hidden=\"true\"\n            className=\"relative w-full cursor-grab touch-none active:cursor-grabbing\"\n            style={{ aspectRatio: \"16 / 9.4\" }}\n          />\n          <p className=\"pointer-events-none absolute left-3.5 top-3 z-10 text-[12.5px] font-medium tracking-[-0.01em] text-muted-foreground\">\n            <TextMorph>{statusLine}</TextMorph>\n          </p>\n          <span\n            aria-hidden=\"true\"\n            className={`pointer-events-none absolute right-3.5 top-3 z-10 font-mono text-[12px] font-medium tabular-nums ${\n              stuffed || flash === \"rejected\"\n                ? \"text-red-600 dark:text-red-400\"\n                : heavy\n                  ? \"text-amber-700 dark:text-amber-400\"\n                  : \"text-muted-foreground\"\n            }`}\n          >\n            <NumberRoll value={pct} />%\n          </span>\n        </div>\n\n        {/* Polite announcement outside buttons for screen readers */}\n        <p className=\"sr-only\" aria-live=\"polite\">\n          {statusLine}. {formatPlainTokens(used)} of {formatPlainTokens(limit)} tokens used.\n        </p>\n\n        {/* Header & rolling token count */}\n        <div className=\"px-2.5 pt-3\">\n          <div className=\"flex items-baseline justify-between gap-2\">\n            <div className=\"flex min-w-0 items-baseline gap-2\">\n              <h2 id={`${baseId}-title`} className=\"truncate text-[15px] font-medium tracking-[-0.01em] text-foreground\">\n                Context window\n              </h2>\n              {model && <span className=\"hidden truncate text-[12px] text-muted-foreground @[21rem]:inline\">{model}</span>}\n            </div>\n            <p\n              className={`shrink-0 text-[12.5px] ${\n                stuffed\n                  ? \"text-red-600 dark:text-red-400\"\n                  : heavy\n                    ? \"text-amber-700 dark:text-amber-400\"\n                    : \"text-muted-foreground\"\n              }`}\n            >\n              <span className=\"font-medium text-foreground\">\n                <TokenFigure n={used} />\n              </span>{\" \"}\n              / <TokenFigure n={limit} />\n            </p>\n          </div>\n\n          {/* Segmented hairline meter */}\n          <div\n            className=\"mt-2.5 flex h-2.5 w-full gap-[2px] overflow-clip rounded-full\"\n            role=\"meter\"\n            aria-label=\"Context window tokens\"\n            aria-valuemin={0}\n            aria-valuemax={limit}\n            aria-valuenow={Math.min(used, limit)}\n            aria-valuetext={`${formatPlainTokens(used)} of ${formatPlainTokens(limit)} tokens used (${pct}%)`}\n            style={{ background: mix(\"var(--foreground)\", 7) }}\n          >\n            {items.map((it, idx) => {\n              const segPct = (Math.max(0, it.tokens) / Math.max(1, limit)) * 100;\n              return (\n                <span\n                  key={it.id}\n                  className=\"h-full shrink-0 first:rounded-l-full last:rounded-r-full\"\n                  style={{\n                    width: `${Math.min(100, segPct)}%`,\n                    background: it.color ?? CHART[idx % CHART.length],\n                    opacity: hoverRemoveId === it.id ? 0.45 : 1,\n                    transition: reduced ? \"none\" : `width 680ms ${EASE_OUT}, opacity 180ms ease`,\n                  }}\n                />\n              );\n            })}\n          </div>\n\n          {/* Attached context rows */}\n          {items.length > 0 && (\n            <ul className=\"mt-3 divide-y divide-border/70 border-t border-border/70\">\n              {items.map((it, idx) => (\n                <li\n                  key={it.id}\n                  className=\"flex items-center justify-between gap-2 py-2 text-[13px] transition-colors\"\n                >\n                  <div className=\"flex min-w-0 items-center gap-2\">\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"size-2 shrink-0 rounded-full\"\n                      style={{ background: it.color ?? CHART[idx % CHART.length] }}\n                    />\n                    <span className=\"truncate font-medium text-foreground\">{it.label}</span>\n                    {it.kind && (\n                      <span className=\"hidden shrink-0 text-[11.5px] text-muted-foreground @[20rem]:inline\">\n                        {it.kind}\n                      </span>\n                    )}\n                  </div>\n                  <div className=\"flex shrink-0 items-center gap-1.5\">\n                    <span className=\"font-mono text-[12px] text-muted-foreground tabular-nums\">\n                      <TokenFigure n={it.tokens} />\n                    </span>\n                    {it.pinned ? (\n                      <span className=\"px-1.5 py-0.5 text-[11px] text-muted-foreground\">Pinned</span>\n                    ) : onRemove ? (\n                      <button\n                        type=\"button\"\n                        aria-label={`Remove ${it.label} (${formatPlainTokens(it.tokens)} tokens)`}\n                        onMouseEnter={() => setHoverRemoveId(it.id)}\n                        onMouseLeave={() => setHoverRemoveId((cur) => (cur === it.id ? null : cur))}\n                        onFocus={() => setHoverRemoveId(it.id)}\n                        onBlur={() => setHoverRemoveId((cur) => (cur === it.id ? null : cur))}\n                        onClick={() => void handleRemove(it.id)}\n                        className={`flex size-6 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                      >\n                        <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" aria-hidden=\"true\">\n                          <path d=\"M3 3l6 6M9 3l-6 6\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n                        </svg>\n                      </button>\n                    ) : null}\n                  </div>\n                </li>\n              ))}\n            </ul>\n          )}\n\n          {/* Quick-feed context pills (click to feed the creature!) */}\n          {onAdd && availableSuggestions.length > 0 && (\n            <div className=\"mt-2.5 flex flex-wrap gap-1.5 border-t border-border/70 pt-2.5\">\n              {availableSuggestions.map((s) => {\n                const wouldOverflow = used + s.tokens > limit;\n                return (\n                  <button\n                    key={s.id}\n                    type=\"button\"\n                    onClick={() => void handleAdd(s)}\n                    className={`inline-flex cursor-pointer items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-[12px] font-medium text-foreground hover:bg-muted ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                    title={wouldOverflow ? \"Exceeds context limit\" : `Attach ${s.label}`}\n                  >\n                    <span aria-hidden=\"true\" className=\"text-muted-foreground\">+</span>\n                    <span className=\"max-w-[130px] truncate\">{s.label}</span>\n                    <span className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">\n                      {formatPlainTokens(s.tokens)}\n                    </span>\n                  </button>\n                );\n              })}\n            </div>\n          )}\n        </div>\n\n        {/* Footer Compact action */}\n        {onCompact && (\n          <div className=\"px-2 pb-1 pt-3\">\n            <div\n              onMouseEnter={() => setHoverCompact(true)}\n              onMouseLeave={() => setHoverCompact(false)}\n            >\n              <StatusButton\n                variant={heavy ? \"primary\" : \"outline\"}\n                status={compactStatus}\n                disabled={compactableTokens === 0 && compactStatus === \"idle\"}\n                labels={{\n                  idle: compactableTokens > 0 ? compactLabel : \"Already compact\",\n                  pending: \"Compacting\",\n                  success: \"Compacted\",\n                  error: \"Try again\",\n                }}\n                onClick={() => void handleCompact()}\n                className=\"h-10 w-full text-[13.5px]\"\n                style={heavy && compactStatus !== \"error\" ? LIT : undefined}\n              />\n            </div>\n          </div>\n        )}\n      </div>\n    </section>\n  );\n}\n\nexport default ContextWindow;\n"},{"path":"registry/tactile-creature-gl.ts","type":"registry:component","content":"// Hairline UI · context-window · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * TACTILE CREATURE GL: zero-dependency WebGL2 SDF engine\n *\n * Renders one living creature in three tactile materials:\n *   plush  volumetric multi-shell fur that sweeps when petted\n *          and flattens smoothly against glass walls\n *   clay   velvety matte plasticine with optional 12fps boil\n *          and healing thumbprint craters where poked\n *   jelly  refracted gummy body with floating micro-bubbles,\n *          lagging spring-suspended eyes and floor caustics\n *\n * The SDF inflates continuously with `fullness` (0..1.15) and\n * presses smoothly against the stage's physical walls past ~75%,\n * gulps when fed, squeezes inward during compaction, bounces\n * on overflow, and sleeps when off-screen or reduced-motion.\n * ───────────────────────────────────────────────────────── */\n\nexport type ContextMaterial = \"plush\" | \"clay\" | \"jelly\";\nexport type ContextTone = \"coral\" | \"lilac\" | \"peach\" | \"mint\" | \"sky\" | \"butter\" | \"primary\";\nexport type CreatureMood = \"idle\" | \"gulp\" | \"heavy\" | \"stuffed\" | \"compacting\" | \"relieved\" | \"rejected\";\n\ntype Rgb = [number, number, number];\n\nconst TONE_PALETTES: Record<Exclude<ContextTone, \"primary\">, { base: Rgb; accent: Rgb }> = {\n  coral:  { base: [0.95, 0.43, 0.48], accent: [1.0, 0.78, 0.80] },\n  lilac:  { base: [0.68, 0.49, 0.96], accent: [0.91, 0.84, 1.0] },\n  peach:  { base: [0.97, 0.57, 0.41], accent: [1.0, 0.84, 0.74] },\n  mint:   { base: [0.28, 0.80, 0.70], accent: [0.76, 0.97, 0.92] },\n  sky:    { base: [0.39, 0.72, 0.98], accent: [0.80, 0.92, 1.0] },\n  butter: { base: [0.98, 0.80, 0.28], accent: [1.0, 0.95, 0.72] },\n};\n\nconst MATERIAL_ID: Record<ContextMaterial, number> = { plush: 0, clay: 1, jelly: 2 };\nconst MOOD_ID: Record<CreatureMood, number> = {\n  idle: 0,\n  gulp: 1,\n  heavy: 2,\n  stuffed: 3,\n  compacting: 4,\n  relieved: 5,\n  rejected: 6,\n};\n\nconst VERT_SRC = `#version 300 es\nprecision highp float;\nvoid main() {\n  vec2 pos = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);\n  gl_Position = vec4(pos * 2.0 - 1.0, 0.0, 1.0);\n}\n`;\n\nconst FRAG_SRC = `#version 300 es\nprecision highp float;\n\nout vec4 fragColor;\n\nuniform vec2  uResolution;\nuniform float uTime;\nuniform int   uMaterial;      // 0 = plush, 1 = clay, 2 = jelly\nuniform int   uMood;          // 0=idle, 1=gulp, 2=heavy, 3=stuffed, 4=compacting, 5=relieved, 6=rejected\nuniform vec3  uBaseColor;\nuniform vec3  uAccentColor;\nuniform float uDarkBg;\nuniform float uClayStep;\n\n// Context-window driven continuous state\nuniform float uFullness;      // 0.0 .. 1.15 continuous context fullness\nuniform float uCompactSq;     // 0.0 .. 1.0 compaction squeeze inward\nuniform float uGulpOpen;      // 0.0 .. 1.0 mouth open gulp impulse\nuniform float uHoverRelief;   // 0.0 .. 1.0 eyeing remove/compact with hope\n\n// Direct tactile physics\nuniform vec2  uLook;\nuniform float uTilt;\nuniform float uJumpY;\nuniform float uSquash;\nuniform vec2  uStretch;\nuniform float uWobbleAmp;\nuniform float uWobblePhase;\nuniform float uBlink;\nuniform float uPetHappy;\nuniform vec2  uPetPos;\nuniform vec2  uPetDir;\nuniform float uPetStrength;\nuniform float uInnerOffsetX;\nuniform float uInnerOffsetY;\nuniform vec4  uDents[4];\n\nconst float FUR_LEN = 0.125;\n\nfloat hash13(vec3 p) {\n  p = fract(p * 0.1031);\n  p += dot(p, p.zyx + 31.32);\n  return fract((p.x + p.y) * p.z);\n}\n\nvec3 hash33(vec3 p) {\n  p = fract(p * vec3(0.1031, 0.1030, 0.0973));\n  p += dot(p, p.yxz + 33.33);\n  return fract((p.xxy + p.yxx) * p.zyx);\n}\n\nfloat noise3(vec3 p) {\n  vec3 i = floor(p);\n  vec3 f = fract(p);\n  f = f * f * (3.0 - 2.0 * f);\n  float n000 = hash13(i + vec3(0.0, 0.0, 0.0));\n  float n100 = hash13(i + vec3(1.0, 0.0, 0.0));\n  float n010 = hash13(i + vec3(0.0, 1.0, 0.0));\n  float n110 = hash13(i + vec3(1.0, 1.0, 0.0));\n  float n001 = hash13(i + vec3(0.0, 0.0, 1.0));\n  float n101 = hash13(i + vec3(1.0, 0.0, 1.0));\n  float n011 = hash13(i + vec3(0.0, 1.0, 1.0));\n  float n111 = hash13(i + vec3(1.0, 1.0, 1.0));\n  float nx00 = mix(n000, n100, f.x);\n  float nx10 = mix(n010, n110, f.x);\n  float nx01 = mix(n001, n101, f.x);\n  float nx11 = mix(n011, n111, f.x);\n  return mix(mix(nx00, nx10, f.y), mix(nx01, nx11, f.y), f.z);\n}\n\nfloat furStrands(vec3 p) {\n  vec3 i = floor(p);\n  vec3 f = fract(p);\n  float minD = 1.0;\n  for (int z = 0; z <= 1; z++) {\n    for (int y = 0; y <= 1; y++) {\n      for (int x = 0; x <= 1; x++) {\n        vec3 g = vec3(float(x), float(y), float(z));\n        vec3 o = hash33(i + g);\n        vec3 r = g + o * 0.84 - f;\n        minD = min(minD, dot(r, r));\n      }\n    }\n  }\n  return clamp(1.0 - sqrt(minD) * 1.15, 0.0, 1.0);\n}\n\nmat2 rot2(float a) {\n  float c = cos(a), s = sin(a);\n  return mat2(c, -s, s, c);\n}\n\nfloat smin(float a, float b, float k) {\n  float h = max(k - abs(a - b), 0.0) / k;\n  return min(a, b) - h * h * h * k * (1.0 / 6.0);\n}\n\nfloat smax(float a, float b, float k) {\n  return -smin(-a, -b, k);\n}\n\nfloat sdEllipsoid(vec3 p, vec3 r) {\n  float k0 = length(p / r);\n  float k1 = length(p / (r * r));\n  return k0 * (k0 - 1.0) / max(k1, 1e-4);\n}\n\nfloat sdRoundCone(vec3 p, vec3 a, vec3 b, float r1, float r2) {\n  vec3 ba = b - a;\n  float l2 = dot(ba, ba);\n  float rr = r1 - r2;\n  float a2 = l2 - rr * rr;\n  float il2 = 1.0 / l2;\n  vec3 pa = p - a;\n  float y = dot(pa, ba);\n  float z = y - l2;\n  vec3 x = pa * l2 - ba * y;\n  float x2 = dot(x, x);\n  float y2 = y * y * l2;\n  float z2 = z * z * l2;\n  float k = sign(rr) * rr * rr * x2;\n  if (sign(z) * a2 * z2 > k) return sqrt(x2 + z2) * il2 - r2;\n  if (sign(y) * a2 * y2 < k) return sqrt(x2 + y2) * il2 - r1;\n  return (sqrt(x2 * a2 * il2) + y * rr) * il2 - r1;\n}\n\nfloat sdCircle2(vec2 p, float r) { return length(p) - r; }\n\nfloat sdEllipse2(vec2 p, vec2 r) {\n  float k0 = length(p / r);\n  float k1 = length(p / (r * r));\n  return k0 * (k0 - 1.0) / max(k1, 1e-4);\n}\n\nfloat sdSegment2(vec2 p, vec2 a, vec2 b) {\n  vec2 pa = p - a, ba = b - a;\n  float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0);\n  return length(pa - ba * h);\n}\n\nfloat sdArc2(vec2 p, vec2 sc, float ra, float rb) {\n  p.x = abs(p.x);\n  return ((sc.y * p.x > sc.x * p.y) ? length(p - sc * ra) : abs(length(p) - ra)) - rb;\n}\n\n// Compute glass alcove walls matching the stage aspect ratio\nvec2 stageHalfSize() {\n  float aspect = uResolution.x / max(uResolution.y, 1.0);\n  // Leave a crisp breathing lane along the top edge so status copy never collides with ears\n  float hh = 0.78;\n  float hw = min(1.36, hh * aspect * 0.88);\n  return vec2(hw, hh);\n}\n\n// Continuous creature scale driven by context fullness & compaction squeeze\nfloat bodyScale() {\n  float f = clamp(uFullness - uHoverRelief * 0.045, 0.0, 1.15);\n  // Nimble (0.64) at low context -> huge & overflowing (1.46) at 100% context\n  float sc = mix(0.64, 1.44, pow(clamp(f, 0.0, 1.0), 0.85)) + max(f - 1.0, 0.0) * 0.28;\n  // Compaction pulls the whole body inward tightly before releasing!\n  sc *= mix(1.0, 0.62, uCompactSq);\n  return sc;\n}\n\n// World point -> normalized character local space (before wall clamping)\nvec3 toLocal(vec3 wp, out float scaleOut) {\n  float t = (uMaterial == 1 && uClayStep > 0.5) ? floor(uTime * 12.0) / 12.0 : uTime;\n  float sc = bodyScale();\n  scaleOut = sc;\n\n  vec3 p = wp;\n  // Breathing gets faster & tighter when stuffed or compacting\n  float breathRate = mix(2.3, 4.6, clamp(uFullness, 0.0, 1.0)) + uCompactSq * 7.0;\n  float breathAmp = mix(0.016, 0.024, clamp(uFullness, 0.0, 1.0));\n  float breath = sin(t * breathRate) * breathAmp;\n\n  // Compacting vibration tremor\n  if (uCompactSq > 0.02) {\n    p.x += sin(uTime * 42.0) * 0.018 * uCompactSq;\n    p.y += cos(uTime * 37.0) * 0.014 * uCompactSq;\n  }\n\n  // Anchor slightly lower so top status strip stays 100% clear even at 100% fullness\n  float floorAnchor = mix(-0.26, -0.14, smoothstep(0.1, 0.9, uFullness));\n  p.y -= (uJumpY + breath + floorAnchor);\n\n  // Rubber-band drag shear\n  float topMask = smoothstep(-0.72, 0.65, p.y);\n  p.xy -= uStretch * (0.42 + 0.58 * topMask);\n\n  // Volume-preserving squash & stretch\n  float sy = clamp(1.0 + uSquash + breath * 1.4 - uCompactSq * 0.14, 0.66, 1.38);\n  float sxz = 1.0 / sqrt(sy);\n  vec3 pivot = vec3(0.0, -0.58 * sc, 0.0);\n  p -= pivot;\n  p.y /= sy;\n  p.xz /= sxz;\n  p += pivot;\n\n  // Soft-body wave ripple (heavier / slower when stuffed, juicier on jelly)\n  if (uWobbleAmp > 0.001) {\n    float matMult = (uMaterial == 2) ? 1.55 : (uMaterial == 0 ? 0.72 : 0.62);\n    float w = sin(p.y * 4.8 - uWobblePhase) * uWobbleAmp * matMult * 0.068;\n    float w2 = cos(p.x * 4.2 - uWobblePhase * 0.85) * uWobbleAmp * matMult * 0.038;\n    p.x += w;\n    p.y += w2;\n  }\n\n  // Head tilt & 3D cursor gaze (tighter when wedged against walls!)\n  float wallLock = 1.0 - 0.55 * smoothstep(0.75, 1.0, uFullness);\n  p.xy = rot2(-uTilt * wallLock) * p.xy;\n  float yaw = -uLook.x * 0.32 * wallLock;\n  float pitch = uLook.y * 0.22 * wallLock;\n  p.xz = rot2(yaw) * p.xz;\n  p.yz = rot2(pitch) * p.yz;\n\n  // Normalize into unit character space\n  p /= sc;\n  return p;\n}\n\nfloat sdCreatureUnit(vec3 lp, out float innerEarMask) {\n  // Belly & cheeks puff plumper horizontally as context fills up!\n  float puff = smoothstep(0.25, 1.0, uFullness);\n  vec3 b = lp - vec3(0.0, -0.06, 0.0);\n  float cheek = 1.0 + (0.10 + 0.16 * puff) * (1.0 - smoothstep(-0.38, 0.34, b.y));\n  b.x /= cheek;\n\n  vec3 bodyRadii = vec3(0.71 + 0.10 * puff, 0.63 + 0.05 * puff, 0.54 + 0.08 * puff);\n  float dBody = sdEllipsoid(b, bodyRadii);\n\n  // Chubby rounded ears (droop slightly outward when stuffed/pressed against ceiling!)\n  vec3 ep = vec3(abs(lp.x), lp.y, lp.z);\n  float earSplay = puff * 0.08;\n  float earDrop = puff * 0.05 + (uMood == 3 || uMood == 6 ? 0.04 : 0.0);\n  vec3 eBase = vec3(0.34 + earSplay * 0.4, 0.30, 0.02);\n  vec3 eTip  = vec3(0.47 + earSplay, 0.61 - earDrop, -0.01);\n  float dEar = sdRoundCone(ep, eBase, eTip, 0.25, 0.13);\n  float d = smin(dBody, dEar, 0.16);\n\n  // Soft blush inner ear region (solid, zero puncture)\n  float dInner = sdRoundCone(ep, vec3(0.36 + earSplay * 0.4, 0.34, 0.23), vec3(0.45 + earSplay, 0.53 - earDrop, 0.17), 0.11, 0.05);\n  innerEarMask = (1.0 - smoothstep(-0.02, 0.11, dInner)) * smoothstep(0.05, 0.18, ep.z);\n\n  if (uMaterial == 1) {\n    // Organic stop-motion hand-kneaded clay irregularity\n    float boilT = (uClayStep > 0.5) ? floor(uTime * 10.0) * 1.37 : uTime * 0.22;\n    float eyeProtect = 1.0 - 0.78 * (1.0 - smoothstep(0.14, 0.34, length(lp.xy - vec2(0.0, -0.03))));\n    float lump = (noise3(lp * 3.1 + vec3(boilT * 0.05, 0.0, 0.0)) - 0.5) * 0.017;\n    lump += (noise3(lp * 7.2 + vec3(0.0, boilT * 0.08, 1.7)) - 0.5) * 0.006;\n    d += lump * eyeProtect;\n\n    // Real viscoelastic cursor poke dents with displaced rim\n    for (int i = 0; i < 4; i++) {\n      vec4 dent = uDents[i];\n      if (dent.w > 0.005) {\n        float rad = 0.21 * (0.68 + 0.32 * dent.w);\n        float dist = length(lp - dent.xyz);\n        float crater = rad - dist;\n        d = smax(d, crater * dent.w * 0.62, 0.085);\n        float rim = exp(-pow((dist - rad * 1.08) / 0.09, 2.0));\n        d -= rim * dent.w * 0.020;\n      }\n    }\n  }\n\n  return d;\n}\n\n// World-space SDF WITH smooth glass-wall squishing at high fullness!\nfloat mapWorldFull(vec3 wp, out float innerEarMask, out float wallPress) {\n  float sc;\n  vec3 lp = toLocal(wp, sc);\n  float d = sdCreatureUnit(lp, innerEarMask) * sc;\n\n  // Stage physical glass alcove boundaries (left, right, ceiling, floor, front pane!)\n  vec2 hs = stageHalfSize();\n  float dWallX = abs(wp.x) - hs.x;\n  float dWallT = wp.y - (hs.y - 0.12);\n  float dWallB = -(hs.y + 0.08) - wp.y;\n  float dWallF = wp.z - 0.74; // presses belly & cheeks softly against the front glass!\n  float dBox = max(max(dWallX, max(dWallT, dWallB)), dWallF);\n\n  // Measure how strongly the creature is being compressed against the glass here\n  wallPress = smoothstep(-0.14, 0.02, dBox);\n\n  // Smoothly flatten any bulging part against the stage glass walls!\n  d = smax(d, dBox, 0.105);\n  return d;\n}\n\nfloat mapWorld(vec3 wp, out float innerEarMask) {\n  float wpPress;\n  return mapWorldFull(wp, innerEarMask, wpPress);\n}\n\nvec3 calcNormal(vec3 wp) {\n  float m;\n  vec2 e = vec2(0.0028, -0.0028);\n  return normalize(\n    e.xyy * mapWorld(wp + e.xyy, m) +\n    e.yyx * mapWorld(wp + e.yyx, m) +\n    e.yxy * mapWorld(wp + e.yxy, m) +\n    e.xxx * mapWorld(wp + e.xxx, m)\n  );\n}\n\nfloat clayFingerprint(vec3 lp) {\n  float boil = (uClayStep > 0.5) ? floor(uTime * 10.0) * 0.05 : 0.0;\n  float total = 0.0;\n  vec3 centers[3];\n  centers[0] = vec3( 0.26,  0.26, 0.44);\n  centers[1] = vec3(-0.36, -0.22, 0.40);\n  centers[2] = vec3( 0.36, -0.24, 0.38);\n\n  for (int i = 0; i < 3; i++) {\n    vec3 dp = lp - centers[i];\n    vec2 rdp = rot2(float(i) * 0.9 + 0.35) * dp.xy;\n    float mask = exp(-(rdp.x * rdp.x * 16.0 + rdp.y * rdp.y * 9.0 + dp.z * dp.z * 12.0));\n    float warp = noise3(lp * 7.5 + vec3(float(i) * 4.1, boil, 0.0)) * 0.075;\n    float r = length(rdp * vec2(1.0, 1.65)) + warp;\n    total += sin(r * 115.0 + float(i) * 2.0) * mask * 0.34;\n  }\n\n  for (int i = 0; i < 4; i++) {\n    vec4 dent = uDents[i];\n    if (dent.w > 0.02) {\n      vec3 dp = lp - dent.xyz;\n      vec2 rdp = rot2(0.45 + float(i) * 0.7) * dp.xy;\n      float mask = exp(-(rdp.x * rdp.x * 24.0 + rdp.y * rdp.y * 16.0)) * dent.w * 1.15;\n      float warp = noise3(lp * 9.5) * 0.04;\n      float r = length(rdp * vec2(1.0, 1.55)) + warp;\n      total += sin(r * 138.0) * mask;\n    }\n  }\n  return total;\n}\n\nstruct FaceEval {\n  float mask;\n  float furClear;\n  float blush;\n  vec3  color;\n  float gloss;\n};\n\nFaceEval evalFace(vec3 lp, float frontZ) {\n  FaceEval f;\n  f.mask = 0.0;\n  f.furClear = 0.0;\n  f.blush = 0.0;\n  f.color = vec3(0.08, 0.05, 0.10);\n  f.gloss = 0.0;\n\n  float frontMask = smoothstep(0.02, 0.18, frontZ);\n  if (frontMask <= 0.001) return f;\n\n  // Hovering remove/compact pulls gaze gently downward toward the controls\n  vec2 gaze = uLook * vec2(0.062, 0.042) + vec2(0.0, -uHoverRelief * 0.065);\n  vec2 fp = lp.xy - vec2(0.0, -0.04);\n  float aa = 0.010;\n\n  // Rosy cheek blushes (stronger when stuffed, petted, or relieved!)\n  float stuffedHeat = smoothstep(0.70, 0.98, uFullness);\n  vec2 cheekP = vec2(abs(fp.x - gaze.x * 0.45) - 0.35, fp.y - gaze.y * 0.3 + 0.09);\n  float cheekDist = length(cheekP / vec2(0.12, 0.075));\n  float blushBoost = 0.85 + 0.65 * max(uPetHappy, stuffedHeat) + (uMood == 5 ? 0.5 : 0.0);\n  f.blush = (1.0 - smoothstep(0.15, 1.15, cheekDist)) * 0.40 * blushBoost * frontMask;\n\n  vec2 ep = vec2(abs(fp.x - gaze.x * 0.75) - 0.215, fp.y - (0.045 + gaze.y * 0.75));\n  float sideSign = sign(fp.x - gaze.x * 0.75);\n\n  float clearEye = 1.0 - smoothstep(0.085, 0.165, length(ep));\n  float clearMouth = 1.0 - smoothstep(0.055, 0.135, length(fp - vec2(gaze.x * 0.55, -0.125 + gaze.y * 0.4)));\n  f.furClear = max(clearEye, clearMouth) * frontMask;\n\n  bool happyEyes = (uPetHappy > 0.35 || uMood == 5);\n  bool squeezeEyes = (uMood == 4); // compacting tight >< squeeze!\n  bool angryState = (uMood == 3 || uMood == 6) && uHoverRelief < 0.45;\n\n  if (squeezeEyes) {\n    // Tight effort > < eyes pointing inward toward nose while compacting!\n    vec2 sp = vec2(ep.x, ep.y);\n    float dTop = sdSegment2(sp, vec2(0.055, 0.055), vec2(-0.058, 0.0)) - 0.019;\n    float dBot = sdSegment2(sp, vec2(0.055, -0.055), vec2(-0.058, 0.0)) - 0.019;\n    float m = 1.0 - smoothstep(-aa, aa, min(dTop, dBot));\n    f.mask = max(f.mask, m);\n    f.color = vec3(0.12, 0.07, 0.14);\n    f.gloss = 0.25;\n  } else if (happyEyes) {\n    // Happy curved ^ ^ arcs (petted or freshly compacted relief!)\n    vec2 sp = ep + vec2(0.0, 0.02);\n    float dArc = sdArc2(sp, vec2(sin(1.05), cos(1.05)), 0.076, 0.020);\n    float m = 1.0 - smoothstep(-aa, aa, dArc);\n    f.mask = max(f.mask, m);\n    f.color = vec3(0.12, 0.07, 0.14);\n    f.gloss = 0.25;\n  } else {\n    // Glossy expressive bead eyes (widen eagerly on gulp or hover-relief!)\n    float wideBoost = 1.0 + uGulpOpen * 0.18 + uHoverRelief * 0.12 + (uMood == 2 ? 0.07 : 0.0);\n    float openH = mix(0.104 * wideBoost, 0.014, uBlink);\n    vec2 eyeR = vec2(0.086 * (1.0 + uGulpOpen * 0.10), openH);\n    vec2 pupilOffset = gaze * 0.18;\n    float dEye = sdEllipse2(ep, eyeR);\n\n    if (angryState) {\n      float lidLine = (ep.y - 0.034) + (fp.x - gaze.x * 0.75) * sideSign * (-0.36);\n      dEye = max(dEye, lidLine - 0.02);\n    }\n\n    float eyeMask = 1.0 - smoothstep(-aa, aa, dEye);\n    if (eyeMask > 0.005) {\n      vec3 eyeCol = vec3(0.06, 0.04, 0.09);\n      float lowerIris = (1.0 - smoothstep(-0.09, 0.02, ep.y)) * (1.0 - smoothstep(0.02, 0.085, length(ep - vec2(0.0, -0.04))));\n      eyeCol += uBaseColor * lowerIris * 0.24;\n\n      float openVis = 1.0 - smoothstep(0.55, 0.9, uBlink);\n      float c1 = 1.0 - smoothstep(0.010, 0.028, length(ep - (vec2(-0.028, 0.034) + pupilOffset * 0.35)));\n      float c2 = 1.0 - smoothstep(0.005, 0.014, length(ep - (vec2(0.024, -0.028) + pupilOffset * 0.35)));\n      eyeCol = mix(eyeCol, vec3(1.0), clamp(c1 + c2 * 0.85, 0.0, 1.0) * openVis);\n\n      f.color = eyeCol;\n      f.mask = max(f.mask, eyeMask);\n      f.gloss = 0.95 * eyeMask;\n    }\n\n    // Angry/strained brows when stuffed/rejected; worried-hopeful brows when heavy or hovering remove\n    if (angryState) {\n      vec2 bp = vec2(abs(fp.x - gaze.x * 0.75), fp.y - gaze.y * 0.75);\n      float dBrow = sdSegment2(bp, vec2(0.095, 0.115), vec2(0.320, 0.195)) - 0.020;\n      float bMask = 1.0 - smoothstep(-aa, aa, dBrow);\n      f.furClear = max(f.furClear, (1.0 - smoothstep(0.01, 0.055, dBrow)) * frontMask);\n      if (bMask > f.mask) {\n        f.color = vec3(0.22, 0.05, 0.08);\n        f.gloss = 0.25;\n      }\n      f.mask = max(f.mask, bMask);\n    } else if (uMood == 2 || uHoverRelief > 0.4) {\n      // Gentle worried/hopeful tilted brows (\\ / inverted -> / \\)\n      vec2 bp = vec2(abs(fp.x - gaze.x * 0.75), fp.y - gaze.y * 0.75);\n      float dBrow = sdSegment2(bp, vec2(0.115, 0.215), vec2(0.305, 0.175)) - 0.016;\n      float bMask = 1.0 - smoothstep(-aa, aa, dBrow);\n      f.furClear = max(f.furClear, (1.0 - smoothstep(0.01, 0.05, dBrow)) * frontMask);\n      if (bMask > f.mask) {\n        f.color = vec3(0.19, 0.12, 0.22);\n        f.gloss = 0.20;\n      }\n      f.mask = max(f.mask, bMask);\n    }\n  }\n\n  // --- MOUTH ---\n  vec2 mp = fp - vec2(gaze.x * 0.6, -0.115 + gaze.y * 0.45);\n  float dMouth = 1.0;\n  vec3 mouthCol = vec3(0.13, 0.06, 0.11);\n  bool mouthOpen = false;\n\n  if (uGulpOpen > 0.12) {\n    // Big round gulping 'O' mouth eating incoming tokens!\n    float rG = 0.032 + uGulpOpen * 0.062;\n    dMouth = sdEllipse2(mp - vec2(0.0, 0.005), vec2(rG * 0.92, rG));\n    mouthOpen = true;\n  } else if (squeezeEyes) {\n    // Tight wavy compaction effort mouth\n    dMouth = sdEllipse2(mp - vec2(0.0, 0.01), vec2(0.048, 0.022));\n  } else if (angryState) {\n    // Pursed stuffed pout\n    dMouth = sdEllipse2(mp - vec2(0.0, 0.012), vec2(0.042, 0.022));\n  } else if (uMood == 2 && uHoverRelief < 0.35) {\n    // Slightly tight worried 'o' when getting heavy\n    dMouth = sdCircle2(mp - vec2(0.0, 0.005), 0.028);\n  } else if (happyEyes) {\n    // Big relieved open D-smile!\n    float dCirc = sdCircle2(mp - vec2(0.0, 0.025), 0.078);\n    dMouth = max(dCirc, mp.y - 0.018);\n    mouthOpen = true;\n  } else {\n    vec2 sp = mp - vec2(0.0, 0.045);\n    dMouth = sdArc2(vec2(sp.x, -sp.y), vec2(sin(0.95), cos(0.95)), 0.072, 0.016);\n  }\n\n  float mouthMask = 1.0 - smoothstep(-aa, aa, dMouth);\n  if (mouthMask > 0.005) {\n    if (mouthOpen) {\n      float tongue = 1.0 - smoothstep(0.02, 0.055, length(mp - vec2(0.0, -0.045)));\n      mouthCol = mix(vec3(0.20, 0.05, 0.11), vec3(0.96, 0.38, 0.48), tongue * 0.85);\n    }\n    if (mouthMask > f.mask) {\n      f.color = mouthCol;\n      f.gloss = mouthOpen ? 0.30 : 0.20;\n    }\n    f.mask = max(f.mask, mouthMask);\n  }\n\n  f.mask *= frontMask;\n  return f;\n}\n\nvec3 studioLights(vec3 N, vec3 V, vec3 albedo, float roughness, float sssAmount, float ao, float specStrength) {\n  vec3 L1 = normalize(vec3(-0.56, 0.82, 0.72));\n  vec3 L2 = normalize(vec3( 0.76, 0.35, 0.45));\n  vec3 L3 = normalize(vec3( 0.0, -0.95, 0.30));\n\n  float wrap = 0.46;\n  float diff1 = clamp((dot(N, L1) + wrap) / (1.0 + wrap), 0.0, 1.0);\n  float diff2 = clamp((dot(N, L2) + 0.38) / 1.38, 0.0, 1.0);\n  float bounce = clamp(dot(N, L3) * 0.5 + 0.5, 0.0, 1.0);\n\n  vec3 shadowTint = albedo * albedo * 0.52 + albedo * 0.34;\n  vec3 col = mix(shadowTint, albedo * vec3(1.06, 1.03, 0.99), diff1) * 0.89;\n  col += albedo * vec3(0.88, 0.94, 1.06) * diff2 * 0.28;\n  col += albedo * mix(vec3(1.0, 0.98, 0.96), vec3(0.55, 0.58, 0.70), uDarkBg) * bounce * 0.24;\n\n  float fresnel = pow(1.0 - max(dot(N, V), 0.0), 2.5);\n  vec3 sssCol = mix(albedo, vec3(1.0, 0.93, 0.87), 0.44);\n  col += sssCol * fresnel * sssAmount;\n\n  vec3 H = normalize(L1 + V);\n  float specPow = mix(96.0, 10.0, roughness);\n  float spec = pow(max(dot(N, H), 0.0), specPow) * specStrength;\n  col += vec3(1.0, 0.99, 0.97) * spec;\n\n  return col * ao;\n}\n\n// --- Material 0: PLUSH FUR ---\nvec4 renderPlush(vec3 ro, vec3 rd) {\n  float t = 0.45;\n  float maxT = 5.4;\n  bool hitOuter = false;\n  float earM = 0.0;\n  for (int i = 0; i < 32; i++) {\n    vec3 wp = ro + rd * t;\n    float dOuter = mapWorld(wp, earM) - FUR_LEN;\n    if (dOuter < 0.003) { hitOuter = true; break; }\n    t += max(dOuter * 0.82, 0.02);\n    if (t > maxT) break;\n  }\n  if (!hitOuter) return vec4(0.0);\n\n  vec3 accumCol = vec3(0.0);\n  float accumAlpha = 0.0;\n  vec3 entryP = ro + rd * t;\n  vec3 Nbase = calcNormal(entryP);\n\n  const int STEPS = 24;\n  float dt = 0.015;\n  float jitter = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453);\n  t += jitter * dt * 0.85;\n\n  vec3 L1 = normalize(vec3(-0.55, 0.84, 0.72));\n  vec3 L2 = normalize(vec3( 0.75, 0.35, 0.45));\n  vec3 V = -rd;\n  float flushAmt = smoothstep(0.82, 1.0, uFullness) * 0.44 + (uMood == 6 ? 0.30 : 0.0);\n\n  for (int i = 0; i < STEPS; i++) {\n    vec3 wp = ro + rd * t;\n    float innerEar = 0.0;\n    float wallPress = 0.0;\n    float dCore = mapWorldFull(wp, innerEar, wallPress);\n    float sc;\n    vec3 lp = toLocal(wp, sc);\n\n    if (dCore > FUR_LEN + 0.03 && i > 2) break;\n\n    FaceEval face = evalFace(lp, lp.z);\n    float featureTrim = max(face.furClear * 0.85, face.mask);\n    // Fur also compresses slightly where pressed flat against the glass walls!\n    float localFurLen = FUR_LEN * (1.0 - featureTrim) * (1.0 - wallPress * 0.58);\n\n    if (dCore <= 0.002) {\n      vec3 N = calcNormal(wp);\n      vec3 baseCol = mix(uBaseColor, mix(uBaseColor, uAccentColor, 0.58), innerEar);\n      baseCol = mix(baseCol, vec3(1.0, 0.42, 0.54), face.blush);\n      baseCol = mix(baseCol, vec3(0.98, 0.24, 0.28), clamp(flushAmt, 0.0, 0.55) * smoothstep(0.02, 0.55, lp.y));\n\n      float coreTex = 0.90 + 0.10 * noise3(lp * 68.0);\n      vec3 coreLit = studioLights(N, V, baseCol * coreTex, 0.90, 0.32, 0.88, 0.08);\n      // Slight glossy glass-contact highlight where fur presses against glass walls\n      coreLit += vec3(1.0) * wallPress * 0.07;\n\n      if (face.mask > 0.005) {\n        vec3 faceLit = face.color;\n        if (face.gloss > 0.3) {\n          vec3 H = normalize(L1 + V);\n          faceLit += vec3(1.0) * pow(max(dot(N, H), 0.0), 64.0) * face.gloss * 0.55;\n        }\n        coreLit = mix(coreLit, faceLit, face.mask);\n      }\n\n      coreLit *= 1.0 - face.furClear * (1.0 - face.mask) * 0.18;\n\n      if (face.mask > 0.5) {\n        accumCol = mix(accumCol + (1.0 - accumAlpha) * coreLit, coreLit, face.mask * 0.95);\n        accumAlpha = 1.0;\n      } else {\n        accumCol += (1.0 - accumAlpha) * coreLit;\n        accumAlpha = 1.0;\n      }\n      break;\n    }\n\n    if (dCore < localFurLen && face.mask < 0.15) {\n      float h = clamp(dCore / max(localFurLen, 0.01), 0.0, 1.0);\n      vec3 N = Nbase;\n      vec3 qSurf = lp - N * (dCore / max(sc, 0.2));\n\n      vec2 radial = qSurf.xy - vec2(0.0, -0.05);\n      float rLen = length(radial);\n      vec3 outComb = vec3(radial / max(rLen, 0.14) * 0.070 * smoothstep(0.0, 0.35, rLen), 0.0);\n      vec3 droop = vec3(0.0, -0.056, 0.0);\n      vec3 clumpDir = (hash33(floor(qSurf * 18.0)) - 0.5) * 0.036;\n\n      float petDist = length(qSurf.xy - uPetPos);\n      float petInfluence = exp(-petDist * petDist * 5.2) * uPetStrength;\n      vec3 petBend = vec3(uPetDir * 0.18, 0.0) * petInfluence;\n\n      vec3 qStrand = qSurf - (outComb + droop + clumpDir + petBend) * (h * h);\n      float fineFiber = furStrands(qStrand * 70.0);\n      float tuftGroup = noise3(qStrand * 22.0 + vec3(2.3, 4.1, 1.7));\n      float strandVal = mix(fineFiber, fineFiber * (0.68 + 0.48 * tuftGroup), 0.50);\n\n      float thresh = mix(0.06, 0.80, pow(h, 0.84));\n      float density = smoothstep(thresh, thresh + 0.24, strandVal);\n\n      if (density > 0.01) {\n        vec3 baseCol = mix(uBaseColor, mix(uBaseColor, uAccentColor, 0.58), innerEar);\n        baseCol = mix(baseCol, vec3(1.0, 0.42, 0.54), face.blush * (1.0 - h * 0.4));\n        baseCol = mix(baseCol, vec3(0.98, 0.24, 0.28), clamp(flushAmt, 0.0, 0.55) * smoothstep(0.02, 0.55, lp.y));\n\n        float facing = max(dot(N, V), 0.0);\n        float minAO = mix(0.46, 0.68, facing);\n        float rootAO = mix(minAO, 1.12, pow(h, 0.58));\n        vec3 rootTint = mix(baseCol * baseCol * 0.58 + baseCol * 0.48, baseCol * vec3(1.08, 1.06, 1.03), pow(h, 0.62));\n\n        float diff1 = clamp(dot(N, L1) * 0.52 + 0.55, 0.0, 1.0);\n        float diff2 = clamp(dot(N, L2) * 0.45 + 0.56, 0.0, 1.0);\n        float bounce = clamp(-N.y * 0.5 + 0.5, 0.0, 1.0);\n        float rim = pow(1.0 - facing, 1.9);\n\n        vec3 fiberCol = rootTint * (diff1 * 0.82 + diff2 * 0.26 + bounce * 0.22) * rootAO;\n        vec3 tipGlow = mix(baseCol, vec3(1.0, 0.98, 0.96), 0.60);\n        fiberCol += tipGlow * rim * (0.30 + 0.46 * h);\n        fiberCol *= (0.94 + 0.12 * tuftGroup);\n        fiberCol *= 1.0 - face.furClear * 0.14 * (1.0 - h);\n\n        float sampleAlpha = clamp(density * (0.46 + 0.28 * (1.0 - h)), 0.0, 1.0);\n        accumCol += (1.0 - accumAlpha) * fiberCol * sampleAlpha;\n        accumAlpha += (1.0 - accumAlpha) * sampleAlpha;\n        if (accumAlpha > 0.97) break;\n      }\n    }\n\n    t += dt;\n  }\n\n  return vec4(accumCol, accumAlpha);\n}\n\n// --- Material 1: STOP-MOTION CLAY ---\nvec4 renderClay(vec3 ro, vec3 rd) {\n  float t = 0.45;\n  float maxT = 5.4;\n  float earM = 0.0;\n  float wallPress = 0.0;\n  bool hit = false;\n\n  for (int i = 0; i < 48; i++) {\n    vec3 wp = ro + rd * t;\n    float d = mapWorldFull(wp, earM, wallPress);\n    if (d < 0.0018) { hit = true; break; }\n    t += d * 0.78;\n    if (t > maxT) break;\n  }\n  if (!hit) return vec4(0.0);\n\n  vec3 wp = ro + rd * t;\n  float sc;\n  vec3 lp = toLocal(wp, sc);\n  vec3 N = calcNormal(wp);\n  vec3 V = -rd;\n  vec3 L1 = normalize(vec3(-0.56, 0.82, 0.72));\n\n  FaceEval face = evalFace(lp, lp.z);\n\n  float fp0 = clayFingerprint(lp) * (1.0 - face.mask);\n  float eps = 0.0045;\n  vec3 fpGrad = vec3(\n    clayFingerprint(lp + vec3(eps, 0.0, 0.0)) - fp0,\n    clayFingerprint(lp + vec3(0.0, eps, 0.0)) - fp0,\n    clayFingerprint(lp + vec3(0.0, 0.0, eps)) - fp0\n  ) / eps;\n  vec3 Nclay = normalize(N - fpGrad * 0.0038 * (1.0 - face.mask));\n\n  float mDummy;\n  float thick = clamp(-mapWorld(wp - N * 0.24, mDummy) * 2.8, 0.0, 1.0);\n  float thinGlow = (1.0 - thick) * 0.52;\n  float dAO1 = mapWorld(wp + N * 0.08, mDummy);\n  float dAO2 = mapWorld(wp + N * 0.18, mDummy);\n  float ao = clamp(0.48 + 0.52 * clamp((dAO1 / 0.08 + dAO2 / 0.18) * 0.5, 0.0, 1.0), 0.58, 1.0);\n\n  float flushAmt = smoothstep(0.82, 1.0, uFullness) * 0.44 + (uMood == 6 ? 0.30 : 0.0);\n  vec3 baseCol = mix(uBaseColor, mix(uBaseColor, uAccentColor, 0.52), earM);\n  baseCol = mix(baseCol, vec3(1.0, 0.44, 0.52), face.blush);\n  baseCol = mix(baseCol, vec3(0.96, 0.24, 0.26), clamp(flushAmt, 0.0, 0.55) * smoothstep(0.02, 0.55, lp.y));\n  baseCol *= 0.965 + 0.055 * noise3(lp * 34.0);\n\n  vec3 col = studioLights(Nclay, V, baseCol, 0.78, 0.22 + thinGlow * 0.34, ao, 0.09);\n  float rimBack = pow(1.0 - max(dot(Nclay, V), 0.0), 2.4) * (0.30 + thinGlow);\n  col += mix(baseCol, vec3(1.0, 0.80, 0.65), 0.42) * rimBack * 0.34;\n  col *= 1.0 + fp0 * 0.026;\n  // Subtle flattened sheen where clay presses against the glass pane\n  col += vec3(1.0, 0.98, 0.96) * wallPress * 0.08;\n\n  if (face.mask > 0.005) {\n    vec3 Neye = normalize(mix(N, vec3(0.0, 0.0, 1.0), 0.35));\n    vec3 H = normalize(L1 + V);\n    vec3 H2 = normalize(normalize(vec3(0.75, 0.4, 0.5)) + V);\n    float beadSpec = pow(max(dot(Neye, H), 0.0), 120.0) * 0.95 + pow(max(dot(Neye, H2), 0.0), 48.0) * 0.30;\n    vec3 faceLit = face.color + vec3(1.0) * beadSpec * face.gloss;\n    col = mix(col, faceLit, face.mask);\n  }\n\n  return vec4(col, 1.0);\n}\n\n// --- Material 2: TRANSLUCENT JELLY ---\nvec4 renderJelly(vec3 ro, vec3 rd) {\n  float t = 0.45;\n  float maxT = 5.4;\n  float earM = 0.0;\n  float wallPress = 0.0;\n  bool hit = false;\n\n  for (int i = 0; i < 46; i++) {\n    vec3 wp = ro + rd * t;\n    float d = mapWorldFull(wp, earM, wallPress);\n    if (d < 0.0018) { hit = true; break; }\n    t += d * 0.82;\n    if (t > maxT) break;\n  }\n  if (!hit) return vec4(0.0);\n\n  vec3 wp = ro + rd * t;\n  float sc;\n  vec3 lp = toLocal(wp, sc);\n  vec3 N = calcNormal(wp);\n  vec3 V = -rd;\n  vec3 L1 = normalize(vec3(-0.58, 0.85, 0.68));\n  vec3 L2 = normalize(vec3( 0.78, 0.38, 0.42));\n\n  vec3 refrDir = refract(rd, N, 1.0 / 1.33);\n  vec2 innerOff = vec2(uInnerOffsetX, uInnerOffsetY);\n\n  float mDummy;\n  float thickness = 0.0;\n  float bubbleGlow = 0.0;\n  float innerCore = 0.0;\n  for (int i = 1; i <= 7; i++) {\n    float stepD = float(i) * 0.16;\n    vec3 ip = wp + refrDir * stepD;\n    float dIn = mapWorld(ip, mDummy);\n    if (dIn < 0.0) {\n      thickness += 0.16;\n      float scIn;\n      vec3 ilp = toLocal(ip, scIn) - vec3(innerOff * 0.42, 0.0);\n      float bCell = furStrands(ilp * 10.5 + vec3(0.0, -uTime * 0.10, 0.0));\n      bubbleGlow += smoothstep(0.84, 0.96, bCell) * 0.18;\n      float coreDist = length(ilp - vec3(0.0, -0.07, -0.02));\n      innerCore = max(innerCore, 1.0 - smoothstep(0.06, 0.42, coreDist));\n    }\n  }\n\n  vec3 absorb = (1.0 - clamp(uBaseColor, 0.08, 0.95)) * 2.1 + vec3(0.20);\n  vec3 transmittance = exp(-thickness * absorb);\n\n  vec3 bgLight = mix(vec3(1.0, 0.99, 1.0), uBaseColor * 1.32 + vec3(0.18), 0.58);\n  vec3 bgDark  = uBaseColor * 0.95 + vec3(0.10, 0.08, 0.16);\n  vec3 transmitted = mix(bgLight, bgDark, uDarkBg) * transmittance;\n\n  vec3 deepCandy = uBaseColor * mix(0.82, 0.72, uDarkBg);\n  vec3 jellyBody = mix(deepCandy, transmitted, 0.62);\n\n  vec3 candyGlow = mix(uBaseColor * 1.15, vec3(1.0, 0.97, 0.92), mix(0.35, 0.22, uDarkBg));\n  jellyBody += candyGlow * innerCore * mix(0.32, 0.44, uDarkBg);\n  jellyBody += vec3(1.0, 0.99, 0.97) * clamp(bubbleGlow, 0.0, 0.65) * 0.52;\n  jellyBody = mix(jellyBody, mix(jellyBody, uAccentColor, 0.45), earM * 0.55);\n\n  vec3 innerP = lp + vec3(refrDir.xy * 0.08, 0.0) - vec3(innerOff * 0.28, 0.0);\n  FaceEval face = evalFace(innerP, lp.z);\n\n  float flushAmt = smoothstep(0.82, 1.0, uFullness) * 0.48 + (uMood == 6 ? 0.30 : 0.0);\n  jellyBody = mix(jellyBody, vec3(1.0, 0.36, 0.52), face.blush * 0.72);\n  jellyBody = mix(jellyBody, vec3(1.0, 0.22, 0.25), clamp(flushAmt, 0.0, 0.55) * smoothstep(0.02, 0.55, lp.y));\n\n  if (face.mask > 0.005) {\n    vec3 suspendedCol = mix(face.color, jellyBody * 0.38 + face.color * 0.75, 0.10);\n    jellyBody = mix(jellyBody, suspendedCol, face.mask * 0.97);\n  }\n\n  float diff = clamp(dot(N, L1) * 0.45 + 0.60, 0.0, 1.0);\n  jellyBody *= (0.84 + 0.22 * diff);\n\n  float fresnel = pow(1.0 - max(dot(N, V), 0.0), 2.7);\n  vec3 H1 = normalize(L1 + V);\n  vec3 H2 = normalize(L2 + V);\n  float specBroad = pow(max(dot(N, H1), 0.0), 28.0) * 0.34 * (1.0 - face.mask * 0.65);\n  float specPin   = pow(max(dot(N, H1), 0.0), 150.0) * 0.72 * (1.0 - face.mask * 0.65);\n  float specFill  = pow(max(dot(N, H2), 0.0), 42.0) * 0.22;\n\n  vec3 rimCol = mix(uBaseColor * 1.35 + vec3(0.24), vec3(1.0), 0.44);\n  vec3 col = jellyBody + rimCol * fresnel * mix(0.56, 0.80, uDarkBg) + vec3(1.0) * (specBroad + specPin + specFill + wallPress * 0.12);\n\n  float alpha = clamp(0.84 + 0.16 * fresnel + thickness * 0.12, 0.0, 1.0);\n  return vec4(col * alpha, alpha);\n}\n\nvec4 evalFloorShadow(vec3 ro, vec3 rd) {\n  float floorY = -0.84;\n  if (rd.y >= -0.001) return vec4(0.0);\n  float t = (floorY - ro.y) / rd.y;\n  if (t <= 0.0 || t > 9.0) return vec4(0.0);\n  vec3 p = ro + rd * t;\n\n  float sc = bodyScale();\n  vec2 center = vec2(uStretch.x * 0.5, 0.0);\n  float heightScale = sc * (1.0 + max(uJumpY, 0.0) * 1.1);\n  float d = length((p.xz - center) / vec2(0.72 * heightScale, 0.46 * heightScale));\n  float strength = exp(-d * d * 3.0) * (0.22 / (1.0 + max(uJumpY, 0.0) * 1.5));\n  strength *= mix(1.0, 1.45, uDarkBg);\n\n  vec3 shadowCol = mix(vec3(0.08, 0.08, 0.12), vec3(0.0, 0.0, 0.0), uDarkBg);\n  if (uMaterial == 2) {\n    float caustic = exp(-d * d * 4.8) * (0.28 / (1.0 + max(uJumpY, 0.0) * 1.3));\n    vec3 glow = mix(uBaseColor, vec3(1.0), 0.22);\n    vec3 premul = shadowCol * strength * 0.65 + glow * caustic * mix(0.48, 0.76, uDarkBg);\n    return vec4(premul, clamp(strength * 0.72 + caustic * 0.40, 0.0, 0.60));\n  }\n  return vec4(shadowCol * strength, strength);\n}\n\nvoid main() {\n  vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / min(uResolution.x, uResolution.y);\n  vec3 ro = vec3(0.0, 0.02, 3.25);\n  vec3 rd = normalize(vec3(uv.x, uv.y - 0.015, -1.66));\n\n  vec4 shadow = evalFloorShadow(ro, rd);\n\n  float sc = bodyScale();\n  float boundR = max(1.18, sc * 1.25 + 0.26);\n  vec3 bCenter = vec3(uStretch.x * 0.5, uJumpY + uStretch.y * 0.5 - 0.12, 0.0);\n  vec3 oc = ro - bCenter;\n  float b = dot(oc, rd);\n  float c = dot(oc, oc) - boundR * boundR;\n\n  vec4 body = vec4(0.0);\n  if (b * b - c >= 0.0) {\n    if (uMaterial == 0) body = renderPlush(ro, rd);\n    else if (uMaterial == 1) body = renderClay(ro, rd);\n    else body = renderJelly(ro, rd);\n  }\n\n  if (body.a > 0.001) {\n    vec3 unpre = body.rgb / body.a;\n    unpre = unpre / (1.0 + 0.14 * max(unpre - 0.78, 0.0));\n    unpre = clamp(unpre, 0.0, 1.0);\n    body.rgb = unpre * body.a;\n  }\n\n  vec3 outRgb = body.rgb + shadow.rgb * (1.0 - body.a);\n  float outA  = body.a + shadow.a * (1.0 - body.a);\n  fragColor = vec4(outRgb, outA);\n}\n`;\n\nclass LocalSpring {\n  x: number;\n  v = 0;\n  target: number;\n  k: number;\n  c: number;\n  constructor(value = 0, stiffness = 220, damping = 17) {\n    this.x = value;\n    this.target = value;\n    this.k = stiffness;\n    this.c = damping;\n  }\n  impulse(dv: number) {\n    if (Number.isFinite(dv)) this.v += dv;\n  }\n  step(dt: number) {\n    const f = -this.k * (this.x - this.target) - this.c * this.v;\n    this.v += f * dt;\n    this.x += this.v * dt;\n    if (!Number.isFinite(this.x)) {\n      this.x = this.target;\n      this.v = 0;\n    }\n    return this.x;\n  }\n}\n\ninterface Particle {\n  kind: \"steam\" | \"sparkle\" | \"crumb\";\n  x: number;\n  y: number;\n  vx: number;\n  vy: number;\n  size: number;\n  rot: number;\n  vrot: number;\n  color: string;\n  life: number;\n  maxLife: number;\n}\n\n/** Resolves a CSS colour (including shadcn --primary) into normalized [0..1] RGB for WebGL. */\nfunction resolvePrimaryRgb(el: HTMLElement): { base: Rgb; accent: Rgb } {\n  if (typeof document === \"undefined\") return TONE_PALETTES.coral;\n  const probe = document.createElement(\"canvas\");\n  probe.width = 1;\n  probe.height = 1;\n  const ctx = probe.getContext(\"2d\");\n  if (!ctx) return TONE_PALETTES.coral;\n  const raw = getComputedStyle(el).getPropertyValue(\"--primary\").trim();\n  ctx.fillStyle = raw || \"#305dde\";\n  ctx.fillRect(0, 0, 1, 1);\n  const d = ctx.getImageData(0, 0, 1, 1).data;\n  const base: Rgb = [d[0] / 255, d[1] / 255, d[2] / 255];\n  // If theme primary is near-black or near-white (default monochrome shadcn), blend a tasteful coral-violet lift\n  const sat = Math.max(...base) - Math.min(...base);\n  if (sat < 0.08) return TONE_PALETTES.coral;\n  const accent: Rgb = [\n    Math.min(1, base[0] * 0.55 + 0.45),\n    Math.min(1, base[1] * 0.55 + 0.45),\n    Math.min(1, base[2] * 0.55 + 0.45),\n  ];\n  return { base, accent };\n}\n\nfunction compileShader(gl: WebGL2RenderingContext, type: number, src: string) {\n  const s = gl.createShader(type);\n  if (!s) throw new Error(\"Failed to create shader\");\n  gl.shaderSource(s, src);\n  gl.compileShader(s);\n  if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {\n    const log = gl.getShaderInfoLog(s) || \"Unknown shader error\";\n    gl.deleteShader(s);\n    throw new Error(log);\n  }\n  return s;\n}\n\nexport interface TactileCreatureOptions {\n  material: ContextMaterial;\n  tone: ContextTone;\n  fullness: number;\n  mood: CreatureMood;\n  reduced: boolean;\n  onPokeAnnoyed?: () => void;\n}\n\nexport class TactileCreatureEngine {\n  private host: HTMLElement;\n  private glCanvas: HTMLCanvasElement;\n  private fxCanvas: HTMLCanvasElement;\n  private gl: WebGL2RenderingContext | null = null;\n  private fx: CanvasRenderingContext2D | null = null;\n  private program: WebGLProgram | null = null;\n  private vao: WebGLVertexArrayObject | null = null;\n  private u: Record<string, WebGLUniformLocation | null> = {};\n\n  private material: ContextMaterial;\n  private tone: ContextTone;\n  private palette: { base: Rgb; accent: Rgb } = TONE_PALETTES.coral;\n  private mood: CreatureMood;\n  private reduced: boolean;\n  private darkBg = false;\n  private onPokeAnnoyed?: () => void;\n\n  private fullnessSpring: LocalSpring;\n  private compactSqSpring = new LocalSpring(0, 140, 15);\n  private gulpSpring = new LocalSpring(0, 190, 14);\n  private hoverReliefSpring = new LocalSpring(0, 110, 14);\n  private lookX = new LocalSpring(0, 85, 14);\n  private lookY = new LocalSpring(0, 85, 14);\n  private tilt = new LocalSpring(0, 140, 14);\n  private jumpY = new LocalSpring(0, 210, 15);\n  private squash = new LocalSpring(0, 260, 16);\n  private stretchX = new LocalSpring(0, 220, 15);\n  private stretchY = new LocalSpring(0, 220, 15);\n  private innerX = new LocalSpring(0, 95, 7.5);\n  private innerY = new LocalSpring(0, 95, 7.5);\n\n  private time = 1.7;\n  private wobbleAmp = 0;\n  private wobblePhase = 0;\n  private blink = 0;\n  private blinkPhase = 0;\n  private nextBlink = 2.6;\n  private petHappy = 0;\n  private petPos: [number, number] = [0, 0];\n  private petDir: [number, number] = [0, 0];\n  private petStrength = 0;\n  private rubAccum = 0;\n  private dents: [number, number, number, number][] = [\n    [0, 0, 0.5, 0],\n    [0, 0, 0.5, 0],\n    [0, 0, 0.5, 0],\n    [0, 0, 0.5, 0],\n  ];\n  private dentCursor = 0;\n  private pokeTimes: number[] = [];\n\n  private pointerDown = false;\n  private dragStart: { x: number; y: number } | null = null;\n  private lastPtr: { x: number; y: number } | null = null;\n  private dragMoved = 0;\n\n  private particles: Particle[] = [];\n  private particleTimer = 0;\n  private dpr = 1;\n  private raf = 0;\n  private lastFrame = 0;\n  private active = true;\n  private disposed = false;\n\n  private ro: ResizeObserver | null = null;\n  private mo: MutationObserver | null = null;\n  private cleanups: (() => void)[] = [];\n\n  constructor(host: HTMLElement, opts: TactileCreatureOptions) {\n    this.host = host;\n    this.material = opts.material;\n    this.tone = opts.tone;\n    this.mood = opts.mood;\n    this.reduced = opts.reduced;\n    this.onPokeAnnoyed = opts.onPokeAnnoyed;\n    this.fullnessSpring = new LocalSpring(opts.fullness, 72, 11);\n\n    this.glCanvas = document.createElement(\"canvas\");\n    this.glCanvas.style.cssText = \"position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;\";\n    this.fxCanvas = document.createElement(\"canvas\");\n    this.fxCanvas.style.cssText = \"position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;\";\n    host.appendChild(this.glCanvas);\n    host.appendChild(this.fxCanvas);\n\n    this.fx = this.fxCanvas.getContext(\"2d\");\n    this._syncTheme();\n    this._initGl();\n    this._bindEvents();\n    this.resize();\n    this.render();\n    if (!this.reduced) this._startLoop();\n  }\n\n  private _syncTheme() {\n    this.darkBg = document.documentElement.classList.contains(\"dark\");\n    this.palette = this.tone === \"primary\" ? resolvePrimaryRgb(this.host) : TONE_PALETTES[this.tone];\n  }\n\n  private _initGl() {\n    const gl = this.glCanvas.getContext(\"webgl2\", {\n      alpha: true,\n      antialias: false,\n      premultipliedAlpha: true,\n      powerPreference: \"high-performance\",\n    });\n    if (!gl) return;\n    try {\n      const vs = compileShader(gl, gl.VERTEX_SHADER, VERT_SRC);\n      const fs = compileShader(gl, gl.FRAGMENT_SHADER, FRAG_SRC);\n      const prog = gl.createProgram();\n      if (!prog) return;\n      gl.attachShader(prog, vs);\n      gl.attachShader(prog, fs);\n      gl.linkProgram(prog);\n      if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {\n        gl.deleteProgram(prog);\n        return;\n      }\n      gl.deleteShader(vs);\n      gl.deleteShader(fs);\n      const vao = gl.createVertexArray();\n      gl.bindVertexArray(vao);\n      this.gl = gl;\n      this.program = prog;\n      this.vao = vao;\n      [\n        \"uResolution\", \"uTime\", \"uMaterial\", \"uMood\", \"uBaseColor\", \"uAccentColor\",\n        \"uDarkBg\", \"uClayStep\", \"uFullness\", \"uCompactSq\", \"uGulpOpen\", \"uHoverRelief\",\n        \"uLook\", \"uTilt\", \"uJumpY\", \"uSquash\", \"uStretch\", \"uWobbleAmp\", \"uWobblePhase\",\n        \"uBlink\", \"uPetHappy\", \"uPetPos\", \"uPetDir\", \"uPetStrength\",\n        \"uInnerOffsetX\", \"uInnerOffsetY\", \"uDents\",\n      ].forEach((name) => {\n        this.u[name] = gl.getUniformLocation(prog, name);\n      });\n    } catch {\n      this.gl = null;\n    }\n  }\n\n  private _bindEvents() {\n    const onGlobalMove = (e: PointerEvent) => {\n      if (this.reduced) return;\n      const rect = this.host.getBoundingClientRect();\n      if (rect.width <= 0) return;\n      const cx = rect.left + rect.width * 0.5;\n      const cy = rect.top + rect.height * 0.5;\n      const dx = (e.clientX - cx) / Math.max(rect.width * 1.15, 220);\n      const dy = -(e.clientY - cy) / Math.max(rect.height * 1.3, 180);\n      this.lookX.target = Math.max(-1, Math.min(1, dx));\n      this.lookY.target = Math.max(-1, Math.min(1, dy));\n\n      const lx = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n      const ly = -(((e.clientY - rect.top) / rect.height) * 2 - 1);\n      const inside = lx * lx * 0.6 + ly * ly < 0.65;\n      if (inside && !this.pointerDown && this.mood !== \"compacting\") {\n        if (this.lastPtr) {\n          const vx = lx - this.lastPtr.x;\n          const vy = ly - this.lastPtr.y;\n          const speed = Math.hypot(vx, vy);\n          if (speed > 0.008 && speed < 0.30) {\n            this.rubAccum = Math.min(1.6, this.rubAccum + speed * 2.3);\n            this.petPos = [lx * 0.72, ly * 0.56];\n            this.petDir = [\n              this.petDir[0] * 0.5 + (vx / Math.max(speed, 0.01)) * 1.2,\n              this.petDir[1] * 0.5 + (vy / Math.max(speed, 0.01)) * 1.2,\n            ];\n            this.petStrength = Math.min(1.0, this.petStrength + 0.36);\n            if (this.rubAccum > 0.52) {\n              this.petHappy = Math.min(1.0, this.petHappy + 0.16);\n              this.tilt.target = lx * 0.14;\n            }\n          }\n        }\n      }\n      this.lastPtr = { x: lx, y: ly };\n    };\n\n    const onDown = (e: PointerEvent) => {\n      const rect = this.host.getBoundingClientRect();\n      const lx = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n      const ly = -(((e.clientY - rect.top) / rect.height) * 2 - 1);\n      this.pointerDown = true;\n      this.dragStart = { x: lx, y: ly };\n      this.dragMoved = 0;\n      this.host.setPointerCapture?.(e.pointerId);\n      this.squash.target = -0.14;\n      this._pokeAt(lx, ly, e.timeStamp);\n    };\n\n    const onMove = (e: PointerEvent) => {\n      if (!this.pointerDown || !this.dragStart) return;\n      const rect = this.host.getBoundingClientRect();\n      const lx = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n      const ly = -(((e.clientY - rect.top) / rect.height) * 2 - 1);\n      const dx = lx - this.dragStart.x;\n      const dy = ly - this.dragStart.y;\n      const dist = Math.hypot(dx, dy);\n      this.dragMoved = Math.max(this.dragMoved, dist);\n\n      const pullX = Math.max(-0.46, Math.min(0.46, dx * 0.65));\n      const pullY = Math.max(-0.36, Math.min(0.42, dy * 0.58));\n      this.stretchX.target = pullX;\n      this.stretchY.target = pullY;\n      this.innerX.target = pullX * 0.65;\n      this.innerY.target = pullY * 0.65;\n      this.squash.target = Math.min(0.24, dist * 0.28 - 0.08);\n      this.tilt.target = -pullX * 0.38;\n      this.petPos = [lx * 0.70, ly * 0.54];\n      this.petDir = [dx * 2.4, dy * 2.4];\n      this.petStrength = 1.0;\n    };\n\n    const onUp = () => {\n      if (!this.pointerDown) return;\n      this.pointerDown = false;\n      if (this.dragMoved > 0.14) {\n        this.innerX.impulse(-this.stretchX.x * 13.5);\n        this.innerY.impulse(-this.stretchY.x * 13.5);\n        this.squash.impulse(4.4);\n        this.wobbleAmp = 1.3;\n      }\n      this.stretchX.target = 0;\n      this.stretchY.target = 0;\n      this.innerX.target = 0;\n      this.innerY.target = 0;\n      this.squash.target = 0;\n      this.tilt.target = 0;\n      this.dragStart = null;\n    };\n\n    window.addEventListener(\"pointermove\", onGlobalMove, { passive: true });\n    this.host.addEventListener(\"pointerdown\", onDown);\n    this.host.addEventListener(\"pointermove\", onMove);\n    this.host.addEventListener(\"pointerup\", onUp);\n    this.host.addEventListener(\"pointercancel\", onUp);\n    this.cleanups.push(() => {\n      window.removeEventListener(\"pointermove\", onGlobalMove);\n      this.host.removeEventListener(\"pointerdown\", onDown);\n      this.host.removeEventListener(\"pointermove\", onMove);\n      this.host.removeEventListener(\"pointerup\", onUp);\n      this.host.removeEventListener(\"pointercancel\", onUp);\n    });\n\n    this.ro = new ResizeObserver(() => {\n      this.resize();\n      if (this.reduced) this.render();\n    });\n    this.ro.observe(this.host);\n\n    this.mo = new MutationObserver(() => {\n      this._syncTheme();\n      if (this.reduced) this.render();\n    });\n    this.mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\"] });\n  }\n\n  private _pokeAt(nx: number, ny: number, stamp: number) {\n    this.squash.impulse(-5.0);\n    this.jumpY.impulse(0.75);\n    this.wobbleAmp = Math.min(1.4, this.wobbleAmp + 1.0);\n    this.innerX.impulse(-nx * 4.8);\n    this.innerY.impulse(-ny * 4.8);\n    this.tilt.impulse(-nx * 2.5);\n\n    const sc = Math.max(0.65, 0.64 + 0.8 * Math.min(1, this.fullnessSpring.x));\n    const zApprox = Math.sqrt(Math.max(0.06, 0.56 * 0.56 - (nx * 0.55) ** 2 - (ny * 0.45) ** 2));\n    this.dents[this.dentCursor] = [(nx * 0.72) / sc, (ny * 0.52) / sc, zApprox, 1.0];\n    this.dentCursor = (this.dentCursor + 1) % 4;\n\n    this.petPos = [nx * 0.68, ny * 0.52];\n    this.petDir = [nx * 1.4, ny * 1.4];\n    this.petStrength = 1.0;\n\n    this.pokeTimes = this.pokeTimes.filter((t) => stamp - t < 2200);\n    this.pokeTimes.push(stamp);\n    if (this.pokeTimes.length >= 4) {\n      this.pokeTimes = [];\n      this._spawnSteam(5);\n      this.onPokeAnnoyed?.();\n    }\n    if (this.reduced) this.render();\n  }\n\n  setProps(next: {\n    material: ContextMaterial;\n    tone: ContextTone;\n    fullness: number;\n    mood: CreatureMood;\n    hoverRelief: boolean;\n    reduced: boolean;\n  }) {\n    const matChanged = next.material !== this.material;\n    const toneChanged = next.tone !== this.tone;\n    const prevMood = this.mood;\n\n    this.material = next.material;\n    this.tone = next.tone;\n    this.mood = next.mood;\n    this.reduced = next.reduced;\n    this.fullnessSpring.target = next.fullness;\n    this.compactSqSpring.target = next.mood === \"compacting\" ? 1 : 0;\n    this.hoverReliefSpring.target = next.hoverRelief ? 1 : 0;\n\n    if (toneChanged) this._syncTheme();\n    if (matChanged) {\n      this.squash.impulse(-3.0);\n      this.wobbleAmp = Math.max(this.wobbleAmp, 0.85);\n    }\n    if (prevMood !== \"compacting\" && next.mood === \"compacting\") {\n      this._spawnSteam(3);\n    }\n    if (prevMood === \"compacting\" && next.mood === \"relieved\") {\n      this.jumpY.impulse(2.8);\n      this.squash.impulse(4.2);\n      this.wobbleAmp = 1.1;\n      this._spawnSparkles(18);\n      this._spawnSteam(4);\n    }\n    if (this.reduced) {\n      this.fullnessSpring.x = next.fullness;\n      this.compactSqSpring.x = next.mood === \"compacting\" ? 1 : 0;\n      this.hoverReliefSpring.x = next.hoverRelief ? 1 : 0;\n      this.render();\n    }\n  }\n\n  /** Triggered when a file/item is fed into the context window. */\n  triggerGulp(weight = 0.25) {\n    this.gulpSpring.x = Math.max(this.gulpSpring.x, 0.95);\n    this.gulpSpring.target = 0;\n    this.jumpY.impulse(1.4 + weight * 1.4);\n    this.squash.impulse(3.2 + weight * 2.5);\n    this.wobbleAmp = Math.min(1.4, this.wobbleAmp + 0.75 + weight * 0.5);\n    this.innerY.impulse(-3.2);\n    if (this.reduced) this.render();\n  }\n\n  /** Triggered when an item is dropped from context. */\n  triggerRelief() {\n    this.jumpY.impulse(2.0);\n    this.squash.impulse(3.0);\n    this.wobbleAmp = Math.min(1.2, this.wobbleAmp + 0.7);\n    this.petHappy = Math.max(this.petHappy, 0.85);\n    this._spawnSparkles(8);\n    if (this.reduced) this.render();\n  }\n\n  /** Triggered when a file bounces off an already-stuffed context window. */\n  triggerReject() {\n    this.tilt.impulse(5.5);\n    this.stretchX.impulse(3.8);\n    this.squash.impulse(-4.5);\n    this.wobbleAmp = 1.4;\n    this.innerX.impulse(5.5);\n    this._spawnSteam(6);\n    if (this.reduced) this.render();\n  }\n\n  setActive(active: boolean) {\n    this.active = active;\n    if (active && !this.reduced && !this.raf && !this.disposed) {\n      this._startLoop();\n    } else if (!active && this.raf) {\n      cancelAnimationFrame(this.raf);\n      this.raf = 0;\n    }\n  }\n\n  resize() {\n    const rect = this.host.getBoundingClientRect();\n    const w = Math.max(120, Math.round(rect.width || 360));\n    const h = Math.max(100, Math.round(rect.height || 200));\n    const dpr = Math.min(window.devicePixelRatio || 1, 1.75);\n    const pw = Math.round(w * dpr);\n    const ph = Math.round(h * dpr);\n    if (this.glCanvas.width !== pw || this.glCanvas.height !== ph) {\n      this.glCanvas.width = pw;\n      this.glCanvas.height = ph;\n      this.fxCanvas.width = pw;\n      this.fxCanvas.height = ph;\n      this.gl?.viewport(0, 0, pw, ph);\n    }\n    this.dpr = dpr;\n  }\n\n  private _spawnSteam(count: number) {\n    for (let i = 0; i < count; i++) {\n      this.particles.push({\n        kind: \"steam\",\n        x: 0.5 + (Math.random() - 0.5) * 0.26,\n        y: 0.20 + (Math.random() - 0.5) * 0.08,\n        vx: (Math.random() - 0.5) * 0.14,\n        vy: -0.22 - Math.random() * 0.14,\n        size: 12 + Math.random() * 14,\n        rot: 0,\n        vrot: 0,\n        color: \"\",\n        life: 0,\n        maxLife: 0.95 + Math.random() * 0.45,\n      });\n    }\n  }\n\n  private _spawnSparkles(count: number) {\n    const cols = [\"#305dde\", \"#10b981\", \"#f59e0b\", \"#ec4899\", \"#8b5cf6\"];\n    for (let i = 0; i < count; i++) {\n      const ang = -Math.PI * 0.5 + (Math.random() - 0.5) * 2.2;\n      const spd = 0.28 + Math.random() * 0.48;\n      this.particles.push({\n        kind: \"sparkle\",\n        x: 0.5 + (Math.random() - 0.5) * 0.24,\n        y: 0.36 + (Math.random() - 0.5) * 0.12,\n        vx: Math.cos(ang) * spd,\n        vy: Math.sin(ang) * spd - 0.12,\n        size: 4 + Math.random() * 5,\n        rot: Math.random() * Math.PI * 2,\n        vrot: (Math.random() - 0.5) * 10,\n        color: cols[i % cols.length],\n        life: 0,\n        maxLife: 0.85 + Math.random() * 0.55,\n      });\n    }\n  }\n\n  private _startLoop() {\n    this.lastFrame = performance.now();\n    const tick = (now: number) => {\n      if (this.disposed || !this.active || this.reduced) {\n        this.raf = 0;\n        return;\n      }\n      const dt = Math.min(0.05, Math.max(0.001, (now - this.lastFrame) / 1000));\n      this.lastFrame = now;\n      this._step(dt);\n      this.render();\n      this.raf = requestAnimationFrame(tick);\n    };\n    this.raf = requestAnimationFrame(tick);\n  }\n\n  private _step(dt: number) {\n    this.time += dt;\n\n    // Periodic steam when stuffed >= 88% or rejected\n    this.particleTimer += dt;\n    if ((this.mood === \"stuffed\" || this.mood === \"rejected\") && this.particleTimer > 0.34) {\n      this.particleTimer = 0;\n      this._spawnSteam(1);\n    }\n\n    // Natural blinking\n    this.nextBlink -= dt;\n    if (this.nextBlink <= 0) {\n      this.nextBlink = 2.4 + Math.random() * 3.2;\n      this.blinkPhase = 0.001;\n    }\n    if (this.blinkPhase > 0) {\n      this.blinkPhase += dt * 7.8;\n      if (this.blinkPhase >= Math.PI) {\n        this.blinkPhase = 0;\n        this.blink = 0;\n      } else {\n        this.blink = Math.sin(this.blinkPhase);\n      }\n    }\n\n    this.rubAccum = Math.max(0, this.rubAccum - dt * 0.72);\n    if (this.rubAccum < 0.25) {\n      this.petHappy = Math.max(0, this.petHappy - dt * 1.4);\n      if (!this.pointerDown) this.tilt.target = 0;\n    }\n    this.petStrength *= Math.exp(-dt * 2.2);\n    this.wobbleAmp *= Math.exp(-dt * (this.material === \"jelly\" ? 2.4 : 4.2));\n    this.wobblePhase += dt * (this.material === \"jelly\" ? 14.5 : 11.5);\n\n    for (let i = 0; i < 4; i++) {\n      if (this.dents[i][3] > 0) {\n        this.dents[i][3] = Math.max(0, this.dents[i][3] - dt * 0.26);\n      }\n    }\n\n    this.fullnessSpring.step(dt);\n    this.compactSqSpring.step(dt);\n    this.gulpSpring.step(dt);\n    this.hoverReliefSpring.step(dt);\n    this.lookX.step(dt);\n    this.lookY.step(dt);\n    this.tilt.step(dt);\n    this.jumpY.step(dt);\n    this.squash.step(dt);\n    this.stretchX.step(dt);\n    this.stretchY.step(dt);\n    this.innerX.step(dt);\n    this.innerY.step(dt);\n\n    for (let i = this.particles.length - 1; i >= 0; i--) {\n      const p = this.particles[i];\n      p.life += dt;\n      if (p.life >= p.maxLife) {\n        this.particles.splice(i, 1);\n        continue;\n      }\n      if (p.kind === \"sparkle\") {\n        p.vy += 0.85 * dt;\n        p.vx *= Math.exp(-dt * 1.4);\n        p.rot += p.vrot * dt;\n      } else {\n        p.vx += Math.sin(this.time * 4 + i) * 0.05 * dt;\n        p.size += 11 * dt;\n      }\n      p.x += p.vx * dt;\n      p.y += p.vy * dt;\n    }\n  }\n\n  render() {\n    const gl = this.gl;\n    if (gl && this.program && this.vao) {\n      gl.clearColor(0, 0, 0, 0);\n      gl.clear(gl.COLOR_BUFFER_BIT);\n      gl.useProgram(this.program);\n      gl.bindVertexArray(this.vao);\n\n      gl.uniform2f(this.u.uResolution, this.glCanvas.width, this.glCanvas.height);\n      gl.uniform1f(this.u.uTime, this.time);\n      gl.uniform1i(this.u.uMaterial, MATERIAL_ID[this.material]);\n      gl.uniform1i(this.u.uMood, MOOD_ID[this.mood]);\n      gl.uniform3fv(this.u.uBaseColor, this.palette.base);\n      gl.uniform3fv(this.u.uAccentColor, this.palette.accent);\n      gl.uniform1f(this.u.uDarkBg, this.darkBg ? 1.0 : 0.0);\n      gl.uniform1f(this.u.uClayStep, 1.0);\n\n      gl.uniform1f(this.u.uFullness, this.fullnessSpring.x);\n      gl.uniform1f(this.u.uCompactSq, this.compactSqSpring.x);\n      gl.uniform1f(this.u.uGulpOpen, Math.max(0, this.gulpSpring.x));\n      gl.uniform1f(this.u.uHoverRelief, this.hoverReliefSpring.x);\n\n      gl.uniform2f(this.u.uLook, this.lookX.x, this.lookY.x);\n      gl.uniform1f(this.u.uTilt, this.tilt.x);\n      gl.uniform1f(this.u.uJumpY, this.jumpY.x);\n      gl.uniform1f(this.u.uSquash, this.squash.x);\n      gl.uniform2f(this.u.uStretch, this.stretchX.x, this.stretchY.x);\n      gl.uniform1f(this.u.uWobbleAmp, this.wobbleAmp);\n      gl.uniform1f(this.u.uWobblePhase, this.wobblePhase);\n      gl.uniform1f(this.u.uBlink, this.blink);\n      gl.uniform1f(this.u.uPetHappy, this.petHappy);\n      gl.uniform2f(this.u.uPetPos, this.petPos[0], this.petPos[1]);\n      gl.uniform2f(this.u.uPetDir, this.petDir[0], this.petDir[1]);\n      gl.uniform1f(this.u.uPetStrength, this.petStrength);\n      gl.uniform1f(this.u.uInnerOffsetX, this.innerX.x);\n      gl.uniform1f(this.u.uInnerOffsetY, this.innerY.x);\n\n      const dentFlat = new Float32Array(16);\n      for (let i = 0; i < 4; i++) {\n        dentFlat[i * 4 + 0] = this.dents[i][0];\n        dentFlat[i * 4 + 1] = this.dents[i][1];\n        dentFlat[i * 4 + 2] = this.dents[i][2];\n        dentFlat[i * 4 + 3] = this.dents[i][3];\n      }\n      gl.uniform4fv(this.u.uDents, dentFlat);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    }\n\n    // 2D overlay particles (steam puffs & compaction sparkles)\n    const ctx = this.fx;\n    if (!ctx) return;\n    const w = this.fxCanvas.width;\n    const h = this.fxCanvas.height;\n    ctx.clearRect(0, 0, w, h);\n    if (!this.particles.length) return;\n    const s = this.dpr;\n    for (const p of this.particles) {\n      const prog = p.life / p.maxLife;\n      const alpha = Math.sin(Math.min(1, prog * 3.5) * Math.PI * 0.5) * (1 - prog * prog);\n      const px = p.x * w;\n      const py = p.y * h;\n      ctx.save();\n      ctx.globalAlpha = Math.max(0, Math.min(1, alpha));\n      if (p.kind === \"steam\") {\n        const rad = p.size * s;\n        const grad = ctx.createRadialGradient(px, py, rad * 0.1, px, py, rad);\n        const col = this.darkBg ? \"235, 238, 248\" : \"108, 110, 124\";\n        grad.addColorStop(0, `rgba(${col}, 0.58)`);\n        grad.addColorStop(0.55, `rgba(${col}, 0.24)`);\n        grad.addColorStop(1, `rgba(${col}, 0)`);\n        ctx.fillStyle = grad;\n        ctx.beginPath();\n        ctx.arc(px, py, rad, 0, Math.PI * 2);\n        ctx.fill();\n      } else {\n        ctx.translate(px, py);\n        ctx.rotate(p.rot);\n        ctx.fillStyle = p.color;\n        const cw = p.size * s;\n        const ch = cw * (0.45 + 0.35 * Math.abs(Math.cos(p.rot * 2)));\n        ctx.fillRect(-cw * 0.5, -ch * 0.5, cw, ch);\n      }\n      ctx.restore();\n    }\n  }\n\n  dispose() {\n    this.disposed = true;\n    if (this.raf) {\n      cancelAnimationFrame(this.raf);\n      this.raf = 0;\n    }\n    this.ro?.disconnect();\n    this.mo?.disconnect();\n    this.cleanups.forEach((fn) => fn());\n    this.cleanups = [];\n    if (this.gl) {\n      if (this.program) this.gl.deleteProgram(this.program);\n      if (this.vao) this.gl.deleteVertexArray(this.vao);\n    }\n    this.glCanvas.remove();\n    this.fxCanvas.remove();\n  }\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · context-window · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/context-window. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}