renderer.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // renderer.js
  2. // Canvas rendering: stage canvas (orb + trail) + overlay canvas (face mesh on preview).
  3. // Owns: W, H, ctx, octx, stage, overlay, smoothedX, smoothedY, trail, fpsSmooth, lastTime.
  4. import { TRAIL_LENGTH, ORB_RADIUS, FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW, IRIS_LANDMARKS, L_IRIS, R_IRIS, CAL_ORDER } from './config.js';
  5. import { dbgSet } from './utils.js';
  6. import { kalUpdate } from './kalman.js';
  7. import {
  8. rawX, rawY, lastResults, lastFrameMs,
  9. irisVisible, lastEAR, lastBlinking, lastHeadPose
  10. } from './gaze.js';
  11. import { calActive, calPaused, calCurrentIdx, getRawXValid, registerResetSmoothed, positionCalDot } from './calibration.js';
  12. // ---- DOM references ----
  13. const stage = document.getElementById('stage');
  14. const ctx = stage.getContext('2d');
  15. const overlay = document.getElementById('overlay');
  16. const octx = overlay.getContext('2d');
  17. // Status bar elements
  18. const statusDot = document.getElementById('status-dot');
  19. const statusText = document.getElementById('status-text');
  20. const fpsEl = document.getElementById('fps');
  21. const gxEl = document.getElementById('gaze-x');
  22. const gyEl = document.getElementById('gaze-y');
  23. const ilEl = document.getElementById('iris-l');
  24. const irEl = document.getElementById('iris-r');
  25. // Debug panel stage row
  26. const dbgStage = document.getElementById('dbg-stage');
  27. const dbgFrame = document.getElementById('dbg-frame');
  28. // V2 debug panel rows (EAR, blink flag, pitch, yaw) — set in the animation loop.
  29. const dbgEar = document.getElementById('dbg-ear');
  30. const dbgBlink = document.getElementById('dbg-blink');
  31. const dbgPitch = document.getElementById('dbg-pitch');
  32. const dbgYaw = document.getElementById('dbg-yaw');
  33. // ---- Renderer state ----
  34. export let W = 0, H = 0;
  35. let smoothedX = 0.5, smoothedY = 0.5; // Kalman-smoothed gaze (0..1)
  36. let trail = []; // array of {x, y}
  37. let lastTime = performance.now();
  38. let fpsSmooth = 0;
  39. export function resetSmoothed() {
  40. smoothedX = 0.5;
  41. smoothedY = 0.5;
  42. }
  43. // ============================================================
  44. // Canvas sizing
  45. // ============================================================
  46. function resize() {
  47. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  48. W = window.innerWidth;
  49. H = window.innerHeight;
  50. stage.width = W * dpr;
  51. stage.height = H * dpr;
  52. stage.style.width = W + 'px';
  53. stage.style.height = H + 'px';
  54. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  55. }
  56. window.addEventListener('resize', () => {
  57. resize();
  58. // Re-position the calibration dot if one is currently active
  59. if (calActive && calCurrentIdx < CAL_ORDER.length) {
  60. positionCalDot(calCurrentIdx);
  61. }
  62. });
  63. // Register the smoothed-reset hook so calibration.clearCalibration() can
  64. // snap the orb back to the center after a recalibration.
  65. registerResetSmoothed(resetSmoothed);
  66. resize();
  67. // ============================================================
  68. // Render: full-screen orb + trail
  69. // ============================================================
  70. function drawOrb() {
  71. // Clear with very slight motion blur for the trail
  72. ctx.fillStyle = 'rgba(10, 10, 26, 0.35)';
  73. ctx.fillRect(0, 0, W, H);
  74. // Map smoothed gaze to screen coordinates (with margin so orb stays on screen)
  75. const margin = 60;
  76. const sx = margin + smoothedX * (W - margin * 2);
  77. const sy = margin + smoothedY * (H - margin * 2);
  78. // Push trail
  79. trail.push({ x: sx, y: sy });
  80. if (trail.length > TRAIL_LENGTH) trail.shift();
  81. // Draw trail (oldest -> newest, fading in opacity & shrinking radius)
  82. // Cheap: simple filled circles, no radialGradient per point.
  83. for (let i = 0; i < trail.length; i++) {
  84. const t = trail[i];
  85. const tNorm = (i + 1) / trail.length; // 0..1
  86. const r = ORB_RADIUS * 0.12 * tNorm;
  87. const a = 0.03 + 0.25 * tNorm;
  88. ctx.fillStyle = 'rgba(0, 229, 255, ' + a + ')';
  89. ctx.beginPath();
  90. ctx.arc(t.x, t.y, r, 0, Math.PI * 2);
  91. ctx.fill();
  92. }
  93. // Main orb - layered radial gradients for glow.
  94. // During a blink we dim the orb (~55% intensity) so the user gets
  95. // visual feedback that the blink was registered, but we keep it on
  96. // screen so its position is unambiguous. The dim also hides the
  97. // brief artifacts that some webcams produce at the moment of lid closure.
  98. const blink = lastBlinking;
  99. // Alpha multipliers: halo and mid-glow dim more aggressively than the
  100. // core so the orb still has a recognisable shape at low alpha.
  101. const haloMul = blink ? 0.55 : 1.0;
  102. const midMul = blink ? 0.60 : 1.0;
  103. const coreMul = blink ? 0.70 : 1.0;
  104. // Optional tint shift: when blinking we mix a touch of warm magenta
  105. // into the orb so it reads as "muted" rather than just "faded". We
  106. // shift the highlight stop to a slightly pinker cyan.
  107. const highlightR = blink ? 200 : 180;
  108. const highlightG = blink ? 180 : 255;
  109. const highlightB = blink ? 255 : 255;
  110. const cx = sx, cy = sy;
  111. // Outer halo
  112. let g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 4);
  113. g.addColorStop(0, 'rgba(0, 229, 255, ' + (0.35 * haloMul).toFixed(3) + ')');
  114. g.addColorStop(0.25, 'rgba(0, 229, 255, ' + (0.18 * haloMul).toFixed(3) + ')');
  115. g.addColorStop(0.6, 'rgba(0, 184, 212, ' + (0.05 * haloMul).toFixed(3) + ')');
  116. g.addColorStop(1, 'rgba(0, 229, 255, 0)');
  117. ctx.fillStyle = g;
  118. ctx.beginPath();
  119. ctx.arc(cx, cy, ORB_RADIUS * 4, 0, Math.PI * 2);
  120. ctx.fill();
  121. // Mid glow
  122. g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS * 1.8);
  123. g.addColorStop(0, 'rgba(' + highlightR + ', ' + highlightG + ', ' + highlightB + ', ' + (0.95 * midMul).toFixed(3) + ')');
  124. g.addColorStop(0.25, 'rgba(0, 229, 255, ' + (0.85 * midMul).toFixed(3) + ')');
  125. g.addColorStop(0.65, 'rgba(0, 184, 212, ' + (0.5 * midMul).toFixed(3) + ')');
  126. g.addColorStop(1, 'rgba(0, 229, 255, 0)');
  127. ctx.fillStyle = g;
  128. ctx.beginPath();
  129. ctx.arc(cx, cy, ORB_RADIUS * 1.8, 0, Math.PI * 2);
  130. ctx.fill();
  131. // Core
  132. g = ctx.createRadialGradient(cx, cy, 0, cx, cy, ORB_RADIUS);
  133. g.addColorStop(0, 'rgba(255, 255, 255, ' + (1.0 * coreMul).toFixed(3) + ')');
  134. g.addColorStop(0.3, 'rgba(' + highlightR + ', ' + highlightG + ', ' + highlightB + ', ' + (1.0 * coreMul).toFixed(3) + ')');
  135. g.addColorStop(0.7, 'rgba(0, 229, 255, ' + (0.95 * coreMul).toFixed(3) + ')');
  136. g.addColorStop(1, 'rgba(0, 184, 212, ' + (0.7 * coreMul).toFixed(3) + ')');
  137. ctx.fillStyle = g;
  138. ctx.beginPath();
  139. ctx.arc(cx, cy, ORB_RADIUS, 0, Math.PI * 2);
  140. ctx.fill();
  141. // Inner sparkle
  142. ctx.fillStyle = 'rgba(255, 255, 255, ' + (0.85 * coreMul).toFixed(3) + ')';
  143. ctx.beginPath();
  144. ctx.arc(cx - ORB_RADIUS * 0.25, cy - ORB_RADIUS * 0.25, ORB_RADIUS * 0.18, 0, Math.PI * 2);
  145. ctx.fill();
  146. }
  147. // ============================================================
  148. // Render: face mesh overlay on webcam preview
  149. // ============================================================
  150. function drawOverlay(results) {
  151. const w = overlay.width;
  152. const h = overlay.height;
  153. octx.clearRect(0, 0, w, h);
  154. if (!results || !results.multiFaceLandmarks || results.multiFaceLandmarks.length === 0) {
  155. // Subtle "no face" indicator
  156. octx.strokeStyle = 'rgba(0, 229, 255, 0.25)';
  157. octx.setLineDash([4, 4]);
  158. octx.lineWidth = 1;
  159. octx.strokeRect(8, 8, w - 16, h - 16);
  160. octx.setLineDash([]);
  161. octx.fillStyle = 'rgba(0, 229, 255, 0.7)';
  162. octx.font = '10px monospace';
  163. octx.fillText('NO FACE DETECTED', 12, h - 12);
  164. return;
  165. }
  166. const lm = results.multiFaceLandmarks[0];
  167. // Note: the video is mirrored visually via CSS, so we mirror X here
  168. // to keep the mesh aligned with what the user sees.
  169. const pt = (i) => ({ x: (1 - lm[i].x) * w, y: lm[i].y * h });
  170. // Draw mesh lines
  171. octx.lineWidth = 0.6;
  172. octx.strokeStyle = 'rgba(0, 229, 255, 0.45)';
  173. octx.beginPath();
  174. [FACE_OVAL, LIPS, L_EYE, R_EYE, L_BROW, R_BROW].forEach(connections => {
  175. for (let i = 0; i < connections.length; i++) {
  176. const a = pt(connections[i]);
  177. const b = pt(connections[(i + 1) % connections.length]);
  178. octx.moveTo(a.x, a.y);
  179. octx.lineTo(b.x, b.y);
  180. }
  181. });
  182. octx.stroke();
  183. // Subtle face dots (subsample every 6th point for performance)
  184. octx.fillStyle = 'rgba(0, 229, 255, 0.4)';
  185. for (let i = 0; i < lm.length; i++) {
  186. if (i % 6 !== 0) continue; // was % 3 — doubled the stride to halve the work
  187. const p = pt(i);
  188. octx.fillRect(p.x, p.y, 1, 1);
  189. }
  190. // Iris highlight (big + bright)
  191. octx.fillStyle = '#ffeb3b';
  192. IRIS_LANDMARKS.forEach(idx => {
  193. const p = pt(idx);
  194. octx.beginPath();
  195. octx.arc(p.x, p.y, 1.6, 0, Math.PI * 2);
  196. octx.fill();
  197. });
  198. // Iris center (468 / 473) - extra large
  199. [L_IRIS, R_IRIS].forEach(idx => {
  200. const p = pt(idx);
  201. octx.fillStyle = '#ffffff';
  202. octx.beginPath();
  203. octx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
  204. octx.fill();
  205. });
  206. }
  207. // ============================================================
  208. // Animation loop
  209. // ============================================================
  210. let faceMesh = null;
  211. export function setFaceMeshRef(v) { faceMesh = v; }
  212. function loop(now) {
  213. // FPS
  214. const dt = now - lastTime;
  215. lastTime = now;
  216. const instFps = 1000 / Math.max(dt, 1);
  217. fpsSmooth = fpsSmooth === 0 ? instFps : (fpsSmooth * 0.9 + instFps * 0.1);
  218. // Kalman filter: feed raw gaze through the Kalman filter.
  219. // rawX/rawY are already screen-coords (applyRegression when calibrated,
  220. // or raw iris ratio clamped to [0,1] before calibration is ready).
  221. // No update when no iris is visible, so the orb holds its position
  222. // instead of drifting back to center.
  223. if (getRawXValid() && !calPaused) {
  224. const kf = kalUpdate(rawX, rawY);
  225. smoothedX = kf.x;
  226. smoothedY = kf.y;
  227. }
  228. drawOrb();
  229. if (lastResults) drawOverlay(lastResults);
  230. // Status text — overall pipeline state
  231. const visible = irisVisible.l || irisVisible.r;
  232. if (visible) {
  233. statusDot.className = 'dot ok';
  234. statusText.className = 'value ok';
  235. statusText.textContent = 'TRACKING';
  236. dbgSet(dbgStage, 'tracking', 'ok');
  237. } else if (faceMesh) {
  238. statusDot.className = 'dot warn';
  239. statusText.className = 'value warn';
  240. statusText.textContent = 'NO IRIS';
  241. dbgSet(dbgStage, 'no face', 'warn');
  242. } else {
  243. statusDot.className = 'dot';
  244. statusText.className = 'value';
  245. statusText.textContent = 'INIT';
  246. dbgSet(dbgStage, 'init', 'run');
  247. }
  248. fpsEl.textContent = Math.round(fpsSmooth);
  249. gxEl.textContent = smoothedX.toFixed(3);
  250. gyEl.textContent = smoothedY.toFixed(3);
  251. ilEl.textContent = irisVisible.l ? '●' : '○';
  252. irEl.textContent = irisVisible.r ? '●' : '○';
  253. ilEl.className = 'value ' + (irisVisible.l ? 'ok' : 'warn');
  254. irEl.className = 'value ' + (irisVisible.r ? 'ok' : 'warn');
  255. dbgSet(dbgFrame, lastFrameMs > 0 ? (lastFrameMs.toFixed(1) + ' ms') : '--');
  256. // V2 debug rows: EAR, blink flag, pitch, yaw. The blink row gets
  257. // a warn class so the user can see at a glance that a blink was
  258. // filtered this frame.
  259. if (dbgEar) dbgSet(dbgEar, lastEAR > 0 ? lastEAR.toFixed(3) : '--');
  260. if (dbgBlink) dbgSet(dbgBlink, lastBlinking ? 'YES' : 'no', lastBlinking ? 'warn' : null);
  261. if (dbgPitch) dbgSet(dbgPitch, lastHeadPose.pitch.toFixed(3));
  262. if (dbgYaw) dbgSet(dbgYaw, lastHeadPose.yaw.toFixed(3));
  263. requestAnimationFrame(loop);
  264. }
  265. requestAnimationFrame(loop);