calibration.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. // calibration.js
  2. // 13-point calibration: collection + 9-dim polynomial regression (OLS) with
  3. // Gaussian elimination (solveNxN) + RANSAC-style per-point outlier rejection
  4. // + localStorage persistence + UI flow (start / step / commit / finish / cancel).
  5. //
  6. // V2 model — 9 features per dimension (screenX and screenY fit independently):
  7. // screenX = a0 + a1*rX + a2*rY + a3*ear + a4*pitch + a5*yaw
  8. // + a6*rX² + a7*rY² + a8*rX*rY
  9. // screenY = b0 + b1*rX + b2*rY + b3*ear + b4*pitch + b5*yaw
  10. // + b6*rX² + b7*rY² + b8*rX*rY
  11. //
  12. // We fit screenX and screenY independently using ordinary least squares
  13. // on the N=13 calibration points (≈ 13 × 27 = 351 effective samples after
  14. // discarding the first 3 per point). We average each point's samples first
  15. // to make one (ratioX, ratioY, ear, pitch, yaw) per grid location, then
  16. // solve the 9×9 normal equation directly (Gaussian elimination with
  17. // partial pivoting — Cramer's rule is too slow / numerically unstable
  18. // past ~6×6).
  19. //
  20. // Old 6-coef payloads are rejected by loadCalibration() because CAL_VERSION
  21. // is now 4 (was 3). This forces a one-time re-calibration on first run
  22. // after the upgrade, which is correct: the V2 model has different
  23. // feature semantics and shouldn't try to read V1 coefficients.
  24. import {
  25. CAL_GRID, CAL_ORDER, CAL_SAMPLES_PER_POINT,
  26. CAL_SAMPLE_INTERVAL_MS, CAL_STORAGE_KEY, CAL_VERSION
  27. } from './config.js';
  28. import { clamp, dbgSet, dbgSetError } from './utils.js';
  29. import {
  30. averageSamples, buildPolyFeatures, buildDesignMatrix, olsFit,
  31. buildPolyFeaturesV2, buildDesignMatrixV2, olsFitV2, N_FEATURES_V2
  32. } from './math.js';
  33. import { kalInit } from './kalman.js';
  34. // ---- DOM references ----
  35. const calOverlay = document.getElementById('calibration-overlay');
  36. const calDot = document.getElementById('cal-dot');
  37. const calText = document.getElementById('cal-text');
  38. const calSub = document.getElementById('cal-sub');
  39. const calCancel = document.getElementById('cal-cancel');
  40. const calDotStatus = document.getElementById('cal-dot-status');
  41. const calStatusText = document.getElementById('cal-status-text');
  42. const recalibrateBtn = document.getElementById('recalibrate-btn');
  43. const dbgCal = document.getElementById('dbg-cal');
  44. // ---- Mutable state exported as `let` (live bindings) ----
  45. // `calibrationData` is the live OLS fit: { coefX:[a0..a8], coefY:[b0..b8], timestamp }.
  46. // 9 coefficients per axis, not 6.
  47. export let calibrationData = null;
  48. // True while a calibration session is in progress.
  49. export let calActive = false;
  50. // True while in the calibration overlay (raw gaze is ignored by the renderer).
  51. export let calPaused = false;
  52. // Index into CAL_ORDER.
  53. export let calCurrentIdx = 0;
  54. // Internal-only state (not exported because no other module needs to mutate it)
  55. let calSamples = []; // collected V2 samples for the active point
  56. let calAllPoints = []; // accumulated {screenX, screenY, samples:[…]} for all 13 points
  57. let calCollectTimer = null; // setInterval id for sample collection
  58. let pointSampleCount = 0; // per-point sample counter (discard first 3)
  59. // ============================================================
  60. // RANSAC + regression
  61. // ============================================================
  62. // RANSAC-style outlier rejection on the V2 features per calibration point.
  63. // For each point's samples, drop those whose (ratioX, ratioY) lies > 2.5
  64. // std from the per-point mean. We also drop samples whose EAR is far from
  65. // the per-point median — those are mid-blink samples that slipped past
  66. // the per-frame blink filter, and they're poison for the regression
  67. // because the iris ratio is unstable while the eyelid covers the iris.
  68. //
  69. // This catches blinks, mid-saccade samples, and points where the user
  70. // briefly looked elsewhere while the dot was moving.
  71. function ransacCleanPerPoint(point) {
  72. if (!point.samples || point.samples.length <= 5) return point.samples || [];
  73. const sams = point.samples;
  74. const meanX = sams.reduce((a, s) => a + s.ratioX, 0) / sams.length;
  75. const meanY = sams.reduce((a, s) => a + s.ratioY, 0) / sams.length;
  76. const stdX = Math.sqrt(sams.reduce((a, s) => a + (s.ratioX - meanX) * (s.ratioX - meanX), 0) / sams.length);
  77. const stdY = Math.sqrt(sams.reduce((a, s) => a + (s.ratioY - meanY) * (s.ratioY - meanY), 0) / sams.length);
  78. // Median EAR (sorted copy) — robust to a few mid-blink samples.
  79. const ears = sams.map(s => (s.ear != null ? s.ear : 0)).slice().sort((a, b) => a - b);
  80. const earMedian = ears[Math.floor(ears.length / 2)];
  81. // If std is essentially 0 (perfectly steady) just return everything.
  82. if (stdX < 1e-6 && stdY < 1e-6) return sams.slice();
  83. const kept = [];
  84. for (let i = 0; i < sams.length; i++) {
  85. const s = sams[i];
  86. const sx = (Math.abs(s.ratioX - meanX) < 2.5 * Math.max(stdX, 1e-6));
  87. const sy = (Math.abs(s.ratioY - meanY) < 2.5 * Math.max(stdY, 1e-6));
  88. // EAR: drop samples whose EAR is more than 0.10 below the median.
  89. // 0.10 is roughly half the open-eye range, so it triggers on closed
  90. // eyes but tolerates normal micro-variation.
  91. const e = s.ear != null ? s.ear : 0;
  92. const se = (e === 0) || (e >= earMedian - 0.10);
  93. if (sx && sy && se) kept.push(s);
  94. }
  95. // Don't drop more than 40% of samples — std may be underestimated.
  96. if (kept.length < sams.length * 0.6) return sams.slice();
  97. return kept;
  98. }
  99. export function fitCalibration(allPoints) {
  100. // allPoints: [{ screenX, screenY, samples:[…] }, …]
  101. // 1) Per-point outlier rejection (RANSAC).
  102. // 2) Average remaining samples per point.
  103. let totalSamples = 0, totalKept = 0;
  104. const pts = allPoints.map(p => {
  105. const cleaned = ransacCleanPerPoint(p);
  106. totalSamples += (p.samples || []).length;
  107. totalKept += cleaned.length;
  108. const avg = averageSamples(cleaned);
  109. return {
  110. screenX: p.screenX,
  111. screenY: p.screenY,
  112. ratioX: avg.ratioX,
  113. ratioY: avg.ratioY,
  114. ear: avg.ear,
  115. pitch: avg.pitch,
  116. yaw: avg.yaw
  117. };
  118. });
  119. // 9-dim design matrix: [1, rX, rY, ear, pitch, yaw, rX², rY², rX*rY]
  120. const X = buildDesignMatrixV2(pts);
  121. const ysx = pts.map(p => p.screenX);
  122. const ysy = pts.map(p => p.screenY);
  123. const coefX = olsFitV2(X, ysx, N_FEATURES_V2);
  124. const coefY = olsFitV2(X, ysy, N_FEATURES_V2);
  125. if (!coefX || !coefY) return null;
  126. // Fit-quality debug: re-evaluate the model at each averaged point and
  127. // report per-axis RMSE. We do this against the averaged points (one
  128. // per grid location) so the metric is independent of how many raw
  129. // samples we collected; the per-point RANSAC above already trims
  130. // gross outliers.
  131. let sseX = 0, sseY = 0;
  132. for (let i = 0; i < pts.length; i++) {
  133. const f = X[i]; // already the 9-dim feature row
  134. let px = 0, py = 0;
  135. for (let k = 0; k < N_FEATURES_V2; k++) {
  136. px += coefX[k] * f[k];
  137. py += coefY[k] * f[k];
  138. }
  139. sseX += (pts[i].screenX - px) * (pts[i].screenX - px);
  140. sseY += (pts[i].screenY - py) * (pts[i].screenY - py);
  141. }
  142. console.log('[cal] V2 fit quality kept=' + totalKept + '/' + totalSamples +
  143. ' RMSE X=' + Math.sqrt(sseX / pts.length).toFixed(4) +
  144. ' RMSE Y=' + Math.sqrt(sseY / pts.length).toFixed(4));
  145. return {
  146. coefX: coefX.slice(0, N_FEATURES_V2),
  147. coefY: coefY.slice(0, N_FEATURES_V2)
  148. };
  149. }
  150. // Apply the V2 (9-coef) regression. Accepts ear/pitch/yaw; they go
  151. // through unused if the model's coefficient for that feature happens
  152. // to be 0 (e.g. a user's particular head pose has no effect on their
  153. // gaze mapping). Output is clamped to a slight overshoot of [0, 1]
  154. // so the orb can briefly travel to the screen edge.
  155. export function applyRegression(ratioX, ratioY, ear, pitch, yaw) {
  156. if (!calibrationData) return { x: 0.5, y: 0.5 };
  157. const cx = calibrationData.coefX;
  158. const cy = calibrationData.coefY;
  159. // Inline the V2 feature row — avoids a small allocation per frame.
  160. // Layout: [1, rX, rY, ear, pitch, yaw, rX², rY², rX*rY]
  161. const e = (ear != null) ? ear : 0;
  162. const pi = (pitch != null) ? pitch : 0;
  163. const w = (yaw != null) ? yaw : 0;
  164. const r2x = ratioX * ratioX;
  165. const r2y = ratioY * ratioY;
  166. const rxy = ratioX * ratioY;
  167. const f = [1, ratioX, ratioY, e, pi, w, r2x, r2y, rxy];
  168. let x = 0, y = 0;
  169. for (let k = 0; k < N_FEATURES_V2; k++) {
  170. x += cx[k] * f[k];
  171. y += cy[k] * f[k];
  172. }
  173. return { x: clamp(x, -0.05, 1.05), y: clamp(y, -0.05, 1.05) };
  174. }
  175. export function saveCalibration(cal) {
  176. try {
  177. const payload = {
  178. version: CAL_VERSION,
  179. coefX: cal.coefX,
  180. coefY: cal.coefY,
  181. timestamp: Date.now()
  182. };
  183. localStorage.setItem(CAL_STORAGE_KEY, JSON.stringify(payload));
  184. } catch (e) {
  185. console.warn('[cal] localStorage save failed', e && e.message);
  186. }
  187. }
  188. export function loadCalibration() {
  189. try {
  190. const raw = localStorage.getItem(CAL_STORAGE_KEY);
  191. if (!raw) return null;
  192. const obj = JSON.parse(raw);
  193. if (!obj || !Array.isArray(obj.coefX) || !Array.isArray(obj.coefY)) return null;
  194. // V2: 9 coefficients per axis (was 6 in the V1 6-dim model).
  195. if (obj.coefX.length !== N_FEATURES_V2 || obj.coefY.length !== N_FEATURES_V2) return null;
  196. if (obj.version !== CAL_VERSION) {
  197. console.warn('[cal] stored calibration version mismatch (got', obj.version, 'expected', CAL_VERSION + '); discarding');
  198. return null;
  199. }
  200. return {
  201. coefX: obj.coefX.slice(0, N_FEATURES_V2),
  202. coefY: obj.coefY.slice(0, N_FEATURES_V2),
  203. timestamp: obj.timestamp || 0
  204. };
  205. } catch (e) {
  206. console.warn('[cal] localStorage load failed', e && e.message);
  207. return null;
  208. }
  209. }
  210. export function clearCalibration() {
  211. try { localStorage.removeItem(CAL_STORAGE_KEY); } catch (e) { /* no-op */ }
  212. calibrationData = null;
  213. // Reset Kalman so the orb returns to the center after a recalibration.
  214. kalInit();
  215. // Mirror the IIFE's `rawXValid = false` so the renderer stops feeding
  216. // stale samples into the Kalman filter. The local mirror is also kept
  217. // in sync by gaze.js via setRawXValid().
  218. _rawXValid = false;
  219. // Notify the renderer that it should snap smoothed values back to center.
  220. _resetSmoothed && _resetSmoothed();
  221. updateCalStatus('uncalibrated');
  222. }
  223. // ============================================================
  224. // Calibration UI flow
  225. // ============================================================
  226. // Imported lazily to avoid a circular import (gaze.js imports
  227. // calibration.js, and calibration.js reads lastGaze from gaze.js).
  228. // We access it through a dynamic getter that gaze.js registers
  229. // once it's initialized.
  230. let _lastGazeGetter = () => ({
  231. ratioX: 0.5, ratioY: 0.5,
  232. ear: 0, pitch: 0, yaw: 0,
  233. visible: false
  234. });
  235. export function registerLastGazeGetter(fn) { _lastGazeGetter = fn; }
  236. // Same pattern for the renderer's smoothed-gaze reset hook (called on
  237. // clearCalibration / finishCalibration). Renderer.js registers this.
  238. let _resetSmoothed = null;
  239. export function registerResetSmoothed(fn) { _resetSmoothed = fn; }
  240. // `rawXValid` is mirrored here too (renderer reads it; gaze writes to it).
  241. // We expose getters/setters so gaze.js doesn't need to import this module.
  242. let _rawXValid = false;
  243. export function getRawXValid() { return _rawXValid; }
  244. export function setRawXValid(v) { _rawXValid = v; }
  245. // Back-compat: some old callers referenced `rawXValid` directly.
  246. // We use `getRawXValid()`/`setRawXValid()` from gaze.js instead.
  247. export function updateCalStatus(state) {
  248. // state: 'uncalibrated' | 'calibrating' | 'calibrated'
  249. if (!calDotStatus || !calStatusText) return;
  250. if (state === 'uncalibrated') {
  251. calDotStatus.className = 'dot';
  252. calStatusText.className = 'value warn';
  253. calStatusText.textContent = 'UNCAL';
  254. if (recalibrateBtn) recalibrateBtn.disabled = false;
  255. dbgSet(dbgCal, 'uncalibrated', 'warn');
  256. } else if (state === 'calibrating') {
  257. calDotStatus.className = 'dot warn';
  258. calStatusText.className = 'value';
  259. calStatusText.textContent = 'CAL…';
  260. if (recalibrateBtn) recalibrateBtn.disabled = true;
  261. dbgSet(dbgCal, 'running', 'run');
  262. } else if (state === 'calibrated') {
  263. calDotStatus.className = 'dot ok';
  264. calStatusText.className = 'value ok';
  265. calStatusText.textContent = 'OK';
  266. if (recalibrateBtn) recalibrateBtn.disabled = false;
  267. dbgSet(dbgCal, 'ready', 'ok');
  268. }
  269. }
  270. export function positionCalDot(idx) {
  271. if (!calDot) return;
  272. const p = CAL_GRID[CAL_ORDER[idx]];
  273. // The body / stage is mirrored via CSS scaleX(-1) (webcam preview only);
  274. // the canvas (#stage) is NOT mirrored, so we use window coordinates directly.
  275. const cx = p.x * window.innerWidth;
  276. const cy = p.y * window.innerHeight;
  277. calDot.style.left = cx + 'px';
  278. calDot.style.top = cy + 'px';
  279. }
  280. export function showCalibrationUI(show) {
  281. if (!calOverlay) return;
  282. if (show) {
  283. calOverlay.classList.add('show');
  284. calOverlay.setAttribute('aria-hidden', 'false');
  285. } else {
  286. calOverlay.classList.remove('show');
  287. calOverlay.setAttribute('aria-hidden', 'true');
  288. }
  289. }
  290. export function startCalibration() {
  291. if (calActive) return;
  292. calActive = true;
  293. calPaused = true; // don't let the orb move while we collect
  294. calAllPoints = [];
  295. calCurrentIdx = 0;
  296. calSamples = [];
  297. pointSampleCount = 0;
  298. updateCalStatus('calibrating');
  299. showCalibrationUI(true);
  300. gotoNextCalPoint();
  301. }
  302. export function gotoNextCalPoint() {
  303. if (!calActive) return;
  304. if (calCurrentIdx >= CAL_ORDER.length) {
  305. finishCalibration();
  306. return;
  307. }
  308. positionCalDot(calCurrentIdx);
  309. if (calText) {
  310. calText.textContent = 'Calibrating (' + (calCurrentIdx + 1) + '/' + CAL_ORDER.length + ')';
  311. }
  312. if (calSub) {
  313. calSub.textContent = 'Follow the dot with your eyes';
  314. }
  315. calSamples = [];
  316. pointSampleCount = 0; // reset per-point counter (first 3 are discarded)
  317. startSampleCollection();
  318. }
  319. export function startSampleCollection() {
  320. if (calCollectTimer) clearInterval(calCollectTimer);
  321. calCollectTimer = setInterval(() => {
  322. if (!calActive) return;
  323. // Discard the first 3 samples so the user has time to fixate on the dot.
  324. if (pointSampleCount < 3) { pointSampleCount++; return; }
  325. const gaze = _lastGazeGetter(); // most recent V2 sample (see onResults)
  326. if (gaze && gaze.visible) {
  327. // V2 sample: ratioX/ratioY + ear/pitch/yaw. We don't separately
  328. // skip blink frames here — the onResults blink filter in gaze.js
  329. // means the gaze is already only being updated on non-blink frames,
  330. // and the per-point RANSAC below will catch any leakage.
  331. calSamples.push({
  332. ratioX: gaze.ratioX,
  333. ratioY: gaze.ratioY,
  334. ear: gaze.ear != null ? gaze.ear : 0,
  335. pitch: gaze.pitch != null ? gaze.pitch : 0,
  336. yaw: gaze.yaw != null ? gaze.yaw : 0
  337. });
  338. }
  339. if (calSamples.length >= CAL_SAMPLES_PER_POINT) {
  340. clearInterval(calCollectTimer);
  341. calCollectTimer = null;
  342. commitCurrentPoint();
  343. }
  344. }, CAL_SAMPLE_INTERVAL_MS);
  345. }
  346. export function commitCurrentPoint() {
  347. const p = CAL_GRID[CAL_ORDER[calCurrentIdx]];
  348. calAllPoints.push({
  349. screenX: p.x,
  350. screenY: p.y,
  351. samples: calSamples.slice()
  352. });
  353. calCurrentIdx++;
  354. if (calCurrentIdx >= CAL_ORDER.length) {
  355. finishCalibration();
  356. } else {
  357. // Brief pause between points so the user can re-target.
  358. setTimeout(gotoNextCalPoint, 150);
  359. }
  360. }
  361. export function finishCalibration() {
  362. if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
  363. const fit = fitCalibration(calAllPoints);
  364. if (!fit) {
  365. console.warn('[cal] OLS fit failed');
  366. calActive = false;
  367. calPaused = false;
  368. showCalibrationUI(false);
  369. updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
  370. return;
  371. }
  372. calibrationData = { coefX: fit.coefX, coefY: fit.coefY, timestamp: Date.now() };
  373. saveCalibration(calibrationData);
  374. console.log('[cal] saved', calibrationData);
  375. // Reset Kalman so stale state doesn't bleed into the new calibration.
  376. kalInit();
  377. calActive = false;
  378. calPaused = false;
  379. showCalibrationUI(false);
  380. updateCalStatus('calibrated');
  381. }
  382. export function cancelCalibration() {
  383. if (calCollectTimer) { clearInterval(calCollectTimer); calCollectTimer = null; }
  384. calActive = false;
  385. calPaused = false;
  386. showCalibrationUI(false);
  387. updateCalStatus(calibrationData ? 'calibrated' : 'uncalibrated');
  388. }
  389. // ---- Wire up buttons ----
  390. if (calCancel) {
  391. calCancel.addEventListener('click', cancelCalibration);
  392. }
  393. // Recalibrate button is wired by main.js (it needs to know whether
  394. // faceMesh is ready before kicking off a new calibration).
  395. export function bindRecalibrateButton(isFaceMeshReady) {
  396. if (!recalibrateBtn) return;
  397. recalibrateBtn.addEventListener('click', () => {
  398. if (!isFaceMeshReady()) return; // need the model to be running
  399. clearCalibration();
  400. startCalibration();
  401. });
  402. }
  403. // Try to restore a previously-saved calibration as soon as the script runs.
  404. export function tryRestoreCalibration() {
  405. const saved = loadCalibration();
  406. if (saved) {
  407. calibrationData = saved;
  408. updateCalStatus('calibrated');
  409. console.log('[cal] restored from localStorage');
  410. } else {
  411. updateCalStatus('uncalibrated');
  412. }
  413. }