/* 20-controls.js — __JFVR.Controls * * Head-locked VR control strip for video playback: progress bar + seek, * play/pause, skip +/-10 s, subtitle toggle, plus a subtitle row (position / * depth / size / opacity / reset — ADDENDUM 4, extended in ADDENDUM 6). Pure * 2D-canvas rendering plus a thin WebXR quad-layer wrapper. Hidden by default * (ADDENDUM 2): show() brings it up and it auto-hides; setPointer() drives the * aiming beam and the cursor. * * Everything the module exposes is documented in INTERFACES.md (§20-controls.js). * draw() and hitTest() are pure and do not touch WebXR, so they can be unit * tested in isolation. No document / navigator access happens at load time. */ (function () { 'use strict'; var NS = (typeof window !== 'undefined' && window.__JFVR) ? window.__JFVR : (typeof window !== 'undefined' ? (window.__JFVR = {}) : {}); function ns() { if (typeof window !== 'undefined' && window.__JFVR) return window.__JFVR; return NS; } function log() { var n = ns(); if (n && typeof n.log === 'function') { n.log.apply(null, arguments); return; } if (typeof console !== 'undefined' && console.log) { console.log.apply(console, ['[JFVR]'].concat(Array.prototype.slice.call(arguments))); } } function stats() { var n = ns(); if (!n) return null; if (!n.state) n.state = {}; if (!n.state.stats) n.state.stats = {}; return n.state.stats; } /* ------------------------------------------------------------------ * * Geometry (all normalized to the panel rect, origin top-left). * Pure data: shared by draw() and hitTest(). * ------------------------------------------------------------------ */ var FONT = 'system-ui, -apple-system, sans-serif'; var ACCENT = '#4ea1ff'; var TRACK_X0 = 0.03; var TRACK_X1 = 0.97; // Panel extents in metres (used for the XR quad layer). Headset feedback: // the ADDENDUM 4 panel (1.1 m x 0.30 m in front of the eye) filled far too // much of the view, so the whole strip is now 0.72 m x 0.21 m expanded and // 0.60 m x 0.05 m collapsed. var PANEL_M = { collapsed: { w: 0.60, h: 0.05 }, expanded: { w: 0.72, h: 0.26 }, // ADDENDUM 7b: the minimal panel shown while the controls are LOCKED. It // carries only the padlock, so nothing adjustable is reachable. locked: { w: 0.26, h: 0.10 } }; // Panel backing-store pixels at 2000 px/m, so the smaller panel stays as // crisp as the old 1000 px/m one. hitTest() infers the mode from the aspect // ratio of (w, h), so pass these (or any matching ratio). var PANEL_PX = { collapsed: { w: 1200, h: 100 }, expanded: { w: 1440, h: 520 }, locked: { w: 520, h: 200 } }; // Layer placement in viewer space (head-locked, centred, lower part of view). var PANEL_Y = -0.28; var PANEL_Z = 1.4; // hitTest mode threshold: collapsed ratio 12.0, expanded 2.77, locked 2.6. var COLLAPSED_RATIO = 8; // Pointer beam (ADDENDUM 2): a separate thin quad layer running from the // origin of the winning input ray to its hit. Shown only while the bar is. var BEAM_H = 0.011; // quad height = beam thickness, metres var BEAM_L_DEFAULT = 1.2; // length when the ray reaches no panel hit var BEAM_L_MIN = 0.05; var BEAM_L_MAX = 6; var BEAM_TEX = { w: 256, h: 8 }; // u = 0 is the origin end of the beam var CURSOR_R = 0.05; // cursor ring radius, fraction of panel height var MIN_UPLOAD_MS = 33; // ~30 Hz cap on canvas re-uploads var BUTTONS = ['back10', 'playpause', 'fwd10', 'subs', 'lock']; /* ---------------- ADDENDUM 7b: padlock ---------------- * The padlock is now a NORMAL PANEL BUTTON, drawn on the panel canvas. The * first attempt gave it its own quad layer parked to the right of the bar, * which failed on device: the only pointing device is the hand ray and the * cursor's acceptance window reaches the bar's own right edge, not a separate * object 0.4 m further out. As a panel button it travels the exact code path * every other button already uses. */ // Icon centred at (cx, cy) with size s. Closed + filled while locked. function drawLockIcon(ctx, cx, cy, s, locked) { var bodyW = s * 0.56, bodyH = s * 0.44; var bodyY = cy + s * 0.11; var lw = Math.max(1.5, s * 0.075); var col = locked ? ACCENT : '#ffffff'; ctx.strokeStyle = col; ctx.lineWidth = lw; ctx.lineCap = 'round'; var r = s * 0.185; ctx.beginPath(); if (locked) { ctx.arc(cx, bodyY - bodyH / 2, r, Math.PI, 0); // closed arch } else { // open: arch lifted and swung right, gap where the body would be ctx.arc(cx + s * 0.10, bodyY - bodyH / 2 - s * 0.07, r, Math.PI * 0.92, Math.PI * 1.88); } ctx.stroke(); ctx.beginPath(); rr(ctx, cx - bodyW / 2, bodyY - bodyH / 2, bodyW, bodyH, bodyH * 0.22); if (locked) { ctx.fillStyle = ACCENT; ctx.fill(); } else { ctx.strokeStyle = col; ctx.lineWidth = lw; ctx.stroke(); } ctx.fillStyle = locked ? 'rgba(10,16,26,0.82)' : col; ctx.beginPath(); ctx.arc(cx, bodyY - bodyH * 0.12, s * 0.058, 0, Math.PI * 2); ctx.fill(); ctx.beginPath(); ctx.moveTo(cx - s * 0.030, bodyY - bodyH * 0.02); ctx.lineTo(cx + s * 0.030, bodyY - bodyH * 0.02); ctx.lineTo(cx + s * 0.018, bodyY + bodyH * 0.30); ctx.lineTo(cx - s * 0.018, bodyY + bodyH * 0.30); ctx.closePath(); ctx.fill(); } // ADDENDUM 4 subtitle row, left to right. Each entry is the action type // hitTest() returns for that button. ADDENDUM 6 added the vertical position // pair (up/down) and the depth pair (near/far): with the angular lock on, the // depth pair changes the strip's DEPTH only, which is how the user brings the // subtitles to the depth of a nearby object without the text changing size. var SUB_BUTTONS = ['sub_up', 'sub_down', 'sub_near', 'sub_far', 'sub_smaller', 'sub_bigger', 'sub_opaque_down', 'sub_opaque_up', 'sub_reset']; // Values shown in the row's caption when the caller supplies no view.sub. var SUB_DEFAULT = { width: 2.0, opacity: 0.85, angleDeg: 69, lock: true, dist: 1.45 }; // Short Chinese label drawn under every button's icon. Headset feedback: the // icon-only row gave no clue what each button did. Keyed by the SAME action // types hitTest() returns, so the label cannot drift from the action. // playpause swaps 播放 / 暂停 with view.playing at draw time. var LABELS = { back10: '后退10s', playpause: '播放', fwd10: '前进10s', subs: '字幕', lock: '上锁', sub_up: '上', sub_down: '下', sub_near: '近', sub_far: '远', sub_smaller: '小', sub_bigger: '大', sub_opaque_down: '暗', sub_opaque_up: '亮', sub_reset: '复位' }; var LAYOUT = { collapsed: { trackCy: 0.50, trackVisH: 0.13, // ~6.5 mm of a 5 cm strip trackHitY0: 0.0, // full strip height is a generous seek band trackHitY1: 1.0 }, // Vertical bands of the 520 px (= 0.26 m) expanded panel, top to bottom: // the ADDENDUM 8 drag strip, time readout, progress track, media buttons, // subtitle caption, subtitle buttons. The hit bands are contiguous and never // overlap, so the seek band is untouched by the button rows (hitTest still // tests every button first). Every offset is a fraction of the panel, so // draw() and hitTest() scale with whatever w/h they are handed. expanded: { // ADDENDUM 8: the picture-pan drag strip sits ABOVE the progress bar (the // owner's requested place). It is the whole picture-pan affordance: pinch it // and drag, and the video content rotates with your hand. Three taps on it // within VIEW_TAP_MS reset the view to dead ahead. viewStripX0: 0.02, viewStripX1: 0.98, viewStripY0: 0.03, viewStripY1: 0.17, viewHitY0: 0.0, // 0 px band 0..104 px viewHitY1: 0.20, // 104 px viewLabelFont: 0.040, viewValueFont: 0.046, viewHintFont: 0.030, viewLabelDy: 0.075, // 39 px first line baseline viewHintDy: 0.155, // 81 px second (hint) baseline trackCy: 0.42, // 218 px trackVisH: 0.030, // 16 px, ~8 mm of a 26 cm panel trackHitY0: 0.30, // 156 px band 156..270 px, far larger than the bar trackHitY1: 0.52, // 270 px textBaseline: 0.275, // 143 px textFont: 0.075, // 39 px btnY: 0.62, // 322 px btnVisualW: 0.105, // 151 px btnVisualH: 0.125, // 65 px btnHitY0: 0.52, // 270 px band 270..385 px btnHitY1: 0.74, // 385 px // Five buttons - the padlock joined the row at the far right (centres // 0.18 / 0.36 / 0.54 / 0.72 / 0.90, pills 0.088..0.992). btnHitHalfW: 0.092, btnSpacing: 0.18, btnFirstCx: 0.18, // Icon over label inside each media button: the label says what the // button does, the icon keeps the quick visual cue. btnIconDy: -0.026, // -13.5 px, icon centre above the button centre btnIconSize: 0.065, // 34 px icon box btnLabelFont: 0.040, // 21 px label btnLabelDy: 0.041, // 21 px label baseline below the button centre // ADDENDUM 4 subtitle row (ADDENDUM 6: nine buttons), tiling the full // width (centres 0.10 .. 0.90, pitch 0.10, symmetric). The hit pills are // 0.104 wide on a 0.10 pitch, so adjacent hit regions overlap by a hair // instead of leaving a dead zone between. subLabelBaseline: 0.795, // 413 px caption baseline subCaptionFont: 0.040, // 21 px caption (distance + size + opacity readout) subBtnY: 0.925, // 481 px button centre subVisualW: 0.092, // 132 px subVisualH: 0.120, // 62 px subHitY0: 0.84, // 437 px band 437..520 px (below the caption) subHitY1: 1.0, // 520 px subHitHalfW: 0.052, subSpacing: 0.10, subFirstCx: 0.10, subIconDy: -0.020, // -10.4 px icon centre above the button centre subIconSize: 0.046, // 24 px icon box subLabelFont: 0.034, // 17.7 px label subLabelDy: 0.036 // 18.7 px label baseline below the button centre }, // ADDENDUM 7b: the locked panel. ONE target — the padlock — centred, with a // label that says what pressing it does. Nothing else is drawn or hit-tested, // so "locked" cannot leak any adjustable control. locked: { lockCx: 0.5, lockCy: 0.40, lockIconSize: 0.62, // fraction of h lockLabelFont: 0.155, lockLabelDy: 0.74, lockHitHalfW: 0.30, lockHitHalfH: 0.48 } }; /* ------------------------------------------------------------------ * * Small pure helpers. * ------------------------------------------------------------------ */ function num(v) { return (typeof v === 'number' && isFinite(v)) ? v : null; } function clamp(v, a, b) { return v < a ? a : (v > b ? b : v); } // mm:ss, or h:mm:ss past an hour. function fmtTime(t) { var v = num(t); if (v == null || v < 0) v = 0; v = Math.floor(v); var h = Math.floor(v / 3600); var m = Math.floor((v % 3600) / 60); var s = v % 60; var pad = function (n) { return (n < 10 ? '0' + n : '' + n); }; return h > 0 ? (h + ':' + pad(m) + ':' + pad(s)) : (pad(m) + ':' + pad(s)); } function modeFor(w, h) { return (w / h) >= COLLAPSED_RATIO ? 'collapsed' : 'expanded'; } // Rounded-rectangle path (no ctx.roundRect dependency; deterministic). function rr(ctx, x, y, w, h, r) { r = Math.min(r, Math.abs(w) * 0.5, Math.abs(h) * 0.5, h * 0.5); if (r < 0) r = 0; ctx.beginPath(); ctx.moveTo(x + r, y); ctx.lineTo(x + w - r, y); ctx.arcTo(x + w, y, x + w, y + r, r); ctx.lineTo(x + w, y + h - r); ctx.arcTo(x + w, y + h, x + w - r, y + h, r); ctx.lineTo(x + r, y + h); ctx.arcTo(x, y + h, x, y + h - r, r); ctx.lineTo(x, y + r); ctx.arcTo(x, y, x + r, y, r); ctx.closePath(); } // Per-character advance in em, used only to keep every label inside its // button. The required font stack is generic (no webfonts), so the real // metrics are unknown; this deliberately errs on the wide side instead of // measuring. function emAdvance(ch) { var c = ch.charCodeAt(0); if (c >= 0x2e80) return 1.0; // CJK / full-width glyph if (c >= 48 && c <= 57) return 0.56; // digits if (ch === '-') return 0.45; if (c >= 65 && c <= 90) return 0.66; // upper-case latin return 0.56; // lower-case latin / fallback } function textEm(s) { var em = 0; for (var i = 0; i < s.length; i++) em += emAdvance(s.charAt(i)); return em; } // Centred button label under the icon. `maxPx` comes from LAYOUT (thus from // h); it is only reduced when the estimated width would leave less than 12 % // of `availW` as padding, so no label can overflow its button. function drawLabel(ctx, text, cx, baselineY, maxPx, availW, color) { var px = maxPx; var em = textEm(text); if (em > 0) px = Math.min(px, (availW * 0.88) / em); px = Math.max(8, px); ctx.font = '600 ' + Math.round(px) + 'px ' + FONT; ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic'; ctx.fillStyle = color; ctx.fillText(text, cx, baselineY); } /* ------------------------------------------------------------------ * * draw() — pure 2D rendering, no WebXR, no timers, no side effects. * ------------------------------------------------------------------ */ function draw(ctx, w, h, view) { if (!ctx || !(w > 0) || !(h > 0)) return; view = view || {}; var mode = (view.mode === 'expanded' || view.mode === 'locked') ? view.mode : 'collapsed'; var lay = LAYOUT[mode]; ctx.clearRect(0, 0, w, h); // Translucent pill so the controls read over arbitrary video. ctx.fillStyle = 'rgba(0,0,0,0.55)'; rr(ctx, 0, 0, w, h, h * 0.5); ctx.fill(); ctx.strokeStyle = 'rgba(255,255,255,0.14)'; ctx.lineWidth = Math.max(1, h * 0.01); ctx.stroke(); // ADDENDUM 7b: the locked panel is JUST the padlock — no progress bar, no // buttons, nothing adjustable. That is the whole point of the lock. if (mode === 'locked') { var lk = view.lock !== false; // locked is the default for this mode var lcx = lay.lockCx * w, lcy = lay.lockCy * h; var lsz = lay.lockIconSize * h; if (view.hover === 'lock') { ctx.fillStyle = 'rgba(78,161,255,0.30)'; rr(ctx, lcx - w * 0.40, lcy - h * 0.42, w * 0.80, h * 0.84, h * 0.42); ctx.fill(); } drawLockIcon(ctx, lcx, lcy, lsz, lk); drawLabel(ctx, lk ? '解锁' : '上锁', lcx, lay.lockLabelDy * h, lay.lockLabelFont * h, w * 0.92, lk ? ACCENT : '#ffffff'); drawCursor(ctx, w, h, view.pointer); return; } var dur = num(view.duration); var cur = num(view.currentTime); var prog = (dur != null && dur > 0) ? clamp((cur == null ? 0 : cur) / dur, 0, 1) : 0; var bx0 = TRACK_X0 * w; var bx1 = TRACK_X1 * w; var bw = bx1 - bx0; var trackCy = lay.trackCy * h; var tvh = Math.max(2, lay.trackVisH * h); // Track background. ctx.fillStyle = 'rgba(255,255,255,0.22)'; rr(ctx, bx0, trackCy - tvh / 2, bw, tvh, tvh / 2); ctx.fill(); // Buffered-range hint (only when a 0..1 number is supplied). var buf = num(view.buffered); if (buf != null && buf > 0) { buf = clamp(buf, 0, 1); if (buf > prog) { ctx.fillStyle = 'rgba(255,255,255,0.34)'; rr(ctx, bx0, trackCy - tvh / 2, Math.max(tvh, bw * buf), tvh, tvh / 2); ctx.fill(); } } // Played portion. var pw = bw * prog; if (pw > 0.5) { ctx.fillStyle = ACCENT; rr(ctx, bx0, trackCy - tvh / 2, Math.max(tvh, pw), tvh, tvh / 2); ctx.fill(); } // Knob / scrub handle; the track hover state enlarges and tints it. var hoveringTrack = view.hover === 'track'; var knobR = tvh * (hoveringTrack ? 1.2 : 0.95); ctx.fillStyle = hoveringTrack ? ACCENT : '#ffffff'; ctx.beginPath(); ctx.arc(clamp(bx0 + pw, bx0, bx1), trackCy, knobR, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); if (mode === 'expanded') { drawViewStrip(ctx, w, h, view, lay); drawExpanded(ctx, w, h, view, lay, dur, cur); } drawCursor(ctx, w, h, view.pointer); } // Where the input ray will land, in normalized panel coords (origin // top-left). `view.pointer` is optional and absent when nothing is aimed at // the panel, so this is a no-op then. Pure, like the rest of draw(). function drawCursor(ctx, w, h, pointer) { if (!pointer) return; var nx = num(pointer.nx); var ny = num(pointer.ny); if (nx == null || ny == null) return; if (nx < 0 || nx > 1 || ny < 0 || ny > 1) return; var x = nx * w; var y = ny * h; var pressed = !!pointer.pressed; // A press visibly flashes: the ring swells and fills. Without this the UI // gave no acknowledgement at all, which read as "clicking does nothing". var r = Math.max(4, h * CURSOR_R) * (pressed ? 1.9 : 1); if (pressed) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.closePath(); ctx.fillStyle = 'rgba(78,161,255,0.45)'; ctx.fill(); } // Dark backing ring keeps the reticle legible on white video frames. ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.closePath(); ctx.strokeStyle = 'rgba(0,0,0,0.75)'; ctx.lineWidth = Math.max(2, r * 0.5); ctx.stroke(); ctx.strokeStyle = pressed ? '#ffffff' : ACCENT; ctx.lineWidth = Math.max(1.5, r * (pressed ? 0.34 : 0.26)); ctx.stroke(); ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(x, y, Math.max(1.5, r * (pressed ? 0.34 : 0.2)), 0, Math.PI * 2); ctx.closePath(); ctx.fill(); } // ADDENDUM 8 — the picture-pan drag strip, ABOVE the progress bar. // It is one self-contained affordance: the grip says "grab me", the values say // where the picture currently points, and the hint says how to reset. Pure like // the rest of draw(): no state, no timers. function drawViewStrip(ctx, w, h, view, lay) { var v = view.view || {}; var yaw = num(v.yawDeg); var pitch = num(v.pitchDeg); if (yaw == null) yaw = 0; if (pitch == null) pitch = 0; var x0 = num(lay.viewStripX0) * w; var x1 = num(lay.viewStripX1) * w; var y0 = num(lay.viewStripY0) * h; var y1 = num(lay.viewStripY1) * h; var sw = x1 - x0, sh = y1 - y0; if (sw <= 0 || sh <= 0) return; var dragging = view.hover === 'view_drag'; ctx.fillStyle = dragging ? 'rgba(78,161,255,0.26)' : 'rgba(255,255,255,0.10)'; rr(ctx, x0, y0, sw, sh, sh * 0.30); ctx.fill(); ctx.strokeStyle = dragging ? ACCENT : 'rgba(255,255,255,0.26)'; ctx.lineWidth = Math.max(1.5, sh * 0.035); if (typeof ctx.setLineDash === 'function') ctx.setLineDash([sh * 0.22, sh * 0.16]); rr(ctx, x0, y0, sw, sh, sh * 0.30); ctx.stroke(); if (typeof ctx.setLineDash === 'function') ctx.setLineDash([]); // Grip: a 2x3 dot pad, the universal "this is draggable" mark. var gy = (y0 + y1) / 2; var gx = x0 + sh * 0.72; var dot = Math.max(1.5, sh * 0.075); var dx = sh * 0.30, dy = sh * 0.20; ctx.fillStyle = dragging ? '#ffffff' : 'rgba(255,255,255,0.75)'; for (var r = -1; r <= 1; r++) { for (var c = -1; c <= 1; c += 2) { ctx.beginPath(); ctx.arc(gx + c * dx * 0.5, gy + r * dy, dot, 0, Math.PI * 2); ctx.fill(); } } var textX = gx + sh * 0.60; ctx.textBaseline = 'alphabetic'; var f1 = Math.max(10, Math.round(num(lay.viewLabelFont) * h)); ctx.textAlign = 'left'; ctx.fillStyle = '#ffffff'; ctx.font = '600 ' + f1 + 'px ' + FONT; ctx.fillText('拖动调整画面', textX, num(lay.viewLabelDy) * h); ctx.font = Math.max(9, Math.round(num(lay.viewHintFont) * h)) + 'px ' + FONT; ctx.fillStyle = 'rgba(255,255,255,0.70)'; ctx.fillText('点一下复位 · 按住 0.5s 再拖动', textX, num(lay.viewHintDy) * h); // Current angles, right-aligned: the numbers to watch while dragging. var f2 = Math.max(10, Math.round(num(lay.viewValueFont) * h)); ctx.textAlign = 'right'; ctx.font = '700 ' + f2 + 'px ' + FONT; ctx.fillStyle = dragging ? ACCENT : '#ffffff'; ctx.fillText('偏航 ' + fmtSigned(yaw) + '\u00b0 俯仰 ' + fmtSigned(pitch) + '\u00b0', x1 - sh * 0.30, num(lay.viewLabelDy) * h); ctx.font = Math.max(9, Math.round(num(lay.viewHintFont) * h)) + 'px ' + FONT; ctx.fillStyle = 'rgba(255,255,255,0.60)'; ctx.fillText('0\u00b0 / 0\u00b0 = 正前方', x1 - sh * 0.30, num(lay.viewHintDy) * h); } // Signed degree readout for the drag strip: "+12" / "-8" / "0". function fmtSigned(deg) { var r = Math.round(deg); if (r > 0) return '+' + r; return String(r); } function drawExpanded(ctx, w, h, view, lay, dur, cur) { var fontSize = Math.max(10, Math.round(lay.textFont * h)); // Elapsed / duration readout above the scrubber. ctx.font = '600 ' + fontSize + 'px ' + FONT; ctx.textBaseline = 'alphabetic'; ctx.fillStyle = '#ffffff'; if (ctx.shadowColor !== undefined) { ctx.shadowColor = 'rgba(0,0,0,0.9)'; ctx.shadowBlur = fontSize * 0.18; } ctx.textAlign = 'left'; ctx.fillText(fmtTime(cur), TRACK_X0 * w, lay.textBaseline * h); ctx.textAlign = 'right'; ctx.fillText(fmtTime(dur), TRACK_X1 * w, lay.textBaseline * h); if (ctx.shadowColor !== undefined) { ctx.shadowColor = 'rgba(0,0,0,0)'; ctx.shadowBlur = 0; } // Buttons row: back10, play/pause, fwd10, subs. Each button carries its icon // plus a short Chinese label, both scaled from h (owner feedback: the // icon-only row was not self-explanatory). var size = lay.btnIconSize * h; var iconDy = lay.btnIconDy * h; var labelDy = lay.btnLabelDy * h; var labelPx = lay.btnLabelFont * h; for (var i = 0; i < BUTTONS.length; i++) { var id = BUTTONS[i]; var cx = (lay.btnFirstCx + i * lay.btnSpacing) * w; var cy = lay.btnY * h; var bw = lay.btnVisualW * w; var bh = lay.btnVisualH * h; var hovered = view.hover === id; if (hovered) { ctx.fillStyle = 'rgba(78,161,255,0.32)'; rr(ctx, cx - bw / 2, cy - bh / 2, bw, bh, bh * 0.35); ctx.fill(); } var color = '#ffffff'; var label = LABELS[id]; if (id === 'playpause') { if (view.playing) { iconPause(ctx, cx, cy + iconDy, size, color); label = '暂停'; } else { iconPlay(ctx, cx, cy + iconDy, size, color); label = '播放'; } } else if (id === 'back10') { iconSkip(ctx, cx, cy + iconDy, size, color, -1); } else if (id === 'fwd10') { iconSkip(ctx, cx, cy + iconDy, size, color, 1); } else if (id === 'subs') { // The toggle must SHOW its state: a filled accent pill while subtitles // are on, plus an accent icon/label. (Before, this read a module-local // flag that main.js never set, so the button always looked OFF.) if (view.subtitlesOn) { color = ACCENT; label = '字幕开'; if (!hovered) { ctx.fillStyle = 'rgba(78,161,255,0.22)'; rr(ctx, cx - bw / 2, cy - bh / 2, bw, bh, bh * 0.35); ctx.fill(); } } else { label = '字幕关'; } iconSubs(ctx, cx, cy + iconDy, size, color, !!view.subtitlesOn); } else if (id === 'lock') { // ADDENDUM 7b: the padlock. In the expanded panel it is always the // "lock" direction (locking swaps the panel to the minimal mode), but the // label follows view.lock so the same button can serve both directions. var lkOn = !!view.lock; if (lkOn) color = ACCENT; label = lkOn ? '解锁' : '上锁'; drawLockIcon(ctx, cx, cy + iconDy, size, lkOn); } drawLabel(ctx, label, cx, cy + labelDy, labelPx, bw, color); if (hovered) { ctx.strokeStyle = ACCENT; ctx.lineWidth = Math.max(1.5, bh * 0.06); rr(ctx, cx - bw / 2, cy - bh / 2, bw, bh, bh * 0.35); ctx.stroke(); } } drawSubRow(ctx, w, h, view, lay); } // ADDENDUM 4 subtitle row (ADDENDUM 6: seven buttons): a caption line with // the current values (angular width in degrees while locked, physical width in // metres while free; opacity as a percentage on the right) over the buttons. // Same hover treatment as the media row. Pure like the rest of draw(). function drawSubRow(ctx, w, h, view, lay) { var sub = view.sub || null; var width = sub ? num(sub.width) : null; var opacity = sub ? num(sub.opacity) : null; var angle = sub ? num(sub.angleDeg) : null; var dist = sub ? num(sub.dist) : null; var lock = sub && typeof sub.lock === 'boolean' ? sub.lock : SUB_DEFAULT.lock; if (width == null) width = SUB_DEFAULT.width; if (opacity == null) opacity = SUB_DEFAULT.opacity; if (angle == null) angle = SUB_DEFAULT.angleDeg; if (dist == null) dist = SUB_DEFAULT.dist; opacity = clamp(opacity, 0, 1); var fontSize = Math.max(10, Math.round((lay.subCaptionFont || lay.subLabelFont) * h)); ctx.font = '600 ' + fontSize + 'px ' + FONT; ctx.textBaseline = 'alphabetic'; ctx.fillStyle = '#ffffff'; if (ctx.shadowColor !== undefined) { ctx.shadowColor = 'rgba(0,0,0,0.9)'; ctx.shadowBlur = fontSize * 0.18; } ctx.textAlign = 'left'; // ADDENDUM 6: the caption always leads with the DEPTH in metres — that is the // number the user has to match against the object they are watching. The // second value is the active size control (locked angular width, or the // physical width when the lock is off). var sizeTxt = lock ? (Math.round(angle) + '\u00b0') : (width.toFixed(1) + 'm'); ctx.fillText('字幕 距' + dist.toFixed(2) + 'm · ' + sizeTxt, TRACK_X0 * w, lay.subLabelBaseline * h); ctx.textAlign = 'right'; ctx.fillText(Math.round(opacity * 100) + '%', TRACK_X1 * w, lay.subLabelBaseline * h); if (ctx.shadowColor !== undefined) { ctx.shadowColor = 'rgba(0,0,0,0)'; ctx.shadowBlur = 0; } var size = lay.subIconSize * h; var iconDy = lay.subIconDy * h; var labelDy = lay.subLabelDy * h; var labelPx = lay.subLabelFont * h; for (var i = 0; i < SUB_BUTTONS.length; i++) { var id = SUB_BUTTONS[i]; var cx = (lay.subFirstCx + i * lay.subSpacing) * w; var cy = lay.subBtnY * h; var bw = lay.subVisualW * w; var bh = lay.subVisualH * h; var hovered = view.hover === id; if (hovered) { ctx.fillStyle = 'rgba(78,161,255,0.32)'; rr(ctx, cx - bw / 2, cy - bh / 2, bw, bh, bh * 0.35); ctx.fill(); } if (id === 'sub_up') iconSubMove(ctx, cx, cy + iconDy, size, true); else if (id === 'sub_down') iconSubMove(ctx, cx, cy + iconDy, size, false); else if (id === 'sub_near') iconSubDepth(ctx, cx, cy + iconDy, size, false); else if (id === 'sub_far') iconSubDepth(ctx, cx, cy + iconDy, size, true); else if (id === 'sub_smaller') iconSubSize(ctx, cx, cy + iconDy, size, false); else if (id === 'sub_bigger') iconSubSize(ctx, cx, cy + iconDy, size, true); else if (id === 'sub_opaque_down') iconSubOpacity(ctx, cx, cy + iconDy, size, false, opacity); else if (id === 'sub_opaque_up') iconSubOpacity(ctx, cx, cy + iconDy, size, true, opacity); else if (id === 'sub_reset') iconSubReset(ctx, cx, cy + iconDy, size); drawLabel(ctx, LABELS[id], cx, cy + labelDy, labelPx, bw, '#ffffff'); if (hovered) { ctx.strokeStyle = ACCENT; ctx.lineWidth = Math.max(1.5, bh * 0.06); rr(ctx, cx - bw / 2, cy - bh / 2, bw, bh, bh * 0.35); ctx.stroke(); } } } // Vertical position pair (ADDENDUM 6): an arrow pointing up / down. Reads as // "move the subtitle strip up / down in the view". function iconSubMove(ctx, cx, cy, s, up) { ctx.save(); ctx.strokeStyle = '#ffffff'; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; var d = up ? -1 : 1; // canvas +y is down ctx.lineWidth = Math.max(1.5, s * 0.09); ctx.beginPath(); ctx.moveTo(cx, cy + d * s * 0.30); ctx.lineTo(cx, cy - d * s * 0.26); ctx.stroke(); ctx.beginPath(); ctx.moveTo(cx - s * 0.18, cy - d * s * 0.06); ctx.lineTo(cx, cy - d * s * 0.28); ctx.lineTo(cx + s * 0.18, cy - d * s * 0.06); ctx.stroke(); ctx.restore(); } // Depth pair (ADDENDUM 6): chevrons pointing at the viewer (near) or away // (far), with a small plane marking the strip. Reads as "bring the subtitles // closer / push them away". function iconSubDepth(ctx, cx, cy, s, far) { ctx.save(); ctx.strokeStyle = '#ffffff'; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; // the strip plane, offset toward the viewer end var px = cx + (far ? -s * 0.34 : s * 0.34); ctx.lineWidth = Math.max(1.5, s * 0.08); ctx.beginPath(); ctx.moveTo(px, cy - s * 0.24); ctx.lineTo(px, cy + s * 0.24); ctx.stroke(); // two chevrons: left = coming closer, right = going further ctx.lineWidth = Math.max(1.5, s * 0.075); var d = far ? 1 : -1; for (var k = 0; k < 2; k++) { var x = cx + d * (s * 0.02) + d * k * s * 0.22; ctx.beginPath(); ctx.moveTo(x - d * s * 0.11, cy - s * 0.18); ctx.lineTo(x + d * s * 0.05, cy); ctx.lineTo(x - d * s * 0.11, cy + s * 0.18); ctx.stroke(); } ctx.restore(); } // Size pair: the same 'A' at two sizes, plus a +/− mark. Reads as "make the // subtitle glyph bigger/smaller". function iconSubSize(ctx, cx, cy, s, bigger) { ctx.fillStyle = '#ffffff'; ctx.font = '700 ' + Math.max(8, Math.round(s * (bigger ? 0.6 : 0.38))) + 'px ' + FONT; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('A', cx - s * 0.1, cy); iconSign(ctx, cx + s * 0.3, cy, s, bigger); } // Opacity pair: a disc filled at the CURRENT opacity plus a +/− mark, so the // button doubles as a readout that brightens/dims with the value. function iconSubOpacity(ctx, cx, cy, s, up, opacity) { var r = s * 0.26; ctx.beginPath(); ctx.arc(cx - s * 0.1, cy, r, 0, Math.PI * 2); ctx.closePath(); ctx.fillStyle = 'rgba(255,255,255,' + (0.18 + 0.82 * clamp(opacity, 0, 1)).toFixed(3) + ')'; ctx.fill(); ctx.strokeStyle = '#ffffff'; ctx.lineWidth = Math.max(1.5, s * 0.06); ctx.stroke(); iconSign(ctx, cx + s * 0.3, cy, s, up); } function iconSign(ctx, cx, cy, s, plus) { ctx.save(); ctx.strokeStyle = '#ffffff'; ctx.lineWidth = Math.max(1.5, s * 0.075); ctx.lineCap = 'round'; var r = s * 0.13; ctx.beginPath(); ctx.moveTo(cx - r, cy); ctx.lineTo(cx + r, cy); ctx.stroke(); if (plus) { ctx.beginPath(); ctx.moveTo(cx, cy - r); ctx.lineTo(cx, cy + r); ctx.stroke(); } ctx.restore(); } // Reset: a circular arrow. function iconSubReset(ctx, cx, cy, s) { ctx.save(); ctx.strokeStyle = '#ffffff'; ctx.fillStyle = '#ffffff'; ctx.lineWidth = Math.max(1.5, s * 0.075); ctx.lineCap = 'round'; var r = s * 0.24; var a0 = Math.PI * 0.35; ctx.beginPath(); ctx.arc(cx, cy, r, a0, a0 + Math.PI * 1.5); ctx.stroke(); // Arrowhead at the arc's open end, pointing back along the tangent. var ax = cx + Math.cos(a0) * r; var ay = cy + Math.sin(a0) * r; var nx = Math.cos(a0); var ny = Math.sin(a0); var tx = Math.sin(a0); var ty = -Math.cos(a0); var hh = s * 0.14; ctx.beginPath(); ctx.moveTo(ax + tx * hh, ay + ty * hh); ctx.lineTo(ax - nx * hh * 0.6, ay - ny * hh * 0.6); ctx.lineTo(ax + nx * hh * 0.6, ay + ny * hh * 0.6); ctx.closePath(); ctx.fill(); ctx.restore(); } function iconPlay(ctx, cx, cy, s, color) { ctx.fillStyle = color; ctx.beginPath(); ctx.moveTo(cx - s * 0.26, cy - s * 0.34); ctx.lineTo(cx - s * 0.26, cy + s * 0.34); ctx.lineTo(cx + s * 0.34, cy); ctx.closePath(); ctx.fill(); } function iconPause(ctx, cx, cy, s, color) { ctx.fillStyle = color; var bw = s * 0.13; var bh = s * 0.72; var gap = s * 0.12; rr(ctx, cx - gap - bw, cy - bh / 2, bw, bh, bw * 0.4); ctx.fill(); rr(ctx, cx + gap, cy - bh / 2, bw, bh, bw * 0.4); ctx.fill(); } function iconSkip(ctx, cx, cy, s, color, dir) { ctx.save(); ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = Math.max(1.5, s * 0.09); ctx.lineCap = 'round'; var r = s * 0.30; var a0 = dir < 0 ? -Math.PI * 0.35 : -Math.PI * 0.15; var a1 = dir < 0 ? Math.PI * 1.15 : Math.PI * 1.35; ctx.beginPath(); ctx.arc(cx, cy, r, a0, a1, dir > 0); ctx.stroke(); // Arrowhead at the open end, pointing along the tangent. var ax = cx + Math.cos(a1) * r; var ay = cy + Math.sin(a1) * r; var nx = Math.cos(a1); var ny = Math.sin(a1); var tx = -ny; var ty = nx; if (dir > 0) { tx = -tx; ty = -ty; } var hh = s * 0.16; ctx.beginPath(); ctx.moveTo(ax + tx * hh, ay + ty * hh); ctx.lineTo(ax + nx * hh * 0.7, ay + ny * hh * 0.7); ctx.lineTo(ax - nx * hh * 0.7, ay - ny * hh * 0.7); ctx.closePath(); ctx.fill(); ctx.restore(); ctx.fillStyle = color; ctx.font = '700 ' + Math.max(8, Math.round(s * 0.42)) + 'px ' + FONT; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('10', cx, cy + s * 0.02); } function iconSubs(ctx, cx, cy, s, color, on) { var w = s * 0.86; var h = s * 0.6; ctx.lineWidth = Math.max(1.5, s * 0.075); ctx.strokeStyle = color; rr(ctx, cx - w / 2, cy - h / 2, w, h, h * 0.24); if (on) { ctx.fillStyle = 'rgba(78,161,255,0.25)'; ctx.fill(); } ctx.stroke(); ctx.fillStyle = color; ctx.font = '700 ' + Math.max(8, Math.round(s * 0.34)) + 'px ' + FONT; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('CC', cx, cy + s * 0.01); if (!on) { // OFF is not just "less bright": the CC glyph gets a slash, so the state // reads at a glance even with the accent tint lost against bright video. ctx.strokeStyle = color; ctx.lineWidth = Math.max(1.5, s * 0.08); ctx.beginPath(); ctx.moveTo(cx - w * 0.5, cy + h * 0.55); ctx.lineTo(cx + w * 0.5, cy - h * 0.55); ctx.stroke(); } } /* ------------------------------------------------------------------ * * Beam geometry — pure math + a texture generator. No WebXR types here so * the whole thing is unit-testable. * ------------------------------------------------------------------ */ function norm3(v) { if (!v) return null; var x = num(v.x), y = num(v.y), z = num(v.z); if (x == null || y == null || z == null) return null; var l = Math.sqrt(x * x + y * y + z * z); if (!(l > 1e-9)) return null; return { x: x / l, y: y / l, z: z / l }; } function cross3(a, b) { return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x }; } // Quaternion from an orthonormal basis given as its local axes, so the // resulting rotation maps local +X/+Y/+Z onto (ax, ay, az). function quatFromAxes(ax, ay, az) { var m00 = ax.x, m01 = ay.x, m02 = az.x; var m10 = ax.y, m11 = ay.y, m12 = az.y; var m20 = ax.z, m21 = ay.z, m22 = az.z; var q = { x: 0, y: 0, z: 0, w: 1 }; var tr = m00 + m11 + m22; var s; if (tr > 0) { s = Math.sqrt(tr + 1) * 2; q.w = 0.25 * s; q.x = (m21 - m12) / s; q.y = (m02 - m20) / s; q.z = (m10 - m01) / s; } else if (m00 > m11 && m00 > m22) { s = Math.sqrt(1 + m00 - m11 - m22) * 2; q.w = (m21 - m12) / s; q.x = 0.25 * s; q.y = (m01 + m10) / s; q.z = (m02 + m20) / s; } else if (m11 > m22) { s = Math.sqrt(1 + m11 - m00 - m22) * 2; q.w = (m02 - m20) / s; q.x = (m01 + m10) / s; q.y = 0.25 * s; q.z = (m12 + m21) / s; } else { s = Math.sqrt(1 + m22 - m00 - m11) * 2; q.w = (m10 - m01) / s; q.x = (m02 + m20) / s; q.y = (m12 + m21) / s; q.z = 0.25 * s; } return q; } var WORLD_UP = { x: 0, y: 1, z: 0 }; var WORLD_BACK = { x: 0, y: 0, z: 1 }; // Component of `v` perpendicular to the unit vector `u` (null when parallel). function perp(u, v) { var d = u.x * v.x + u.y * v.y + u.z * v.z; return norm3({ x: v.x - u.x * d, y: v.y - u.y * d, z: v.z - u.z * d }); } // Orientation for the beam quad. // // local +X is the quad's width/long axis and also the texture's u axis, and it // is mapped onto `dir`: the beam then lies ALONG the ray (a quad's local -Z is // its plane normal, so mapping -Z onto dir would lay the strip across the ray // and it could never read as a laser). // // local -Z is the face normal. It must be perpendicular to `dir` AND point at // the eye, otherwise the ribbon is seen edge-on and effectively disappears. // // A world-up bias is NOT good enough: measured on device, a hand-held ray gave // a near-vertical normal while the viewer was level with the beam, a 68.7 deg // angle between normal and view direction, and only ~2 mm of projected width // at 0.8 m - i.e. invisible. In viewer space the eye IS the origin, so the // direction from the beam to the eye is simply -pos; take the component of // that perpendicular to the beam axis. // // Texture consequence: u = 0 is the local -X end = `origin`, so the gradient // (bright at u = 0) runs origin -> hit. function beamQuat(dir, pos, crossed) { var x = norm3(dir); if (!x) return { x: 0, y: 0, z: 0, w: 1 }; var toEye = null; if (pos) { var pl = Math.sqrt(pos.x * pos.x + pos.y * pos.y + pos.z * pos.z); if (pl > 1e-4) toEye = { x: -pos.x / pl, y: -pos.y / pl, z: -pos.z / pl }; } var n = toEye ? perp(x, toEye) : null; // face the viewer when possible if (!n) n = perp(x, WORLD_UP); if (!n) n = perp(x, WORLD_BACK); if (!n) return { x: 0, y: 0, z: 0, w: 1 }; // The second ribbon of the crossed pair is rolled 90 deg about the beam axis. if (crossed) n = norm3(cross3(x, n)) || n; var z = { x: -n.x, y: -n.y, z: -n.z }; // local +Z; the front normal is -Z = n var y = cross3(z, x); // right-handed basis: Y = Z x X return quatFromAxes(x, y, z); } // Soft laser gradient, premultiplied RGBA: bright at u = 0 (the origin end), // gone at u = 1, feathered across v so the beam has no hard edge. function buildBeamTexture(w, h) { var data = new Uint8Array(w * h * 4); for (var y = 0; y < h; y++) { var v = (y + 0.5) / h; var edge = Math.sin(Math.PI * v); edge = edge * edge; for (var x = 0; x < w; x++) { var u = (x + 0.5) / w; var a = (0.15 + 0.85 * Math.pow(1 - u, 1.3)) * edge; if (a > 1) a = 1; else if (a < 0) a = 0; var i = (y * w + x) * 4; data[i] = Math.round(78 * a); // ACCENT, premultiplied by a data[i + 1] = Math.round(161 * a); data[i + 2] = Math.round(255 * a); data[i + 3] = Math.round(255 * a); } } return data; } /* ------------------------------------------------------------------ * * hitTest() — pure geometry of (nx, ny, w, h). * Mode is inferred from the panel aspect ratio. Every button (media row and * subtitle row) is tested before the track, so no button can ever be shadowed * by the seek band; the hit bands themselves do not overlap. * ------------------------------------------------------------------ */ function hitTest(nx, ny, w, h, modeHint) { if (!(w > 0) || !(h > 0)) return null; if (typeof nx !== 'number' || typeof ny !== 'number') return null; if (!(nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1)) return null; var mode = (modeHint === 'expanded' || modeHint === 'locked') ? modeHint : modeFor(w, h); var lay = LAYOUT[mode]; // Locked panel: one target, the padlock, and it is a free hit over most of // the pill (the pill is small, so padding is not needed - and a bigger // window would make the summon gesture press it by accident). if (mode === 'locked') { if (Math.abs(nx - lay.lockCx) <= lay.lockHitHalfW && Math.abs(ny - lay.lockCy) <= lay.lockHitHalfH) { return { type: 'lock' }; } return null; } if (mode === 'expanded') { // ADDENDUM 8: the drag strip first. Its band (0..0.20) does not overlap the // seek band (0.30..0.52) or the button bands (0.52+), so order is cosmetic. if (ny >= lay.viewHitY0 && ny <= lay.viewHitY1 && nx >= lay.viewStripX0 && nx <= lay.viewStripX1) { return { type: 'view_drag' }; } var i, cx, y0 = lay.btnHitY0, y1 = lay.btnHitY1; for (i = 0; i < BUTTONS.length; i++) { cx = lay.btnFirstCx + i * lay.btnSpacing; if (ny >= y0 && ny <= y1 && nx >= cx - lay.btnHitHalfW && nx <= cx + lay.btnHitHalfW) { return { type: BUTTONS[i] }; } } var sy0 = lay.subHitY0, sy1 = lay.subHitY1; for (i = 0; i < SUB_BUTTONS.length; i++) { cx = lay.subFirstCx + i * lay.subSpacing; if (ny >= sy0 && ny <= sy1 && nx >= cx - lay.subHitHalfW && nx <= cx + lay.subHitHalfW) { return { type: SUB_BUTTONS[i] }; } } } if (ny >= lay.trackHitY0 && ny <= lay.trackHitY1) { var value = clamp((nx - TRACK_X0) / (TRACK_X1 - TRACK_X0), 0, 1); return { type: 'seek', value: value }; } return null; } /* ------------------------------------------------------------------ * * Module state (closures only — nothing leaks onto __JFVR except the * documented API). * ------------------------------------------------------------------ */ var S = { // 'collapsed' | 'expanded' | 'locked'. ADDENDUM 7b: "locked" is a minimal // panel carrying only the padlock. The mode is NOT reset on hide() any more — // the layer keeps the size it will be shown at, so the summon window is the // full panel rect and re-showing needs no resize. mode: 'expanded', shown: false, hover: null, subtitlesOn: false, video: null, getExtra: null, onActionCb: null, reticle: null, autoHideTimer: null, // visibility / opacity (ADDENDUM 2) opacity: 1, layerOpacityOk: false, // latest setPointer() payload, plus the beam quad it drives pointer: null, beamOn: false, beamSig: null, beamLayer: null, beamLayer2: null, beamTex: null, // padlock (ADDENDUM 7b) — panel state only, no own layer lockOn: false, hold: false, // ADDENDUM 8: drag in progress -> freeze auto-hide // XR resources canvas: null, ctx2d: null, gl: null, prog: null, attrLoc: -1, vbo: null, tex: null, fbo: null, binding: null, layer: null, hookFn: null, created: false, // redraw bookkeeping lastSig: null, lastPtrSig: null, lastDrawTime: -1e9, forceRedraw: true }; var FS = [ '#version 300 es', 'precision mediump float;', 'in vec2 vUv;', 'uniform sampler2D uTex;', 'out vec4 outColor;', 'void main(){ outColor = texture(uTex, vUv); }' ].join('\n'); function setErr(msg) { var s = stats(); if (s) s.ctlErr = msg; } // Single place that keeps the ctl* diagnostic keys in sync with the module. function updateVisibilityStats() { var s = stats(); if (!s) return; s.ctlVisible = S.shown; s.ctlHidden = !S.shown; s.ctlMode = S.mode; s.ctlLock = !!S.lockOn; s.ctlBeamOn = S.beamOn; s.ctlOpacity = S.opacity; s.ctlPointer = S.pointer ? ((S.pointer.visible ? S.pointer.source : 'gaze') + (S.pointer.hit ? ' @' + S.pointer.hit.nx.toFixed(2) + ',' + S.pointer.hit.ny.toFixed(2) : ' @-')) : '(none)'; } function init() { S.mode = 'expanded'; S.shown = false; S.hover = null; S.opacity = 1; S.pointer = null; S.beamOn = false; S.beamSig = null; var s = stats(); if (s) { s.ctlDraws = s.ctlDraws || 0; s.ctlLastAction = s.ctlLastAction || null; s.ctlHover = null; s.ctlErr = s.ctlErr || null; s.ctlLock = !!S.lockOn; s.ctlMode = S.lockOn ? 'locked' : 'expanded'; } updateVisibilityStats(); } /* ------------------------------------------------------------------ * * Media readers — injected via setVideo(), else read from the element. * ------------------------------------------------------------------ */ function reader(extra, name) { if (!extra) return null; var fn = extra[name]; if (typeof fn === 'function') { try { return fn(); } catch (e) { return null; } } return fn; } function readCurrentTime() { var v = reader(S.getExtra, 'currentTime'); if (v != null) return num(v); var el = S.video; return el ? num(el.currentTime) : null; } function readDuration() { var v = reader(S.getExtra, 'duration'); if (v != null) return num(v); var el = S.video; return el ? num(el.duration) : null; } function readBuffered() { var v = reader(S.getExtra, 'buffered'); if (v != null) return num(v); var el = S.video; if (!el || !el.buffered) return null; try { var len = el.buffered.length; if (!len) return null; var dur = readDuration(); if (!(dur > 0)) return null; return clamp(el.buffered.end(len - 1) / dur, 0, 1); } catch (e) { return null; } } function readPlaying() { var v = reader(S.getExtra, 'playing'); if (typeof v === 'boolean') return v; var el = S.video; return el ? (el.paused === false) : false; } function readSubtitles() { var v = reader(S.getExtra, 'subtitlesOn'); if (typeof v === 'boolean') return v; // main.js keeps the toggle in the SHARED state (state.subtitles), and only // ever passes a video to setVideo(); reading the module-local S.subtitlesOn // alone meant this always returned false, so the button never showed ON. var n = ns(); if (n && n.state && typeof n.state.subtitles === 'boolean') return n.state.subtitles; return !!S.subtitlesOn; } // What the cursor is currently over, so the button under it highlights. The // pointer position was already reduced to a hitTest() action by the draw path, // so this is just that lookup - and it means hover feedback needs no extra // plumbing from 90-main.js. // ADDENDUM 8: current video-window angles in DEGREES, read from the shared // state that 90-main.js owns (it owns the video layer's transform). function readViewAngles() { var n = ns(); var st = (n && n.state) || {}; var yaw = num(st.videoYaw); var pitch = num(st.videoPitch); return { yawDeg: yaw == null ? 0 : yaw * 180 / Math.PI, pitchDeg: pitch == null ? 0 : pitch * 180 / Math.PI }; } function readHover() { var extra = reader(S.getExtra, 'hover'); if (typeof extra === 'string') return extra; var p = S.pointer; if (!p || !p.hit) return null; var px = PANEL_PX[S.mode] || PANEL_PX.expanded; var a = hitTest(p.hit.nx, p.hit.ny, px.w, px.h, S.mode); if (!a) return null; return a.type === 'seek' ? 'track' : a.type; } // Current subtitle size/opacity/angle/depth for the ADDENDUM 4/6 row. main.js // owns the values (state.subPlacement / state.subOpacity / state.subAngleDeg, // persisted by main); this module only reads them so draw() can render the readout. function readSubValues() { var n = ns(); var st = (n && n.state) || {}; var p = st.subPlacement || {}; var width = num(p.width); var z = num(p.z); var opacity = num(st.subOpacity); var angle = num(st.subAngleDeg); return { width: width == null ? SUB_DEFAULT.width : width, opacity: opacity == null ? SUB_DEFAULT.opacity : clamp(opacity, 0, 1), angleDeg: angle == null ? SUB_DEFAULT.angleDeg : angle, lock: (typeof st.subLockAngle === 'boolean') ? st.subLockAngle : SUB_DEFAULT.lock, // Viewer space forward is -Z, so the DEPTH the user perceives is |z|. dist: z == null ? SUB_DEFAULT.dist : Math.abs(z) }; } // The cursor position draw() renders last. Absent (null) when the input ray // does not point at the panel, so there is nothing to highlight. function viewPointer() { var p = S.pointer; if (!p || !p.hit) return null; return { nx: p.hit.nx, ny: p.hit.ny, pressed: !!p.pressed }; } function buildView() { var v = { playing: readPlaying(), currentTime: readCurrentTime() || 0, duration: readDuration() || 0, buffered: readBuffered(), subtitlesOn: readSubtitles(), mode: S.mode, hover: readHover(), pointer: viewPointer(), lock: !!S.lockOn, // ADDENDUM 8: the video window's angles, in degrees, for the drag strip. view: readViewAngles(), sub: readSubValues() }; // Diagnostics: what the bar actually rendered, so the CC state can be checked // from CDP (stats.ctlSubsOn / ctlSubDist) without reading the canvas. var st = stats(); if (st) { st.ctlSubsOn = v.subtitlesOn; st.ctlSubDist = v.sub.dist; st.ctlSubAngle = v.sub.angleDeg; st.ctlSubLock = v.sub.lock; } return v; } // Media/canvas state only — the pointer is tracked separately (ptrSigOf) so a // moving ray can be redrawn at a capped rate without starving media changes. function sigOf(v) { return [ v.mode, v.playing ? 1 : 0, v.subtitlesOn ? 1 : 0, v.lock ? 1 : 0, v.hover || '', Math.floor(v.currentTime), Math.floor(v.duration), v.buffered == null ? '' : Math.round(v.buffered * 200), Math.round(v.sub.width * 100), Math.round(v.sub.opacity * 100), Math.round(v.sub.angleDeg), v.sub.lock ? 1 : 0, Math.round(v.sub.dist * 100), Math.round(v.view.yawDeg), Math.round(v.view.pitchDeg) ].join('|'); } function ptrSigOf(v) { if (!v.pointer) return '-'; return Math.round(v.pointer.nx * 400) + '/' + Math.round(v.pointer.ny * 400) + (v.pointer.pressed ? '!' : ''); } /* ------------------------------------------------------------------ * * XR lifecycle. * ------------------------------------------------------------------ */ function compile(gl, type, src) { var n = ns(); if (n && typeof n.compileShader === 'function') return n.compileShader(gl, type, src); var sh = gl.createShader(type); gl.shaderSource(sh, src); gl.compileShader(sh); if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) { throw new Error(gl.getShaderInfoLog(sh) || 'shader compile failed'); } return sh; } function makeProgram(gl) { var n = ns(); var vsSrc = (n && n.QUAD_VS) ? n.QUAD_VS : null; if (!vsSrc) throw new Error('missing __JFVR.QUAD_VS'); var prog = gl.createProgram(); gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, vsSrc)); gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, FS)); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { throw new Error(gl.getProgramInfoLog(prog) || 'controls program link failed'); } gl.useProgram(prog); return prog; } function bindGeometry(gl, prog) { var n = ns(); if (n && typeof n.bindFullscreenTriangle === 'function') { // Core helper returns the aPos attribute location; it owns the VBO. S.attrLoc = n.bindFullscreenTriangle(gl, prog); S.vbo = null; return; } var buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); var loc = gl.getAttribLocation(prog, 'aPos'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); S.attrLoc = loc; S.vbo = buf; } function applyModeToLayer() { var px = PANEL_PX[S.mode]; var m = PANEL_M[S.mode]; if (S.canvas) { S.canvas.width = px.w; S.canvas.height = px.h; S.ctx2d = S.canvas.getContext('2d'); } if (S.layer) { try { S.layer.width = m.w; S.layer.height = m.h; } catch (e) { /* read-only on some builds: layer keeps its size */ } } S.forceRedraw = true; updateVisibilityStats(); } // The bar layer is created once per session and never rebuilt: hiding sets // layer.opacity to 0 *and* drops it from the render state, so the bar cannot // stay on screen on a runtime that ignores layer.opacity. main.js still finds // it through getLayer() for its ray -> panel math while it is hidden. function applyBarVisible() { var n = ns(); var l = S.layer; if (!l) return; if (S.layerOpacityOk) { try { l.opacity = S.shown ? S.opacity : 0; } catch (e) { S.layerOpacityOk = false; } } if (S.shown) { if (n && typeof n.addLayer === 'function') n.addLayer(l); } else if (n && typeof n.removeLayer === 'function') { n.removeLayer(l); } } // Probe once whether the runtime honours layer.opacity; when it does not the // 2D context alpha dims the same pixels instead (see drawIntoCanvas). function probeLayerOpacity(l) { try { if (!l || !('opacity' in l)) return false; var prev = l.opacity; l.opacity = 0.5; var ok = (l.opacity === 0.5); l.opacity = prev; return ok; } catch (e) { return false; } } function uploadTexture() { if (!S.gl || !S.tex || !S.canvas) return; S.gl.bindTexture(S.gl.TEXTURE_2D, S.tex); S.gl.pixelStorei(S.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); S.gl.texImage2D(S.gl.TEXTURE_2D, 0, S.gl.RGBA, S.gl.RGBA, S.gl.UNSIGNED_BYTE, S.canvas); } function drawIntoCanvas(view) { S.ctx2d.globalAlpha = S.layerOpacityOk ? 1 : S.opacity; draw(S.ctx2d, S.canvas.width, S.canvas.height, view); S.ctx2d.globalAlpha = 1; uploadTexture(); } function present(frame, layer, tex, fbW, fbH) { if (!S.gl || !S.binding || !layer || !tex) return; var sub = S.binding.getSubImage(layer, frame); if (!sub || !sub.colorTexture) return; var gl = S.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, S.fbo); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, sub.colorTexture, 0); gl.viewport(0, 0, sub.colorTextureWidth || fbW, sub.colorTextureHeight || fbH); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.useProgram(S.prog); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex); gl.drawArrays(gl.TRIANGLES, 0, 3); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } function presentBar(frame) { if (!S.layer || !S.tex || !S.canvas) return; present(frame, S.layer, S.tex, S.canvas.width, S.canvas.height); } function presentBeam(frame) { if (!S.beamOn || !S.beamLayer || !S.beamTex) return; present(frame, S.beamLayer, S.beamTex, BEAM_TEX.w, BEAM_TEX.h); if (S.beamLayer2) present(frame, S.beamLayer2, S.beamTex, BEAM_TEX.w, BEAM_TEX.h); } /* ------------------------------------------------------------------ * * Beam: transform + visibility. Both origin/dir and the beam layer live in * VIEWER space (90-main.js computes the pointer there), so the ray * coordinates are used directly, with no per-frame space conversion. * ------------------------------------------------------------------ */ // Distance from the ray origin to the panel plane, used only when main does // not supply a hit distance. Same plane math main.js uses. function panelDistance(p) { var t = (S.layer && S.layer.transform) ? S.layer.transform.position : null; var cz = t ? num(t.z) : null; if (cz == null) cz = -PANEL_Z; if (!p.dir || Math.abs(p.dir.z) < 1e-6) return null; var d = (cz - p.origin.z) / p.dir.z; return d > 0 ? d : null; } // ADDENDUM 11b: the beam reaches the panel plane whenever the ray meets it, // even when the intersection is off the panel (there is simply no cursor then). // Previously it fell back to a fixed length without a hit, so an edge-aimed // beam stopped short of the plane while the cursor was clamped to the border. function beamLength(p) { var d = num(p.distance); if (d == null) d = panelDistance(p); if (d == null || !(d > BEAM_L_MIN)) return BEAM_L_DEFAULT; return clamp(d, BEAM_L_MIN, BEAM_L_MAX); } function beamSigOf(p, len) { return [ Math.round(p.origin.x * 1000), Math.round(p.origin.y * 1000), Math.round(p.origin.z * 1000), Math.round(p.dir.x * 1000), Math.round(p.dir.y * 1000), Math.round(p.dir.z * 1000), Math.round(len * 1000) ].join('|'); } function updateBeamTransform() { var p = S.pointer; if (!p || !p.origin || !p.dir || !S.beamLayer) return; var len = beamLength(p); var sig = beamSigOf(p, len); if (sig === S.beamSig) return; // 1 mm granularity: no churn S.beamSig = sig; var mid = { x: p.origin.x + p.dir.x * len * 0.5, y: p.origin.y + p.dir.y * len * 0.5, z: p.origin.z + p.dir.z * len * 0.5 }; try { S.beamLayer.transform = new XRRigidTransform(mid, beamQuat(p.dir, mid, false)); S.beamLayer.width = len; S.beamLayer.height = BEAM_H; if (S.beamLayer2) { S.beamLayer2.transform = new XRRigidTransform(mid, beamQuat(p.dir, mid, true)); S.beamLayer2.width = len; S.beamLayer2.height = BEAM_H; } } catch (e) { setErr('beam transform: ' + ((e && e.message) || e)); } } // The beam is an AIMING GUIDE: it must be visible whenever an input source is // pointing, independently of whether the bar is shown. Requiring S.shown here // was a bug - the bar only appears on activation, so the user could never aim // at it before pinching. function applyBeamVisible() { var n = ns(); var l = S.beamLayer; var on = !!(S.pointer && S.pointer.visible && S.pointer.beam !== false && l); if (on === S.beamOn) return; S.beamOn = on; var both = [S.beamLayer, S.beamLayer2]; for (var i = 0; i < both.length; i++) { var b = both[i]; if (!b) continue; try { b.opacity = on ? 1 : 0; } catch (e) { void e; } if (n) { if (on && typeof n.addLayer === 'function') n.addLayer(b); else if (!on && typeof n.removeLayer === 'function') n.removeLayer(b); } } updateVisibilityStats(); } function hook(frame, time, session) { try { if (!S.canvas || !S.ctx2d) return; // NOTE: this must NOT early-return on !S.shown. The beam is presented every // frame regardless of bar visibility; only the BAR work is gated below. if (S.shown) { var view = buildView(); var sig = sigOf(view); var psig = ptrSigOf(view); var need = (sig !== S.lastSig) || (psig !== S.lastPtrSig); if (!need && view.playing && (time - S.lastDrawTime) > 500) need = true; // The cursor tracks the ray every frame; cap pointer-only redraws at ~30 Hz. if (need && sig === S.lastSig && (time - S.lastDrawTime) < MIN_UPLOAD_MS) need = false; if (S.forceRedraw) need = true; if (need) { drawIntoCanvas(view); S.lastSig = sig; S.lastPtrSig = psig; S.lastDrawTime = time; S.forceRedraw = false; var s = stats(); if (s) { s.ctlDraws = (s.ctlDraws || 0) + 1; s.ctlHover = view.hover || ''; } updateVisibilityStats(); } } // Beam placement follows the pointer even while the bar is hidden. if (S.beamOn) updateBeamTransform(); presentBeam(frame); if (S.shown) presentBar(frame); } catch (e) { setErr('hook: ' + ((e && e.message) || e)); } void session; } function create(session, glContextOrNull) { try { if (S.created && S.layer) return S.layer; if (!session) { log('controls.create: no session'); return null; } if (typeof XRWebGLBinding === 'undefined') { log('controls.create: no XRWebGLBinding'); setErr('no XRWebGLBinding'); return null; } var n = ns(); // ADDENDUM 5: the panel lives in LOCAL space, not viewer space. Gaze // selection needs the panel to hold a stable world pose - if it were // head-locked the view centre would always map to its centre and no // individual button could ever be targeted. 90-main.js drives the lazy // follow by writing layer.transform every frame. var space = (n && n.refSpace) || (n && n.state && n.state.refSpace); if (!space) { log('controls.create: no refSpace'); setErr('no refSpace'); return null; } var canvas = document.createElement('canvas'); canvas.width = PANEL_PX.expanded.w; canvas.height = PANEL_PX.expanded.h; var ctx2d = canvas.getContext('2d'); if (!ctx2d) { log('controls.create: no 2d context'); setErr('no 2d context'); return null; } var gl = glContextOrNull; if (!gl) { gl = (n && typeof n.xrGl === 'function') ? n.xrGl(true) : document.createElement('canvas').getContext('webgl2', { xrCompatible: true, alpha: true, premultipliedAlpha: true, antialias: false, depth: false }); } if (!gl) { log('controls.create: no webgl2'); setErr('no webgl2'); return null; } var prog = makeProgram(gl); bindGeometry(gl, prog); var tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); gl.disable(gl.DEPTH_TEST); gl.disable(gl.BLEND); gl.uniform1i(gl.getUniformLocation(prog, 'uTex'), 0); var fbo = gl.createFramebuffer(); var binding = new XRWebGLBinding(session, gl); var opts = { space: space, layout: 'mono', alpha: true, width: PANEL_M.expanded.w, height: PANEL_M.expanded.h, viewPixelWidth: canvas.width, viewPixelHeight: canvas.height }; if (typeof XRRigidTransform !== 'undefined') { opts.transform = new XRRigidTransform({ x: 0, y: PANEL_Y, z: -PANEL_Z }); } var layer = binding.createQuadLayer(opts); if (!layer) { log('controls.create: createQuadLayer returned null'); setErr('createQuadLayer null'); return null; } S.canvas = canvas; S.ctx2d = ctx2d; S.gl = gl; S.prog = prog; S.tex = tex; S.fbo = fbo; S.binding = binding; S.layer = layer; S.created = true; S.lastSig = null; S.lastPtrSig = null; S.lastDrawTime = -1e9; S.forceRedraw = true; S.layerOpacityOk = probeLayerOpacity(layer); // --- pointer beam: a second, independent quad layer --------------- // Built once and reused; only its transform changes per frame. A runtime // without XRRigidTransform (or without a spare layer) just means no beam // guide - the bar keeps working. if (typeof XRRigidTransform !== 'undefined') { try { S.beamLayer = binding.createQuadLayer({ space: space, layout: 'mono', alpha: true, width: BEAM_L_DEFAULT, height: BEAM_H, viewPixelWidth: BEAM_TEX.w, viewPixelHeight: BEAM_TEX.h, transform: new XRRigidTransform({ x: 0, y: 0, z: -BEAM_L_DEFAULT * 0.5 }) }) || null; // Second ribbon, rolled 90 deg about the beam axis (see beamQuat). // A single flat ribbon is seen edge-on whenever the beam points away // from the viewer; a crossed pair guarantees that at least 0.707 of // the width faces the eye from any angle. S.beamLayer2 = binding.createQuadLayer({ space: space, layout: 'mono', alpha: true, width: BEAM_L_DEFAULT, height: BEAM_H, viewPixelWidth: BEAM_TEX.w, viewPixelHeight: BEAM_TEX.h, transform: new XRRigidTransform({ x: 0, y: 0, z: -BEAM_L_DEFAULT * 0.5 }) }) || null; S.beamTex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, S.beamTex); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); // Raw pixels are already premultiplied; do not premultiply twice. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, BEAM_TEX.w, BEAM_TEX.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, buildBeamTexture(BEAM_TEX.w, BEAM_TEX.h)); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); // Starts hidden like the bar (see applyBeamVisible). try { S.beamLayer.opacity = 0; } catch (e) { void e; } try { if (S.beamLayer2) S.beamLayer2.opacity = 0; } catch (e) { void e; } } catch (e) { log('controls: beam layer unavailable:', (e && e.message) || e); S.beamLayer = null; S.beamLayer2 = null; } } else { log('controls: no XRRigidTransform, pointer beam disabled'); } // Sync the freshly created (expanded-sized) layer to the current mode. applyModeToLayer(); // ADDENDUM 2: created hidden. Both layers stay allocated for the session; // show()/hide() toggle opacity + render-state membership only. applyBarVisible(); applyBeamVisible(); var hk = hook; S.hookFn = hk; if (n && typeof n.addFrameHook === 'function') n.addFrameHook(hk); setErr(null); log('controls layer created (hidden, ' + S.mode + ', beam=' + !!S.beamLayer + ')'); return layer; } catch (e) { setErr('create: ' + ((e && e.message) || e)); log('controls.create failed:', (e && e.message) || e); try { teardown(); } catch (e2) { void e2; } return null; } } function teardown() { var n = ns(); if (S.hookFn && n && typeof n.removeFrameHook === 'function') { try { n.removeFrameHook(S.hookFn); } catch (e) { void e; } } ['layer', 'beamLayer', 'beamLayer2'].forEach(function (key) { if (S[key] && n && typeof n.removeLayer === 'function') { try { n.removeLayer(S[key]); } catch (e) { void e; } } }); var gl = S.gl; if (gl) { try { if (S.tex) gl.deleteTexture(S.tex); if (S.beamTex) gl.deleteTexture(S.beamTex); if (S.fbo) gl.deleteFramebuffer(S.fbo); if (S.vbo) gl.deleteBuffer(S.vbo); if (S.prog) gl.deleteProgram(S.prog); } catch (e) { void e; } } S.canvas = null; S.ctx2d = null; S.gl = null; S.prog = null; S.tex = null; S.beamTex = null; S.fbo = null; S.vbo = null; S.binding = null; S.layer = null; S.beamLayer = null; S.beamLayer2 = null; S.hookFn = null; S.created = false; S.pointer = null; S.beamOn = false; S.beamSig = null; S.layerOpacityOk = false; // The session is gone: a later create() must start hidden again, at the // expanded size (the summon window is the full panel rect), and UNLOCKED - // 90-main.js also clears it, but the module must not depend on that. S.shown = false; S.mode = 'expanded'; S.lockOn = false; updateVisibilityStats(); } function destroy() { try { if (S.autoHideTimer != null) { clearTimeout(S.autoHideTimer); S.autoHideTimer = null; } } catch (e) { void e; } try { teardown(); } catch (e) { void e; } S.forceRedraw = true; S.lastSig = null; S.lastPtrSig = null; } /* ------------------------------------------------------------------ * * Public API: the INTERFACES.md surface, plus setReticle which is kept for * the pre-ADDENDUM-2 gaze-only input path (setPointer supersedes it). * ------------------------------------------------------------------ */ function setVideo(videoEl, getExtra) { S.video = videoEl || null; S.getExtra = getExtra || null; } function onAction(cb) { S.onActionCb = (typeof cb === 'function') ? cb : null; } // Visible + expanded, then auto-hide. ADDENDUM 2: this is the only way the // bar becomes visible - create() leaves it hidden. function show(autoHideMs) { // ADDENDUM 7b: which panel comes up is decided by the lock state. S.mode = S.lockOn ? 'locked' : 'expanded'; S.shown = true; applyModeToLayer(); applyBarVisible(); S.beamSig = null; // re-place the beam for this show applyBeamVisible(); if (S.beamOn) updateBeamTransform(); restartAutoHide(autoHideMs); updateVisibilityStats(); } function restartAutoHide(autoHideMs) { if (S.autoHideTimer != null) { clearTimeout(S.autoHideTimer); S.autoHideTimer = null; } if (S.hold) return; // a drag is in progress: stay up var n = ns(); var def = (n && n.state && typeof n.state.ctlAutoHideMs === 'number') ? n.state.ctlAutoHideMs : 4000; var ms = (typeof autoHideMs === 'number' && isFinite(autoHideMs) && autoHideMs > 0) ? autoHideMs : def; S.autoHideTimer = setTimeout(function () { S.autoHideTimer = null; hide(); }, ms); } // ADDENDUM 8: pause the auto-hide while a hold-style interaction (the picture // drag) is running. Without this the panel would disappear mid-drag, because // the timer that show() armed keeps running. function hold(on) { var v = !!on; if (v === S.hold) return; S.hold = v; if (v) { if (S.autoHideTimer != null) { clearTimeout(S.autoHideTimer); S.autoHideTimer = null; } } else if (S.shown) { restartAutoHide(); } var s = stats(); if (s) s.ctlHold = v; } // Fully hidden: no bar, no beam, no cursor, and no further drawing/uploading // until the next show(). The MODE is kept so the layer stays at the size it will // be shown at, which keeps the summon window (main.js ray-casts the layer) at // the full panel rect rather than a 5 cm strip. function hide() { if (S.autoHideTimer != null) { clearTimeout(S.autoHideTimer); S.autoHideTimer = null; } S.shown = false; S.hold = false; var hs = stats(); if (hs) hs.ctlHold = false; applyBarVisible(); applyBeamVisible(); updateVisibilityStats(); } function isVisible() { return S.shown; } // 0..1 dimmer for the bar, applied live to the XR layer (or to the canvas // alpha when the runtime has no layer.opacity). Never rebuilds the layer. function setOpacity(a) { var v = num(a); S.opacity = (v == null) ? 1 : clamp(v, 0, 1); if (S.layer && S.layerOpacityOk) { try { S.layer.opacity = S.shown ? S.opacity : 0; } catch (e) { S.layerOpacityOk = false; } } S.forceRedraw = true; updateVisibilityStats(); } function getOpacity() { return S.opacity; } /* ------------------------------------------------------------------ * * ADDENDUM 7b padlock state. * * Locking does NOT hide the panel here: 90-main.js decides that by calling * show() again, which re-picks the mode from S.lockOn and restarts the * auto-hide timer. So "lock, then the lock icon auto-hides like the panel" * falls out of the existing lifecycle instead of a second one. * ------------------------------------------------------------------ */ function setLock(on) { var v = !!on; if (v === S.lockOn) return; S.lockOn = v; if (S.shown) { S.mode = v ? 'locked' : 'expanded'; // swap the panel in place applyModeToLayer(); } var st = stats(); if (st) st.ctlLock = v; } function getLock() { return !!S.lockOn; } // Per-frame pointer from 90-main.js. Coordinates are in VIEWER space - the // same space as the head-locked bar and the beam quad - and are copied here // so the module never holds on to main's mutable object. function setPointer(p) { if (!p || typeof p !== 'object') { S.pointer = null; applyBeamVisible(); updateVisibilityStats(); return; } var origin = norm3(p.origin) ? { x: num(p.origin.x), y: num(p.origin.y), z: num(p.origin.z) } : null; var dir = norm3(p.dir); var hit = (p.hit && num(p.hit.nx) != null && num(p.hit.ny) != null) ? { nx: clamp(p.hit.nx, 0, 1), ny: clamp(p.hit.ny, 0, 1) } : null; S.pointer = { visible: !!p.visible && !!origin && !!dir, // `beam` MUST be carried through: the beam is only shown for an accurate // controller ray. Dropping the field made `beam !== false` always true, so // gaze aiming drew a degenerate beam from the eye itself. beam: p.beam !== false, source: (typeof p.source === 'string') ? p.source : '', origin: origin, dir: dir, hit: hit, distance: num(p.distance), pressed: !!p.pressed }; applyBeamVisible(); if (S.beamOn) updateBeamTransform(); updateVisibilityStats(); } function setReticle(nx, ny) { if (typeof nx === 'number' && typeof ny === 'number' && isFinite(nx) && isFinite(ny)) { S.reticle = { nx: clamp(nx, 0, 1), ny: clamp(ny, 0, 1) }; } else { S.reticle = null; } } function handleSelect(inputSource, frame) { // Unified pointer (ADDENDUM 2) wins when main set one; setReticle() stays as // the fallback for the older gaze-only path. With NEITHER there is nothing to // press: the old "assume the panel centre" fallback silently pressed whatever // button happened to live at (0.5, 0.5), which is a seek/skip in disguise. var pt = (S.pointer && S.pointer.hit) || S.reticle; if (!pt) { updateVisibilityStats(); return null; } var px = PANEL_PX[S.mode] || PANEL_PX.expanded; // The mode MUST be passed: the runtime does not tell us which panel we are // showing, and "collapsed" (a thin strip) shares no safe invariant with the // locked panel. var action = hitTest(pt.nx, pt.ny, px.w, px.h, S.mode); var s = stats(); if (s) s.ctlHover = (action ? (action.type === 'seek' ? 'track' : action.type) : ''); if (action) { if (s) s.ctlLastAction = action.type; if (S.onActionCb) { try { S.onActionCb(action); } catch (e) { setErr('onAction: ' + ((e && e.message) || e)); } } } updateVisibilityStats(); void inputSource; void frame; return action; } var Controls = { // pure / testable draw: draw, hitTest: hitTest, // lifecycle init: init, create: create, destroy: destroy, // state / input setVideo: setVideo, onAction: onAction, show: show, hide: hide, isVisible: isVisible, hold: hold, setOpacity: setOpacity, getOpacity: getOpacity, setLock: setLock, getLock: getLock, handleSelect: handleSelect, // input model (ADDENDUM 2): main pushes the winning ray every XR frame; // setReticle stays for the older gaze-only path. setPointer: setPointer, setReticle: setReticle, // accessor 90-main.js probes for its controller-ray -> panel math getLayer: function () { return S.layer; }, get layer() { return S.layer; }, // geometry constants, so main can pass the matching w/h to hitTest() PANEL_M: PANEL_M, PANEL_PX: PANEL_PX }; var n2 = ns(); n2.Controls = Controls; })();