| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286 |
- <!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 & 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>
|