Преглед изворни кода

feat: eye tracking demo with iris-ratio + head-pose hybrid algorithm

root пре 5 месеци
комит
a710135349
2 измењених фајлова са 1416 додато и 0 уклоњено
  1. 130 0
      README.md
  2. 1286 0
      index.html

+ 130 - 0
README.md

@@ -0,0 +1,130 @@
+# Eye Tracking Demo - 视控追踪演示
+
+纯前端网页应用,通过 PC 前置摄像头实时捕捉虹膜位置,控制屏幕上的光球跟随视线移动。
+
+**在线体验:** https://gogs.wxapp.info/eye-demo/
+
+> 需要浏览器允许摄像头权限(HTTPS 环境下 getUserMedia 才可用)。
+
+---
+
+## 技术栈
+
+| 组件 | 技术 |
+|------|------|
+| 人脸/虹膜检测 | [MediaPipe Face Mesh](https://google.github.io/mediapipe/solutions/face_mesh)(WASM,浏览器本地推理) |
+| 面部关键点 | 478 点面部网格,含 468-477 虹膜轮廓 |
+| 视线估计算法 | Iris Ratio + Head Pose 混合(见下方算法说明) |
+| 信号平滑 | 一维 Kalman Filter(低延迟调参) |
+| 渲染 | Canvas 2D(光球 + 拖尾 + 面部网格叠加) |
+| 依赖 | 零构建,单 HTML 文件,CDN 引入 MediaPipe |
+
+---
+
+## 算法说明
+
+### 1. Iris Ratio(虹膜比例法)
+
+参考成熟开源项目 [t0mdicks0n/gaze-cursor](https://github.com/t0mdicks0n/gaze-cursor) 的方法,不使用传统的 iris_center - eye_center 偏移量(信号极小,±0.05~0.15),而是计算虹膜在眼眶中的**相对位置比例**:
+
+```
+ratioX = (iris.x - inner_corner.x) / (outer_corner.x - inner_corner.x)
+```
+
+结果天然在 [0, 1] 范围内,不受脸距摄像头远近影响。
+
+**使用的 MediaPipe Face Mesh 关键点:**
+
+```
+左眼:外角(33)  内角(133)  上眼睑(159)  下眼睑(145)  虹膜中心(468)
+右眼:外角(362) 内角(263)  上眼睑(386)  下眼睑(374)  虹膜中心(473)
+```
+
+### 2. Head Pose(头部姿态信号)
+
+虹膜纵向偏移量本身较小,单纯看瞳孔上下移动范围有限。因此额外提取头部姿态信号:
+
+- **横向**:鼻尖 (landmark 1) 在画面中的 x 位置
+- **纵向**:鼻尖相对于面部上下边界 (landmark 10/152) 中点的偏移,除以面部高度归一化
+
+### 3. 混合加权
+
+最终屏幕坐标 = 虹膜信号 × 权重 + 头部信号 × (1 - 权重)
+
+```
+IRIS_WEIGHT_X = 0.65   # 横向以虹膜为主
+IRIS_WEIGHT_Y = 0.30   # 纵向以头部为主(更大范围)
+```
+
+头部信号额外做了放大(横向 3x,纵向 2.5x),虹膜纵向也放大 2x。
+
+### 4. Kalman 滤波
+
+对混合后的 [0,1] 坐标做一维 Kalman 平滑,参数调优为**低延迟**优先:
+
+- R = 0.015(测量噪声,低 = 更信任原始数据 → 响应更快)
+- Q = 0.006(过程噪声,高 = 允许更多变化 → 抖动更少平滑)
+
+### 5. 镜像处理
+
+前置摄像头通过 CSS `transform: scaleX(-1)` 做视觉镜像。MediaPipe 接收的是未镜像的原始图像,因此在映射时对 X 坐标做反向处理,确保用户"看右边 → 球往右走"。
+
+---
+
+## 文件结构
+
+```
+eye-tracking-demo/
+├── index.html    # 唯一文件(HTML + CSS + JS 全部内联)
+└── README.md     # 本文档
+```
+
+---
+
+## 部署方式
+
+### Nginx 静态文件(当前方案)
+
+```nginx
+location /eye-demo/ {
+    alias /lio/projects/eye-tracking-demo/;
+    index index.html;
+    try_files $uri $uri/ /eye-demo/index.html;
+}
+```
+
+### 任意静态服务器
+
+直接把 `index.html` 放到任意支持 HTTPS 的 Web 服务器目录下即可。不依赖后端、不依赖构建工具。
+
+---
+
+## 浏览器兼容性
+
+| 浏览器 | 支持 |
+|--------|------|
+| Chrome 80+ | OK |
+| Edge 80+ | OK |
+| Firefox 75+ | OK |
+| Safari 14+ | OK(需 HTTPS) |
+
+需要 HTTPS 环境(getUserMedia 安全要求)。不支持 HTTP 访问。
+
+---
+
+## 已知限制
+
+1. **精度上限**:前置摄像头分辨率有限,虹膜检测精度不如专用眼动仪(如 Tobii、Pupil Labs)
+2. **头部依赖**:纵向方向依赖头部移动辅助,纯眼球上下转动范围有限
+3. **光线敏感**:逆光或暗光环境下虹膜检测准确度下降
+4. **无校准**:当前为免校准方案,不同用户的虹膜比例分布略有差异,通过混合头部信号弥补
+5. **MediaPipe CDN**:首次加载需下载 WASM + 模型文件(约 4MB),后续浏览器缓存
+
+---
+
+## 参考资料
+
+- [t0mdicks0n/gaze-cursor](https://github.com/t0mdicks0n/gaze-cursor) — MediaPipe 虹膜追踪 + 线性回归校准
+- [MediaPipe Face Mesh](https://google.github.io/mediapipe/solutions/face_mesh) — Google 人脸网格方案
+- [WebGazer.js](https://github.com/webgazer/webgazer.js) — 浏览器端视线追踪(基于回归模型)
+- [Pupil Labs](https://github.com/pupil-labs) — 开源眼动追踪硬件/软件方案

+ 1286 - 0
index.html

@@ -0,0 +1,1286 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1.0" />
+<title>Eye Tracking Demo · MediaPipe Iris</title>
+<style>
+  :root {
+    --bg: #0a0a1a;
+    --grid: rgba(0, 255, 255, 0.04);
+    --cyan: #00e5ff;
+    --cyan-dim: #00b8d4;
+    --text: #e0f7fa;
+    --text-dim: #80deea;
+    --danger: #ff5252;
+    --ok: #00e676;
+    --panel: rgba(10, 20, 40, 0.55);
+    --panel-border: rgba(0, 229, 255, 0.35);
+  }
+
+  * { box-sizing: border-box; margin: 0; padding: 0; }
+
+  html, body {
+    width: 100%;
+    height: 100%;
+    overflow: hidden;
+    background: var(--bg);
+    color: var(--text);
+    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "SF Mono", "Roboto Mono", Menlo, Consolas, monospace;
+    -webkit-font-smoothing: antialiased;
+    user-select: none;
+  }
+
+  body {
+    background-color: var(--bg);
+    background-image:
+      linear-gradient(var(--grid) 1px, transparent 1px),
+      linear-gradient(90deg, var(--grid) 1px, transparent 1px);
+    background-size: 40px 40px;
+    background-position: -1px -1px;
+  }
+
+  /* Subtle radial vignette */
+  body::before {
+    content: "";
+    position: fixed;
+    inset: 0;
+    pointer-events: none;
+    background: radial-gradient(ellipse at center, transparent 0%, rgba(0,0,0,0.6) 100%);
+    z-index: 1;
+  }
+
+  #stage {
+    position: fixed;
+    inset: 0;
+    z-index: 2;
+    cursor: crosshair;
+  }
+
+  /* ---------- Webcam preview ---------- */
+  #preview-wrap {
+    position: fixed;
+    left: 24px;
+    bottom: 64px;
+    width: 240px;
+    height: 180px;
+    border-radius: 14px;
+    overflow: hidden;
+    background: #000;
+    border: 1px solid var(--panel-border);
+    box-shadow:
+      0 0 0 1px rgba(0, 229, 255, 0.08) inset,
+      0 8px 32px rgba(0, 229, 255, 0.12),
+      0 2px 8px rgba(0, 0, 0, 0.6);
+    z-index: 10;
+    backdrop-filter: blur(4px);
+  }
+
+  #preview-wrap::before {
+    content: "LIVE · IRIS";
+    position: absolute;
+    top: 8px;
+    left: 10px;
+    font-size: 10px;
+    letter-spacing: 0.15em;
+    color: var(--cyan);
+    text-shadow: 0 0 8px rgba(0, 229, 255, 0.7);
+    z-index: 12;
+    pointer-events: none;
+  }
+
+  #preview-wrap::after {
+    content: "";
+    position: absolute;
+    inset: 0;
+    border-radius: 14px;
+    pointer-events: none;
+    box-shadow: 0 0 24px rgba(0, 229, 255, 0.18) inset;
+    z-index: 11;
+  }
+
+  #webcam, #overlay {
+    position: absolute;
+    inset: 0;
+    width: 100%;
+    height: 100%;
+  }
+
+  #webcam {
+    object-fit: cover;
+    transform: scaleX(-1); /* mirrored */
+    z-index: 1;
+  }
+
+  #overlay {
+    z-index: 2;
+    pointer-events: none;
+  }
+
+  /* ---------- Status bar ---------- */
+  #status-bar {
+    position: fixed;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    height: 48px;
+    display: flex;
+    align-items: center;
+    gap: 24px;
+    padding: 0 20px;
+    background: var(--panel);
+    border-top: 1px solid var(--panel-border);
+    backdrop-filter: blur(8px);
+    font-size: 12px;
+    letter-spacing: 0.05em;
+    z-index: 20;
+    color: var(--text-dim);
+  }
+
+  .stat {
+    display: flex;
+    align-items: center;
+    gap: 8px;
+  }
+
+  .stat .label {
+    color: rgba(128, 222, 234, 0.55);
+    text-transform: uppercase;
+    font-size: 10px;
+    letter-spacing: 0.18em;
+  }
+
+  .stat .value {
+    color: var(--cyan);
+    text-shadow: 0 0 8px rgba(0, 229, 255, 0.5);
+    font-variant-numeric: tabular-nums;
+    min-width: 60px;
+  }
+
+  .stat .value.ok { color: var(--ok); text-shadow: 0 0 8px rgba(0, 230, 118, 0.4); }
+  .stat .value.warn { color: #ffb74d; text-shadow: 0 0 8px rgba(255, 183, 77, 0.4); }
+  .stat .value.err { color: var(--danger); text-shadow: 0 0 8px rgba(255, 82, 82, 0.4); }
+
+  .dot {
+    width: 8px;
+    height: 8px;
+    border-radius: 50%;
+    background: var(--cyan-dim);
+    box-shadow: 0 0 8px var(--cyan-dim);
+    animation: pulse 1.6s ease-in-out infinite;
+  }
+  .dot.ok { background: var(--ok); box-shadow: 0 0 10px var(--ok); }
+  .dot.warn { background: #ffb74d; box-shadow: 0 0 10px #ffb74d; }
+  .dot.err { background: var(--danger); box-shadow: 0 0 10px var(--danger); animation: none; }
+
+  @keyframes pulse {
+    0%, 100% { opacity: 1; transform: scale(1); }
+    50% { opacity: 0.4; transform: scale(0.8); }
+  }
+
+  /* ---------- Title ---------- */
+  #title {
+    position: fixed;
+    top: 18px;
+    left: 24px;
+    z-index: 15;
+    font-size: 11px;
+    letter-spacing: 0.3em;
+    color: rgba(0, 229, 255, 0.7);
+    text-shadow: 0 0 8px rgba(0, 229, 255, 0.4);
+  }
+  #title .accent { color: var(--cyan); }
+
+  /* ---------- Loading overlay ---------- */
+  #loader {
+    position: fixed;
+    inset: 0;
+    z-index: 100;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    gap: 28px;
+    background: rgba(10, 10, 26, 0.92);
+    backdrop-filter: blur(6px);
+    transition: opacity 0.5s ease, visibility 0.5s;
+  }
+  #loader.hidden {
+    opacity: 0;
+    visibility: hidden;
+  }
+
+  .spinner {
+    width: 64px;
+    height: 64px;
+    border: 2px solid rgba(0, 229, 255, 0.15);
+    border-top-color: var(--cyan);
+    border-right-color: var(--cyan);
+    border-radius: 50%;
+    animation: spin 1s linear infinite;
+    box-shadow: 0 0 24px rgba(0, 229, 255, 0.3);
+  }
+
+  @keyframes spin {
+    to { transform: rotate(360deg); }
+  }
+
+  .loader-text {
+    font-size: 12px;
+    letter-spacing: 0.4em;
+    text-transform: uppercase;
+    color: var(--cyan);
+    text-shadow: 0 0 10px rgba(0, 229, 255, 0.6);
+  }
+  .loader-sub {
+    font-size: 11px;
+    color: var(--text-dim);
+    letter-spacing: 0.15em;
+    max-width: 320px;
+    text-align: center;
+    line-height: 1.6;
+  }
+
+  /* ---------- Error overlay ---------- */
+  #error-overlay {
+    position: fixed;
+    inset: 0;
+    z-index: 90;
+    display: none;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    gap: 18px;
+    background: rgba(10, 10, 26, 0.88);
+    backdrop-filter: blur(6px);
+    padding: 40px;
+    text-align: center;
+  }
+  #error-overlay.show { display: flex; }
+
+  #error-overlay .icon {
+    font-size: 48px;
+    filter: drop-shadow(0 0 12px rgba(255, 82, 82, 0.6));
+  }
+  #error-overlay h2 {
+    font-size: 18px;
+    letter-spacing: 0.15em;
+    color: var(--danger);
+    text-transform: uppercase;
+  }
+  #error-overlay p {
+    color: var(--text-dim);
+    font-size: 13px;
+    max-width: 520px;
+    line-height: 1.7;
+  }
+  #error-overlay button {
+    margin-top: 12px;
+    padding: 10px 24px;
+    background: transparent;
+    border: 1px solid var(--cyan);
+    color: var(--cyan);
+    font-family: inherit;
+    font-size: 12px;
+    letter-spacing: 0.2em;
+    text-transform: uppercase;
+    cursor: pointer;
+    border-radius: 6px;
+    transition: background 0.2s, box-shadow 0.2s;
+  }
+  #error-overlay button:hover {
+    background: rgba(0, 229, 255, 0.1);
+    box-shadow: 0 0 16px rgba(0, 229, 255, 0.3);
+  }
+
+  /* ---------- Debug panel (top-left, collapsible) ---------- */
+  #debug-panel {
+    position: fixed;
+    top: 48px;
+    left: 24px;
+    z-index: 30;
+    width: 260px;
+    max-width: calc(100vw - 48px);
+    background: var(--panel);
+    border: 1px solid var(--panel-border);
+    border-radius: 10px;
+    backdrop-filter: blur(8px);
+    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
+    font-size: 11px;
+    color: var(--text);
+    overflow: hidden;
+    transition: max-height 0.25s ease;
+  }
+  #debug-panel.collapsed { max-height: 32px; }
+  #debug-panel.expanded { max-height: 480px; }
+
+  #debug-header {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    padding: 8px 12px;
+    cursor: pointer;
+    user-select: none;
+    background: rgba(0, 229, 255, 0.06);
+    border-bottom: 1px solid var(--panel-border);
+    font-size: 10px;
+    letter-spacing: 0.2em;
+    text-transform: uppercase;
+    color: var(--cyan);
+  }
+  #debug-panel.collapsed #debug-body { display: none; }
+  #debug-panel.collapsed #debug-header { border-bottom: none; }
+  #debug-toggle {
+    font-family: inherit;
+    color: var(--cyan);
+    font-size: 14px;
+    line-height: 1;
+  }
+
+  #debug-body {
+    padding: 10px 12px 12px;
+    display: flex;
+    flex-direction: column;
+    gap: 6px;
+    max-height: 440px;
+    overflow-y: auto;
+  }
+
+  .dbg-row {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    gap: 8px;
+    font-size: 11px;
+    line-height: 1.4;
+    word-break: break-all;
+  }
+  .dbg-row .k {
+    color: rgba(128, 222, 234, 0.7);
+    text-transform: uppercase;
+    letter-spacing: 0.1em;
+    font-size: 10px;
+    flex-shrink: 0;
+  }
+  .dbg-row .v {
+    color: var(--text);
+    text-align: right;
+    font-variant-numeric: tabular-nums;
+  }
+  .dbg-row .v.ok   { color: var(--ok); }
+  .dbg-row .v.warn { color: #ffb74d; }
+  .dbg-row .v.err  { color: var(--danger); }
+  .dbg-row .v.run  { color: var(--cyan); }
+
+  #debug-err {
+    margin-top: 6px;
+    padding: 8px 10px;
+    background: rgba(255, 82, 82, 0.08);
+    border: 1px solid rgba(255, 82, 82, 0.35);
+    border-radius: 6px;
+    color: var(--danger);
+    font-size: 10px;
+    line-height: 1.5;
+    word-break: break-word;
+    display: none;
+    max-height: 120px;
+    overflow-y: auto;
+  }
+  #debug-err.show { display: block; }
+</style>
+</head>
+<body>
+
+<canvas id="stage"></canvas>
+
+<div id="title">
+  EYE · TRACK <span class="accent">//</span> PUPIL GAZE
+</div>
+
+<div id="preview-wrap" aria-label="Webcam preview with face mesh overlay">
+  <video id="webcam" autoplay playsinline muted></video>
+  <canvas id="overlay" width="240" height="180"></canvas>
+</div>
+
+<div id="status-bar">
+  <div class="stat">
+    <span class="dot" id="status-dot"></span>
+    <span class="label">Status</span>
+    <span class="value" id="status-text">INIT</span>
+  </div>
+  <div class="stat">
+    <span class="label">FPS</span>
+    <span class="value" id="fps">--</span>
+  </div>
+  <div class="stat">
+    <span class="label">Gaze X</span>
+    <span class="value" id="gaze-x">0.000</span>
+  </div>
+  <div class="stat">
+    <span class="label">Gaze Y</span>
+    <span class="value" id="gaze-y">0.000</span>
+  </div>
+  <div class="stat">
+    <span class="label">Iris L</span>
+    <span class="value" id="iris-l">--</span>
+  </div>
+  <div class="stat">
+    <span class="label">Iris R</span>
+    <span class="value" id="iris-r">--</span>
+  </div>
+</div>
+
+<div id="loader">
+  <div class="spinner"></div>
+  <div class="loader-text" id="loader-text">Loading MediaPipe</div>
+  <div class="loader-sub" id="loader-sub">Initializing WASM runtime &amp; face mesh model. Please allow camera access when prompted.</div>
+</div>
+
+<div id="debug-panel" class="collapsed">
+  <div id="debug-header" title="Click to expand/collapse">
+    <span>DEBUG</span>
+    <span id="debug-toggle">+</span>
+  </div>
+  <div id="debug-body">
+    <div class="dbg-row"><span class="k">camera_utils</span><span class="v" id="dbg-cdn1">…</span></div>
+    <div class="dbg-row"><span class="k">drawing_utils</span><span class="v" id="dbg-cdn2">…</span></div>
+    <div class="dbg-row"><span class="k">face_mesh</span><span class="v" id="dbg-cdn3">…</span></div>
+    <div class="dbg-row"><span class="k">model</span><span class="v" id="dbg-model">…</span></div>
+    <div class="dbg-row"><span class="k">camera</span><span class="v" id="dbg-camera">…</span></div>
+    <div class="dbg-row"><span class="k">stage</span><span class="v" id="dbg-stage">…</span></div>
+    <div class="dbg-row"><span class="k">frame ms</span><span class="v" id="dbg-frame">--</span></div>
+    <div class="dbg-row"><span class="k">downloaded</span><span class="v" id="dbg-bytes">0 KB</span></div>
+    <div id="debug-err"></div>
+  </div>
+</div>
+
+<div id="error-overlay">
+  <div class="icon">⚠</div>
+  <h2 id="err-title">Camera Access Denied</h2>
+  <p id="err-msg">We need your camera to track your gaze. Please grant camera permission in your browser settings and reload the page.</p>
+  <button id="err-retry">Retry</button>
+</div>
+
+<!-- MediaPipe CDN -->
+<script>
+  // Mark CDN load state on the global scope so the inline app can read it.
+  window.__cdnStatus = window.__cdnStatus || {};
+  function __cdnErr(name, src) {
+    window.__cdnStatus[name] = 'error';
+    console.error('[CDN] failed to load', name, src);
+    // Surface the failure as a visible loader message immediately.
+    var lt = document.getElementById('loader-text');
+    var ls = document.getElementById('loader-sub');
+    if (lt) lt.textContent = 'CDN load failed';
+    if (ls) ls.textContent = 'Could not download ' + name + ' from the CDN. Check your network and reload.';
+    try {
+      var evt = new CustomEvent('cdnError', { detail: { name: name, src: src } });
+      window.dispatchEvent(evt);
+    } catch (e) { /* no-op */ }
+  }
+  function __cdnOk(name) {
+    window.__cdnStatus[name] = 'ok';
+    console.log('[CDN] loaded', name);
+    try {
+      window.dispatchEvent(new CustomEvent('cdnOk', { detail: { name: name } }));
+    } catch (e) { /* no-op */ }
+  }
+</script>
+<script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"
+        onload="__cdnOk('camera_utils')"
+        onerror="__cdnErr('camera_utils', this.src)"></script>
+<script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"
+        onload="__cdnOk('drawing_utils')"
+        onerror="__cdnErr('drawing_utils', this.src)"></script>
+<script src="https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh.js" crossorigin="anonymous"
+        onload="__cdnOk('face_mesh')"
+        onerror="__cdnErr('face_mesh', this.src)"></script>
+
+<script>
+(function () {
+  'use strict';
+
+  // ============================================================
+  //  Config
+  // ============================================================
+  const TRAIL_LENGTH = 50;            // # of trail points
+  const ORB_RADIUS = 40;              // px
+  const GRID_DRAW_INTERVAL_MS = 33;   // ~30fps redraw
+  // Kalman filter parameters (tuned for responsiveness, not smoothness)
+  const KALMAN_R = 0.015;             // measurement noise (LOW = trust raw data more = faster response)
+  const KALMAN_Q = 0.006;             // process noise (HIGHER = less smoothing = more responsive)
+  // No fixed sensitivity — iris ratio already maps to [0,1] natively
+
+  // Iris / eye landmark indices (MediaPipe Face Mesh)
+  // Left eye
+  const L_OUTER = 33,   L_INNER = 133;
+  const L_TOP   = 159,  L_BOT   = 145;
+  const L_IRIS  = 468;
+  // Right eye
+  const R_OUTER = 362,  R_INNER = 263;
+  const R_TOP   = 386,  R_BOT   = 374;
+  const R_IRIS  = 473;
+  // Iris contour points
+  const IRIS_LANDMARKS = [
+    468, 469, 470, 471, 472,   // left iris
+    473, 474, 475, 476, 477    // right iris
+  ];
+
+  // Face mesh tesselation connection subsets (subset of FACE_TESSELATION)
+  // Use eye / brow / lip / nose silhouettes to keep it light
+  const FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109];
+  const LIPS      = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95, 78];
+  const L_EYE     = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246];
+  const R_EYE     = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398];
+  const L_BROW    = [46, 53, 52, 65, 55, 107, 66, 105, 63, 70];
+  const R_BROW    = [276, 283, 282, 295, 285, 336, 296, 334, 293, 300];
+
+  // ============================================================
+  //  DOM
+  // ============================================================
+  const stage      = document.getElementById('stage');
+  const ctx        = stage.getContext('2d');
+  const video      = document.getElementById('webcam');
+  const overlay    = document.getElementById('overlay');
+  const octx       = overlay.getContext('2d');
+  const loader     = document.getElementById('loader');
+  const loaderText = document.getElementById('loader-text');
+  const loaderSub  = document.getElementById('loader-sub');
+  const errOverlay = document.getElementById('error-overlay');
+  const errTitle   = document.getElementById('err-title');
+  const errMsg     = document.getElementById('err-msg');
+  const errRetry   = document.getElementById('err-retry');
+  const statusDot  = document.getElementById('status-dot');
+  const statusText = document.getElementById('status-text');
+  const fpsEl      = document.getElementById('fps');
+  const gxEl       = document.getElementById('gaze-x');
+  const gyEl       = document.getElementById('gaze-y');
+  const ilEl       = document.getElementById('iris-l');
+  const irEl       = document.getElementById('iris-r');
+
+  // Debug panel
+  const dbgPanel   = document.getElementById('debug-panel');
+  const dbgHeader  = document.getElementById('debug-header');
+  const dbgToggle  = document.getElementById('debug-toggle');
+  const dbgCdn1    = document.getElementById('dbg-cdn1');
+  const dbgCdn2    = document.getElementById('dbg-cdn2');
+  const dbgCdn3    = document.getElementById('dbg-cdn3');
+  const dbgModel   = document.getElementById('dbg-model');
+  const dbgCamera  = document.getElementById('dbg-camera');
+  const dbgStage   = document.getElementById('dbg-stage');
+  const dbgFrame   = document.getElementById('dbg-frame');
+  const dbgBytes   = document.getElementById('dbg-bytes');
+  const dbgErr     = document.getElementById('debug-err');
+
+  // ============================================================
+  //  Debug panel helpers
+  // ============================================================
+  function dbgSet(el, text, cls) {
+    if (!el) return;
+    el.textContent = text;
+    el.className = 'v' + (cls ? ' ' + cls : '');
+  }
+  function dbgSetError(msg) {
+    if (!dbgErr) return;
+    if (!msg) { dbgErr.classList.remove('show'); dbgErr.textContent = ''; return; }
+    dbgErr.textContent = msg;
+    dbgErr.classList.add('show');
+  }
+  if (dbgHeader) {
+    dbgHeader.addEventListener('click', () => {
+      const collapsed = dbgPanel.classList.toggle('collapsed');
+      dbgPanel.classList.toggle('expanded', !collapsed);
+      dbgToggle.textContent = collapsed ? '+' : '–';
+    });
+  }
+  // Initialize CDN cells from the global status that the loader scripts set
+  try {
+    const s = (window.__cdnStatus) || {};
+    dbgSet(dbgCdn1, s.camera_utils || (s.camera_utils === 'error' ? 'FAIL' : '…'),
+                  s.camera_utils === 'ok' ? 'ok' : s.camera_utils === 'error' ? 'err' : 'run');
+    dbgSet(dbgCdn2, s.drawing_utils || (s.drawing_utils === 'error' ? 'FAIL' : '…'),
+                  s.drawing_utils === 'ok' ? 'ok' : s.drawing_utils === 'error' ? 'err' : 'run');
+    dbgSet(dbgCdn3, s.face_mesh    || (s.face_mesh    === 'error' ? 'FAIL' : '…'),
+                  s.face_mesh    === 'ok' ? 'ok' : s.face_mesh    === 'error' ? 'err' : 'run');
+  } catch (e) { /* no-op */ }
+  // Live-update on CDN load / failure events
+  window.addEventListener('cdnOk', (e) => {
+    const n = e && e.detail && e.detail.name;
+    if (n === 'camera_utils') dbgSet(dbgCdn1, 'OK', 'ok');
+    if (n === 'drawing_utils') dbgSet(dbgCdn2, 'OK', 'ok');
+    if (n === 'face_mesh')    dbgSet(dbgCdn3, 'OK', 'ok');
+  });
+  window.addEventListener('cdnError', (e) => {
+    const n = e && e.detail && e.detail.name;
+    if (n === 'camera_utils') { dbgSet(dbgCdn1, 'FAIL', 'err'); dbgSetError('CDN camera_utils failed to load'); }
+    if (n === 'drawing_utils') { dbgSet(dbgCdn2, 'FAIL', 'err'); dbgSetError('CDN drawing_utils failed to load'); }
+    if (n === 'face_mesh')    { dbgSet(dbgCdn3, 'FAIL', 'err'); dbgSetError('CDN face_mesh failed to load'); }
+  });
+
+  function setLoaderText(main, sub) {
+    if (loaderText) loaderText.textContent = main;
+    if (loaderSub)  loaderSub.textContent  = sub;
+    console.log('[loader]', main, '—', sub);
+  }
+
+  // ============================================================
+  //  State
+  // ============================================================
+  let W = 0, H = 0;
+  let smoothedX = 0.5, smoothedY = 0.5;     // Kalman-smoothed gaze (0..1)
+  let rawX = 0.5, rawY = 0.5;              // raw gaze (0..1)
+  let rawXValid = false;                   // whether raw gaze has a fresh, valid measurement
+  let trail = [];                          // array of {x, y}
+  let faceMesh = null;
+  let camera   = null;
+  let lastResults = null;
+  let lastTime = performance.now();
+  let fpsSmooth = 0;
+  let irisVisible = { l: false, r: false };
+  let trackingLocked = false;
+  let lastFrameMs = 0;        // last face-mesh processing time in ms
+  let lastMeshSendAt = 0;
+
+  // ============================================================
+  //  Simple 1D Kalman filter
+  // ============================================================
+  class SimpleKalman {
+    constructor(R, Q) {
+      this.R = R;             // measurement noise covariance
+      this.Q = Q;             // process noise covariance
+      this.P = 1;             // estimation error covariance
+      this.X = 0.5;           // state estimate
+      this.K = 0;             // Kalman gain
+    }
+    update(measurement) {
+      // Predict: covariance grows by process noise
+      this.P = this.P + this.Q;
+      // Update: compute Kalman gain and incorporate measurement
+      this.K = this.P / (this.P + this.R);
+      this.X = this.X + this.K * (measurement - this.X);
+      this.P = (1 - this.K) * this.P;
+      return this.X;
+    }
+    reset(v = 0.5) {
+      this.P = 1; this.X = v; this.K = 0;
+    }
+  }
+  const kalmanX = new SimpleKalman(KALMAN_R, KALMAN_Q);
+  const kalmanY = new SimpleKalman(KALMAN_R, KALMAN_Q);
+
+  // ============================================================
+  //  Canvas sizing
+  // ============================================================
+  function resize() {
+    const dpr = Math.min(window.devicePixelRatio || 1, 2);
+    W = window.innerWidth;
+    H = window.innerHeight;
+    stage.width  = W * dpr;
+    stage.height = H * dpr;
+    stage.style.width  = W + 'px';
+    stage.style.height = H + 'px';
+    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+  }
+  window.addEventListener('resize', resize);
+  resize();
+
+  // ============================================================
+  //  Gaze math: iris-ratio + head-pose hybrid
+  //  iris ratio gives fine eye-in-socket direction;
+  //  face/nose position in the frame captures head movement (which
+  //  naturally accompanies gaze shifts). Blending both = much larger
+  //  usable range, especially vertically.
+  // ============================================================
+
+  // Weight: how much iris vs head contributes  (0=all head, 1=all iris)
+  const IRIS_WEIGHT_X = 0.65;
+  const IRIS_WEIGHT_Y = 0.30;   // give head even more weight vertically → bigger range
+
+  function computeIrisGaze(landmarks) {
+    function eyeData(outerIdx, innerIdx, topIdx, botIdx, irisIdx) {
+      const outer = landmarks[outerIdx];
+      const inner = landmarks[innerIdx];
+      const top   = landmarks[topIdx];
+      const bot   = landmarks[botIdx];
+      const iris  = landmarks[irisIdx];
+      if (!outer || !inner || !iris) return null;
+      if ((iris.x === 0 && iris.y === 0) || Number.isNaN(iris.x) || Number.isNaN(iris.y)) return null;
+
+      const eyeW = outer.x - inner.x;
+      if (Math.abs(eyeW) < 1e-6) return null;
+
+      const ratioX = (iris.x - inner.x) / eyeW;
+      const midY = (top.y + bot.y) * 0.5;
+      const ratioY = (iris.y - midY) / Math.abs(eyeW);
+
+      return { ratioX, ratioY };
+    }
+
+    const left  = eyeData(L_OUTER, L_INNER, L_TOP, L_BOT, L_IRIS);
+    const right = eyeData(R_OUTER, R_INNER, R_TOP, R_BOT, R_IRIS);
+    irisVisible.l = !!left;
+    irisVisible.r = !!right;
+
+    if (!left && !right) return { x: 0.5, y: 0.5, visible: false };
+
+    // --- Iris ratio (eye-in-socket signal) ---
+    let rx, ry;
+    if (left && right) {
+      rx = (left.ratioX + right.ratioX) * 0.5;
+      ry = (left.ratioY + right.ratioY) * 0.5;
+    } else {
+      const s = left || right;
+      rx = s.ratioX; ry = s.ratioY;
+    }
+
+    // --- Head pose signal (nose tip position in frame) ---
+    // Nose tip = landmark 1, face center = average of landmarks 10(top) + 152(bottom)
+    const nose   = landmarks[1];
+    const fTop   = landmarks[10];
+    const fBot   = landmarks[152];
+    const faceMidY = (fTop.y + fBot.y) * 0.5;
+
+    // headX: nose x relative to image center.  ~0.5 when centered.
+    // headY: nose y relative to face vertical center, normalized by face height.
+    const faceH = Math.abs(fBot.y - fTop.y) || 1e-6;
+    const headOffY = (nose.y - faceMidY) / faceH;  // negative=looking up, positive=looking down
+
+    // --- Blend iris + head ---
+    // Iris X already [0,1]. Head X = nose.x (also ~[0,1], invert because raw is mirror).
+    const irisScreenX = rx * 1.8 - 0.4;                 // amplify & recenter
+    const headScreenX = 0.5 + (0.5 - nose.x) * 3.0;      // amplify head horizontal by 3x
+    const irisScreenY = 0.5 - ry * 2.0;                    // amplify iris vertical by 2x
+    const headScreenY = 0.5 + headOffY * 2.5;            // amplify head vertical by 2.5x
+
+    const screenX = IRIS_WEIGHT_X * irisScreenX + (1 - IRIS_WEIGHT_X) * headScreenX;
+    const screenY = IRIS_WEIGHT_Y * irisScreenY + (1 - IRIS_WEIGHT_Y) * headScreenY;
+
+    return {
+      x: Math.min(1, Math.max(0, screenX)),
+      y: Math.min(1, Math.max(0, screenY)),
+      visible: true
+    };
+  }
+
+  // ============================================================
+  //  Render: full-screen orb + trail
+  // ============================================================
+  function drawOrb() {
+    // Clear with very slight motion blur for the trail
+    ctx.fillStyle = 'rgba(10, 10, 26, 0.35)';
+    ctx.fillRect(0, 0, W, H);
+
+    // Map smoothed gaze to screen coordinates (with margin so orb stays on screen)
+    // No extra mirror needed — computeIrisGaze already handles it
+    const margin = 60;
+    const sx = margin + smoothedX * (W - margin * 2);
+    const sy = margin + smoothedY * (H - margin * 2);
+
+    // Push trail
+    trail.push({ x: sx, y: sy });
+    if (trail.length > TRAIL_LENGTH) trail.shift();
+
+    // Draw trail (oldest -> newest, fading in opacity & shrinking radius)
+    for (let i = 0; i < trail.length; i++) {
+      const t = trail[i];
+      const tNorm = (i + 1) / trail.length;   // 0..1
+      const r = ORB_RADIUS * 0.15 * tNorm;
+      const a = 0.05 + 0.45 * tNorm;
+      const grad = ctx.createRadialGradient(t.x, t.y, 0, t.x, t.y, r * 2.5);
+      grad.addColorStop(0,    `rgba(0, 229, 255, ${a})`);
+      grad.addColorStop(0.4,  `rgba(0, 184, 212, ${a * 0.6})`);
+      grad.addColorStop(1,    'rgba(0, 229, 255, 0)');
+      ctx.fillStyle = grad;
+      ctx.beginPath();
+      ctx.arc(t.x, t.y, r * 2.5, 0, Math.PI * 2);
+      ctx.fill();
+    }
+
+    // Connect trail points with a smooth fading line
+    if (trail.length > 1) {
+      ctx.lineCap = 'round';
+      ctx.lineJoin = 'round';
+      for (let i = 1; i < trail.length; i++) {
+        const tNorm = i / trail.length;
+        ctx.strokeStyle = `rgba(0, 229, 255, ${0.05 + 0.35 * tNorm})`;
+        ctx.lineWidth = 2 + 2 * tNorm;
+        ctx.beginPath();
+        ctx.moveTo(trail[i - 1].x, trail[i - 1].y);
+        ctx.lineTo(trail[i].x,     trail[i].y);
+        ctx.stroke();
+      }
+    }
+
+    // Main orb - layered radial gradients for glow
+    const cx = sx, cy = sy;
+
+    // Outer halo
+    let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4);
+    g.addColorStop(0,    'rgba(0, 229, 255, 0.35)');
+    g.addColorStop(0.25, 'rgba(0, 229, 255, 0.18)');
+    g.addColorStop(0.6,  'rgba(0, 184, 212, 0.05)');
+    g.addColorStop(1,    'rgba(0, 229, 255, 0)');
+    ctx.fillStyle = g;
+    ctx.beginPath();
+    ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2);
+    ctx.fill();
+
+    // Mid glow
+    g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8);
+    g.addColorStop(0,    'rgba(180, 255, 255, 0.95)');
+    g.addColorStop(0.25, 'rgba(0, 229, 255, 0.85)');
+    g.addColorStop(0.65, 'rgba(0, 184, 212, 0.5)');
+    g.addColorStop(1,    'rgba(0, 229, 255, 0)');
+    ctx.fillStyle = g;
+    ctx.beginPath();
+    ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2);
+    ctx.fill();
+
+    // Core
+    g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS);
+    g.addColorStop(0,   'rgba(255, 255, 255, 1)');
+    g.addColorStop(0.3, 'rgba(180, 255, 255, 1)');
+    g.addColorStop(0.7, 'rgba(0, 229, 255, 0.95)');
+    g.addColorStop(1,   'rgba(0, 184, 212, 0.7)');
+    ctx.fillStyle = g;
+    ctx.beginPath();
+    ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2);
+    ctx.fill();
+
+    // Inner sparkle
+    ctx.fillStyle = 'rgba(255, 255, 255, 0.85)';
+    ctx.beginPath();
+    ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2);
+    ctx.fill();
+  }
+
+  // ============================================================
+  //  Render: face mesh overlay on webcam preview
+  // ============================================================
+  function drawOverlay(results) {
+    const w = overlay.width;
+    const h = overlay.height;
+    octx.clearRect(0, 0, w, h);
+
+    if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
+      // Subtle "no face" indicator
+      octx.strokeStyle = 'rgba(0, 229, 255, 0.25)';
+      octx.setLineDash([4, 4]);
+      octx.lineWidth = 1;
+      octx.strokeRect(8, 8, w - 16, h - 16);
+      octx.setLineDash([]);
+      octx.fillStyle = 'rgba(0, 229, 255, 0.7)';
+      octx.font = '10px monospace';
+      octx.fillText('NO FACE DETECTED', 12, h - 12);
+      return;
+    }
+
+    const lm = results.multiFaceLandmarks[0];
+    // Note: the video is mirrored visually via CSS, so we mirror X here
+    // to keep the mesh aligned with what the user sees.
+    const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h });
+
+    // Draw mesh lines
+    octx.lineWidth = 0.6;
+    octx.strokeStyle = 'rgba(0, 229, 255, 0.45)';
+    octx.beginPath();
+    [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => {
+      for (let i = 0; i < connections.length; i++) {
+        const a = pt(connections[i]);
+        const b = pt(connections[(i + 1) % connections.length]);
+        octx.moveTo(a.x, a.y);
+        octx.lineTo(b.x, b.y);
+      }
+    });
+    octx.stroke();
+
+    // Subtle face dots
+    octx.fillStyle = 'rgba(0, 229, 255, 0.4)';
+    for (let i = 0; i < lm.length; i++) {
+      if (i % 3 !== 0) continue; // subsample
+      const p = pt(i);
+      octx.fillRect(p.x, p.y, 1, 1);
+    }
+
+    // Iris highlight (big + bright)
+    octx.fillStyle = '#ffeb3b';
+    octx.shadowColor = '#ffeb3b';
+    octx.shadowBlur  = 10;
+    IRIS_LANDMARKS.forEach(idx => {
+      const p = pt(idx);
+      octx.beginPath();
+      octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2);
+      octx.fill();
+    });
+
+    // Iris center (468 / 473) - extra large
+    octx.shadowBlur = 14;
+    [L_IRIS, R_IRIS].forEach(idx => {
+      const p = pt(idx);
+      octx.fillStyle = '#ffffff';
+      octx.beginPath();
+      octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
+      octx.fill();
+    });
+    octx.shadowBlur = 0;
+  }
+
+  // ============================================================
+  //  Animation loop
+  // ============================================================
+  function loop(now) {
+    // FPS
+    const dt = now - lastTime;
+    lastTime = now;
+    const instFps = 1000 / Math.max(dt, 1);
+    fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1);
+
+    // Kalman smoothing: feed raw gaze through the per-axis Kalman filters.
+    // No update when no iris is visible, so the orb holds its last position
+    // instead of drifting back toward the center.
+    if (rawXValid) {
+      smoothedX = kalmanX.update(rawX);
+      smoothedY = kalmanY.update(rawY);
+    }
+
+    drawOrb();
+    if (lastResults) drawOverlay(lastResults);
+
+    // Status text
+    const visible = irisVisible.l || irisVisible.r;
+    if (visible) {
+      statusDot.className = 'dot ok';
+      statusText.className = 'value ok';
+      statusText.textContent = 'TRACKING';
+      dbgSet(dbgStage, 'tracking', 'ok');
+    } else if (faceMesh) {
+      statusDot.className = 'dot warn';
+      statusText.className = 'value warn';
+      statusText.textContent = 'NO IRIS';
+      dbgSet(dbgStage, 'no face', 'warn');
+    } else {
+      statusDot.className = 'dot';
+      statusText.className = 'value';
+      statusText.textContent = 'INIT';
+      dbgSet(dbgStage, 'init', 'run');
+    }
+    fpsEl.textContent = Math.round(fpsSmooth);
+    gxEl.textContent  = smoothedX.toFixed(3);
+    gyEl.textContent  = smoothedY.toFixed(3);
+    ilEl.textContent  = irisVisible.l ? '●' : '○';
+    irEl.textContent  = irisVisible.r ? '●' : '○';
+    ilEl.className    = 'value ' + (irisVisible.l ? 'ok' : 'warn');
+    irEl.className    = 'value ' + (irisVisible.r ? 'ok' : 'warn');
+    dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--');
+
+    requestAnimationFrame(loop);
+  }
+  requestAnimationFrame(loop);
+
+  // ============================================================
+  //  MediaPipe setup
+  // ============================================================
+  function showError(title, msg) {
+    console.error('[error]', title, '—', msg);
+    errTitle.textContent = title;
+    errMsg.textContent   = msg;
+    errOverlay.classList.add('show');
+    loader.classList.add('hidden');
+    statusDot.className  = 'dot err';
+    statusText.className = 'value err';
+    statusText.textContent = 'ERROR';
+    dbgSetError((title ? title + ': ' : '') + (msg || ''));
+    dbgSet(dbgStage, 'error', 'err');
+  }
+
+  errRetry.addEventListener('click', () => {
+    errOverlay.classList.remove('show');
+    location.reload();
+  });
+
+  // Format bytes for the debug panel / loader text
+  function fmtBytes(n) {
+    if (n < 1024) return n + ' B';
+    if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
+    return (n / (1024 * 1024)).toFixed(2) + ' MB';
+  }
+
+  // Pre-fetch a list of MediaPipe WASM / data files with byte-level progress.
+  // Returns a map { filename -> blob: URL } suitable for locateFile().
+  // If any file fails, the function still resolves with whatever succeeded
+  // (MediaPipe will retry from the network as a fallback).
+  async function prefetchAssets(files) {
+    console.log('[model] pre-fetching', files.length, 'asset(s)…');
+    dbgSet(dbgModel, 'loading…', 'run');
+    const out = {};
+    let totalBytes = 0;
+    for (let i = 0; i < files.length; i++) {
+      const file = files[i];
+      const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
+      setLoaderText(
+        'Downloading model (' + (i + 1) + '/' + files.length + ')',
+        file + '  (0 MB)'
+      );
+      console.log('[model] GET', file);
+      try {
+        const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' });
+        if (!resp.ok) throw new Error('HTTP ' + resp.status);
+        const len = parseInt(resp.headers.get('content-length') || '0', 10);
+        // Stream the body so we can show incremental progress.
+        const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null;
+        const chunks = [];
+        let received = 0;
+        if (reader) {
+          // eslint-disable-next-line no-constant-condition
+          while (true) {
+            const { done, value } = await reader.read();
+            if (done) break;
+            chunks.push(value);
+            received += value.byteLength;
+            totalBytes += value.byteLength;
+            const pct = len ? Math.round((received / len) * 100) : 0;
+            setLoaderText(
+              'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)',
+              file + '  —  ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '')
+            );
+            dbgSet(dbgBytes, fmtBytes(totalBytes));
+          }
+          const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' });
+          out[file] = URL.createObjectURL(blob);
+        } else {
+          const blob = await resp.blob();
+          out[file] = URL.createObjectURL(blob);
+          totalBytes += blob.size;
+          dbgSet(dbgBytes, fmtBytes(totalBytes));
+        }
+        console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0)));
+      } catch (e) {
+        console.warn('[model] pre-fetch failed for', file, e && e.message);
+        // leave out[file] undefined → MediaPipe will fall back to the URL
+      }
+    }
+    dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok');
+    console.log('[model] pre-fetch done, total', fmtBytes(totalBytes));
+    return out;
+  }
+
+  async function initFaceMesh() {
+    console.log('[init] initFaceMesh start');
+    setLoaderText(
+      'Initializing face mesh…',
+      'Preparing the iris-tracking model. This may take a moment.'
+    );
+    dbgSet(dbgModel, 'init…', 'run');
+    try {
+      // 1) Pre-fetch the big WASM / data files so the user can see progress
+      //    instead of a silent stall. The list mirrors the files MediaPipe
+      //    requests at runtime when refineLandmarks is enabled.
+      const assetMap = await prefetchAssets([
+        'face_mesh_solution_simd_wasm_bin.js',
+        'face_mesh_solution_simd_wasm_bin.wasm',
+        'face_mesh_solution_packed_assets.data'
+      ]);
+
+      setLoaderText(
+        'Initializing face mesh…',
+        'WASM runtime ready. Constructing the model.'
+      );
+
+      // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the
+      //    blob URL so the browser uses the cached bytes; otherwise let
+      //    MediaPipe fall back to the CDN.
+      faceMesh = new FaceMesh({
+        locateFile: (file) => {
+          if (assetMap[file]) {
+            console.log('[model] locateFile (cached)', file);
+            return assetMap[file];
+          }
+          const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
+          console.log('[model] locateFile (remote)', file);
+          return url;
+        }
+      });
+      faceMesh.setOptions({
+        maxNumFaces: 1,
+        refineLandmarks: true,        // gives 468-477 iris
+        minDetectionConfidence: 0.5,
+        minTrackingConfidence: 0.5
+      });
+      faceMesh.onResults(onResults);
+
+      console.log('[init] FaceMesh constructed, calling .initialize()');
+      setLoaderText(
+        'Initializing face mesh…',
+        'Calling MediaPipe .initialize() — finalizing WASM.'
+      );
+      if (typeof faceMesh.initialize === 'function') {
+        await faceMesh.initialize();
+      }
+      console.log('[init] FaceMesh ready');
+      dbgSet(dbgModel, 'ready', 'ok');
+
+      startCamera();
+    } catch (e) {
+      console.error('FaceMesh init failed:', e);
+      dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e));
+      dbgSet(dbgModel, 'failed', 'err');
+      showError(
+        'Initialization Failed',
+        'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') +
+        '). Check your network connection and reload the page.'
+      );
+    }
+  }
+
+  function onResults(results) {
+    const t1 = performance.now();
+    lastResults = results;
+
+    if (!results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
+      // No face - hold last smoothed position, don't drift
+      lastFrameMs = performance.now() - t1;
+      return;
+    }
+
+    const lm = results.multiFaceLandmarks[0];
+    const gaze = computeIrisGaze(lm);
+    if (gaze.visible) {
+      rawX = gaze.x;
+      rawY = gaze.y;
+      rawXValid = true;
+    } else {
+      rawXValid = false;
+    }
+    lastFrameMs = performance.now() - t1;
+  }
+
+  function startCamera() {
+    console.log('[camera] startCamera');
+    setLoaderText(
+      'Connecting camera…',
+      'Requesting webcam access. Please click "Allow" in the browser prompt.'
+    );
+    dbgSet(dbgCamera, 'requesting…', 'run');
+    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
+      dbgSet(dbgCamera, 'unsupported', 'err');
+      showError(
+        'Browser Not Supported',
+        'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).'
+      );
+      return;
+    }
+
+    camera = new Camera(video, {
+      onFrame: async () => {
+        if (faceMesh) {
+          const t0 = performance.now();
+          try {
+            await faceMesh.send({ image: video });
+          } catch (e) {
+            // swallow individual frame errors
+            console.warn('[frame] send error', e && e.message);
+          } finally {
+            lastMeshSendAt = performance.now() - t0;
+            if (lastMeshSendAt > 5) {
+              // Only log slow frames to keep the console quiet
+              // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms');
+            }
+          }
+        }
+      },
+      width:  640,
+      height: 480
+    });
+
+    camera.start()
+      .then(() => {
+        // wait for metadata
+        return new Promise(resolve => {
+          if (video.readyState >= 1) return resolve();
+          video.addEventListener('loadedmetadata', resolve, { once: true });
+        });
+      })
+      .then(() => {
+        console.log('[camera] stream ready, hiding loader');
+        loader.classList.add('hidden');
+        statusText.textContent = 'READY';
+        dbgSet(dbgCamera, 'streaming', 'ok');
+        dbgSet(dbgStage, 'live', 'ok');
+      })
+      .catch(err => {
+        console.error('Camera error:', err);
+        dbgSet(dbgCamera, 'error', 'err');
+        const name = err && err.name;
+        if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') {
+          showError(
+            'Camera Access Denied',
+            'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.'
+          );
+        } else if (name === 'NotFoundError' || name === 'OverconstrainedError') {
+          showError(
+            'No Camera Found',
+            'No webcam was detected on this device. Please connect a camera and reload the page.'
+          );
+        } else if (name === 'NotReadableError' || name === 'TrackStartError') {
+          showError(
+            'Camera Busy',
+            'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.'
+          );
+        } else {
+          showError(
+            'Camera Error',
+            (err && err.message) || 'An unknown error occurred while accessing the camera.'
+          );
+        }
+      });
+  }
+
+  // Wait for the global FaceMesh symbol to be available
+  function waitFor(predicate, timeout = 20000) {
+    return new Promise((resolve, reject) => {
+      const start = performance.now();
+      (function check() {
+        if (predicate()) return resolve();
+        if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe'));
+        requestAnimationFrame(check);
+      })();
+    });
+  }
+
+  // Kick off: stage 1 = wait for the CDN script to register window.FaceMesh
+  setLoaderText(
+    'Loading MediaPipe JS…',
+    'Downloading the MediaPipe scripts from the CDN.'
+  );
+  console.log('[boot] waiting for window.FaceMesh…');
+  waitFor(() => typeof window.FaceMesh === 'function', 20000)
+    .then(() => {
+      console.log('[boot] window.FaceMesh available');
+      initFaceMesh();
+    })
+    .catch((e) => {
+      console.error('[boot] FaceMesh never appeared:', e && e.message);
+      dbgSet(dbgCdn3, 'TIMEOUT', 'err');
+      dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.');
+      showError(
+        'Failed to Load MediaPipe',
+        'The MediaPipe library could not be loaded (timeout). The CDN may be blocked in your region — try a VPN or a different network, then reload.'
+      );
+    });
+
+  // Safety: if a CDN script failed before waitFor() could resolve, bail out
+  // promptly with a clear message instead of waiting for the timeout.
+  window.addEventListener('cdnError', () => {
+    if (typeof window.FaceMesh !== 'function') {
+      console.error('[boot] CDN error before FaceMesh became available');
+      showError(
+        'CDN Load Failed',
+        'Could not download the MediaPipe library from the CDN. The CDN may be blocked in your region — try a VPN, a different network, or self-host the files, then reload.'
+      );
+    }
+  });
+
+})();
+</script>
+</body>
+</html>