Files
jellyfin_vr_web_plugin/src/90-main.js
T
cat-shark e18c3d51bd hud-10 (rev3): cursor on the guide line; a press is attributed to the acting hand
ADDENDUM 11b, both reported against ADDENDUM 11.

1. The cursor drifted off the guide line, worse near the panel edge. panelHit()
   clamps an off-panel intersection to the border and flags it via inBounds, but
   updatePointer() published that clamped nx,ny as pointer.hit, so the ring was
   drawn on the border while the beam ended at the true (off-panel) intersection.
   pointer.hit is now published only when inBounds; distance is still published so
   an edge-aimed beam reaches the plane (beamLength no longer requires p.hit).
   Near-misses still summon the bar, but no longer press.

2. A right-hand press could still act at the left hand's position, for three
   separate reasons: the activate cooldown was global (a gamepad edge from one hand
   swallowed the other hand's select - now per input source); a missing ray fell
   back to another hand (with a preferKey the acting source now owns the shot and
   a missing candidate MISSes); and a null frame skipped re-attribution entirely
   (now falls back to S.lastFrame and MISSes if the acting source yields no
   pointer).

New diagnostics: stats.pressSrc, stats.pressPtr.

Verified with injected synthetic input sources:
  both on panel, right press      pressSrc hand:right  pressAt 0.78,0.50  seek 79.5%
  left press then right 100ms     pressSrc hand:right  pressAt 0.78,0.50  (not swallowed)
  both off panel                  state.pointer.hit = null (no clamped cursor)
  off panel, right press          pressPtr "hand:right nohit"  MISS (no hit on the panel)
2026-10-12 21:07:05 +08:00

1919 lines
82 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*!
* JFVR main — boot, DOM scan, in-page settings panel, XR session lifecycle,
* input dispatch, wiring.
*
* Loaded last. Owns everything the modules do not.
* See INTERFACES.md.
*/
(function () {
'use strict';
var NS = window.__JFVR;
if (!NS) { console.error('[JFVR] core missing'); return; }
if (NS.__main) return;
NS.__main = true;
var S = NS.state;
var log = NS.log;
/* ================================================================== *
* rAF broker
* ------------------------------------------------------------------
* While an immersive XR session runs, window.requestAnimationFrame is
* COMPLETELY stopped (measured: 0 callbacks in 6s). Jellyfin renders libass
* subtitles from an rAF loop, so that froze the subtitle canvas.
*
* The FIRST fix was to queue callbacks in XR and pump the queue from
* video.requestVideoFrameCallback. That is not enough on Jellyfin 12.x: a
* callback that is ALREADY PENDING in the NATIVE scheduler when the session
* starts is destroyed with the native scheduler and never runs again, and
* SubtitlesOctopus starts ONE long-lived rAF loop when the video loads whose
* id is never reset. Verified on device: instance.rafId stuck on a native id
* (1150), oneshotState.eventStart frozen ~7 min behind the playhead, zero
* oneshot-render requests for the whole session -> the whole prerender chain
* stalls and the HUD shows the last line drawn before VR started.
*
* So the queue is used ALWAYS, even outside XR, and drained by a native rAF
* pump. Nothing is ever left pending natively, so nothing can be lost when the
* session starts; startRafPump just swaps the driver. In XR the native pump
* stops and video.requestVideoFrameCallback drives the queue (it still fires,
* in step with the video); a slow timer also drives it when the video is not
* presenting frames (paused / stalled / ended), so a paused seek or a track
* switch still redraws instead of leaving a stale line on screen.
* ================================================================== */
var RAFQ = {
inXR: false,
native: (window.requestAnimationFrame || function () {}).bind(window),
nativeCancel: (window.cancelAnimationFrame || function () {}).bind(window),
queue: new Map(),
nextId: 1000000000,
pumped: 0,
nativeId: null,
lastPump: 0,
err: null
};
function drainRaf(t) {
if (!RAFQ.queue.size) return;
var cbs = [];
RAFQ.queue.forEach(function (cb) { cbs.push(cb); });
RAFQ.queue.clear();
RAFQ.pumped++;
for (var i = 0; i < cbs.length; i++) {
try { cbs[i](t); } catch (e) { if (!RAFQ.err) RAFQ.err = NS.recordError('raf cb', e); }
}
}
// Native driver (outside XR). Exactly ONE native callback is kept in flight so
// that a rAF which re-schedules itself cannot multiply the driver (an earlier
// version nulled nativeId before draining, re-armed on every self-rescheduling
// callback AND again at the end -> exponential native callbacks -> frozen page).
function nativeRafStep(t) {
if (RAFQ.inXR) { RAFQ.nativeId = null; return; } // the XR driver owns the queue
RAFQ.nativeId = RAFQ.native(nativeRafStep); // re-arm BEFORE draining
drainRaf(t);
if (!RAFQ.queue.size && !RAFQ.inXR) { // nothing left -> stop
try { RAFQ.nativeCancel(RAFQ.nativeId); } catch (e) {}
RAFQ.nativeId = null;
}
}
function ensureNativeRaf() {
if (RAFQ.inXR || RAFQ.nativeId != null) return;
RAFQ.nativeId = RAFQ.native(nativeRafStep);
}
try {
window.requestAnimationFrame = function (cb) {
if (typeof cb !== 'function') return 0;
var id = RAFQ.nextId++;
RAFQ.queue.set(id, cb);
if (!RAFQ.inXR) ensureNativeRaf();
return id;
};
window.cancelAnimationFrame = function (id) {
if (RAFQ.queue.has(id)) { RAFQ.queue.delete(id); return; }
return RAFQ.nativeCancel(id);
};
} catch (e) { log('rAF broker install failed', e); }
function startRafPump(video) {
// NOTE: do NOT clear the queue. The callback that a naive broker loses at
// session start is sitting in it, and it is the one that keeps Jellyfin's
// subtitle loop alive. The pending NATIVE driver id is dropped: that callback
// is lost with the native scheduler anyway, and clearing the id lets the
// driver restart cleanly after the session ends.
RAFQ.nativeId = null;
RAFQ.inXR = true;
RAFQ.pumped = 0;
RAFQ.lastPump = 0;
RAFQ.err = null;
var stopped = false;
S.stats.rafPump = video && video.requestVideoFrameCallback ? 'videoFrameCallback' : 'interval';
if (video && video.requestVideoFrameCallback) {
var step = function (now) {
if (stopped) return;
RAFQ.lastPump = performance.now();
drainRaf(now);
video.requestVideoFrameCallback(step);
};
video.requestVideoFrameCallback(step);
}
// Idle fallback: rVFC stops while the video is paused / stalled / ended.
var id = setInterval(function () {
if (stopped || !RAFQ.inXR) return;
if (performance.now() - RAFQ.lastPump > 60) drainRaf(performance.now());
}, 50);
RAFQ.stop = function () { stopped = true; clearInterval(id); };
}
function stopRafPump() {
try { if (RAFQ.stop) RAFQ.stop(); } catch (e) {}
RAFQ.stop = null;
RAFQ.inXR = false;
RAFQ.lastPump = 0;
// hand the queue back to the native driver so nothing is stranded
ensureNativeRaf();
}
/* ================================================================== *
* settings persistence (localStorage, per browser)
* ================================================================== */
var STORE_KEY = 'jfvr.settings.v1';
var saveTimer = null;
function num(v, lo, hi, dflt) {
if (typeof v !== 'number' || !isFinite(v)) return dflt;
return NS.clamp(v, lo, hi);
}
function loadSettings() {
var raw;
try { raw = localStorage.getItem(STORE_KEY); } catch (e) { return; }
if (!raw) return;
var o;
try { o = JSON.parse(raw); } catch (e) { return; } // corrupt -> defaults
if (!o || typeof o !== 'object') return;
try {
if (o.subPlacement && typeof o.subPlacement === 'object') {
S.subPlacement = {
y: num(o.subPlacement.y, -0.95, -0.05, S.subPlacement.y),
z: num(o.subPlacement.z, -2.6, -0.35, S.subPlacement.z),
width: num(o.subPlacement.width, 0.2, 4.5, S.subPlacement.width)
};
}
// ADDENDUM 6: depth/size decoupling. When locked, the stored width is
// re-derived from subAngleDeg + z by 10-subtitles.js, so this pair is what
// actually restores the user's look.
if (typeof o.subLockAngle === 'boolean') S.subLockAngle = o.subLockAngle;
if (typeof o.subAngleDeg === 'number') S.subAngleDeg = num(o.subAngleDeg, 20, 120, S.subAngleDeg);
S.subOpacity = num(o.subOpacity, 0.1, 1.0, S.subOpacity);
S.ctlAutoHideMs = num(o.ctlAutoHideMs, 1000, 10000, S.ctlAutoHideMs);
if (o.subMode === 'hud' || o.subMode === 'sphere') S.subMode = o.subMode;
// subLayout is deliberately NOT restored: a persisted manual override
// silently ruined the default dual-eye content once already (forced 'mono'
// made the HUD show both eyes side by side). Layout always starts on 'auto'.
// ADDENDUM 8: how the picture aim is applied. 'space' is the live path; the
// 'rebuild' escape hatch exists because mutating a media layer's transform is
// ignored by this runtime, so if an offset reference space turns out not to be
// honoured either, this is how we get movement back without a redeploy.
if (o.videoRotMode === 'auto' || o.videoRotMode === 'space' || o.videoRotMode === 'rebuild') {
S.videoRotMode = o.videoRotMode;
}
// 'off' is deliberately NOT restored. Persisting it had the same effect as
// persisting subtitles:false - the subtitle layer was never created on the
// next session, which looked like a loading failure. Same for subAlpha,
// which is harmless but pointless to restore when subtitles start ON.
if (o.subAlpha === 'premultiplied' || o.subAlpha === 'straight') S.subAlpha = o.subAlpha;
if (o.projection === '180' || o.projection === '360') S.projection = o.projection;
if (o.stereo === 'mono' || o.stereo === 'sbs' || o.stereo === 'ou') S.stereo = o.stereo;
if (typeof o.controls === 'boolean') S.controls = o.controls;
// NOTE: `subtitles` is deliberately NOT restored. Persisting it meant a
// session where the user toggled subtitles off came back with them off,
// the subtitle layer never being created - which looked like a loading
// failure. Subtitles always start ON; the toggle is per-session only.
log('settings restored', JSON.stringify(S.subPlacement), 'opacity', S.subOpacity);
} catch (e) { /* keep defaults */ }
}
function saveSettings() {
if (saveTimer != null) clearTimeout(saveTimer);
saveTimer = setTimeout(function () {
saveTimer = null;
try {
localStorage.setItem(STORE_KEY, JSON.stringify({
subPlacement: S.subPlacement,
subLockAngle: S.subLockAngle,
subAngleDeg: S.subAngleDeg,
subOpacity: S.subOpacity,
subMode: S.subMode,
subAlpha: S.subAlpha,
projection: S.projection,
stereo: S.stereo,
videoRotMode: S.videoRotMode,
controls: S.controls,
ctlAutoHideMs: S.ctlAutoHideMs
}));
S.stats.saved = 'ok';
} catch (e) { S.stats.saved = 'err:' + ((e && e.message) || e); }
}, 400);
}
/* ================================================================== *
* video discovery
* ================================================================== */
function findVideo() {
var list = Array.prototype.slice.call(document.querySelectorAll('video'));
var playing = null, any = null;
for (var i = 0; i < list.length; i++) {
var v = list[i];
if (!v.videoWidth) continue;
if (!any) any = v;
if (!v.paused && v.readyState >= 2 && !playing) playing = v;
}
return playing || any || null;
}
/* ================================================================== *
* format detection
* ================================================================== */
function detectFromName(name) {
if (!name) return null;
var n = name.toLowerCase();
var is360 = /(^|[^0-9])360([^0-9]|$)/.test(n) || /\bvr360\b/.test(n);
var is180 = /(^|[^0-9])180([^0-9]|$)/.test(n) || /\bvr180\b/.test(n);
var sbs = /(^|[^a-z])(sbs|lr|3dh)([^a-z]|$)/.test(n);
var ou = /(^|[^a-z])(ou|tb|3dv)([^a-z]|$)/.test(n);
if (!is180 && !is360 && !sbs && !ou) return null;
return { projection: is360 ? '360' : '180', stereo: ou ? 'ou' : (sbs || is180 || is360) ? 'sbs' : 'mono' };
}
function detectFromShape(w, h) {
if (!w || !h) return null;
var r = w / h;
if (r >= 3.6) return { projection: '360', stereo: 'sbs' };
if (r >= 1.8 && r <= 2.2) return { projection: '180', stereo: 'sbs' };
if (r >= 1.15 && r <= 1.45) return { projection: '180', stereo: 'mono' };
if (r <= 0.6) return { projection: '180', stereo: 'ou' };
return { projection: '180', stereo: 'sbs' };
}
function currentItemId() {
var m = /[?&]id=([a-f0-9]{32})/i.exec(location.hash || '');
return m ? m[1] : null;
}
function tryFetchFileName() {
var id = currentItemId();
if (!id || typeof ApiClient === 'undefined' || !ApiClient.getItem) return Promise.resolve('');
var uid;
try { uid = ApiClient.getCurrentUserId(); } catch (e) { uid = null; }
if (!uid) return Promise.resolve('');
return ApiClient.getItem(uid, id)
.then(function (item) { return (item && (item.Path || item.Name)) || ''; })
.catch(function () { return ''; });
}
function applyAutoDetect() {
return tryFetchFileName().then(function (name) {
if (name) {
S.fileName = name.split(/[\\/]/).pop();
var d = detectFromName(S.fileName);
if (d) { S.projection = d.projection; S.stereo = d.stereo; S.detected = 'filename: ' + S.fileName; return; }
}
var v = S.video;
var d2 = v && v.videoWidth ? detectFromShape(v.videoWidth, v.videoHeight) : null;
if (d2) {
S.projection = d2.projection; S.stereo = d2.stereo;
S.detected = 'resolution: ' + v.videoWidth + 'x' + v.videoHeight;
}
}).catch(function () {});
}
/* ================================================================== *
* in-page UI
* ================================================================== */
var CSS = [
// Sits ABOVE Jellyfin's own OSD bar: at the viewport's bottom-right it
// covered the player's fullscreen button (owner report). 120 px clears the
// OSD bottom bar; the settings panel stacks above it.
'.jfvr-btn{position:fixed;right:16px;bottom:120px;z-index:2147483000;display:flex;align-items:center;gap:8px;',
'padding:10px 16px;border:0;border-radius:24px;background:linear-gradient(135deg,#4ea1ff,#7b5cff);color:#fff;',
'font-size:15px;font-weight:600;cursor:pointer;box-shadow:0 6px 22px rgba(0,0,0,.45);font-family:inherit}',
'.jfvr-btn:active{transform:scale(.96)}',
// the panel must always fit the viewport AND keep the CTA reachable, so the
// body scrolls and the button lives in a sticky footer
'.jfvr-panel{position:fixed;right:16px;bottom:180px;z-index:2147483001;width:290px;background:rgba(20,20,24,.96);',
'color:#eaeaea;border:1px solid rgba(255,255,255,.14);border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.6);',
'font-family:inherit;font-size:14px;backdrop-filter:blur(10px);display:flex;flex-direction:column;',
'max-height:calc(100vh - 200px);overflow:hidden}',
'.jfvr-head{display:flex;justify-content:space-between;align-items:center;padding:10px 12px;background:rgba(255,255,255,.06);font-weight:600;flex:0 0 auto}',
'.jfvr-x{background:none;border:0;color:#aaa;font-size:20px;line-height:1;cursor:pointer;padding:0 4px}',
'.jfvr-body{padding:12px;overflow-y:auto;flex:1 1 auto;min-height:0}',
'.jfvr-foot{flex:0 0 auto;padding:10px 12px 12px;background:rgba(16,16,20,.98);border-top:1px solid rgba(255,255,255,.1)}',
'.jfvr-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px;gap:8px}',
'.jfvr-lbl{color:#9aa0aa;font-size:13px;white-space:nowrap}',
'.jfvr-seg{display:flex;border:1px solid rgba(255,255,255,.16);border-radius:8px;overflow:hidden;flex-shrink:0}',
'.jfvr-seg button{background:none;border:0;color:#bbb;padding:6px 9px;font-size:12px;cursor:pointer;font-family:inherit}',
'.jfvr-seg button+button{border-left:1px solid rgba(255,255,255,.16)}',
'.jfvr-seg button.on{background:#4ea1ff;color:#fff;font-weight:600}',
'.jfvr-seg button:disabled{color:#555;cursor:default}',
'.jfvr-hint{font-size:12px;color:#8b93a1;margin:2px 0 10px;line-height:1.5;word-break:break-all}',
'.jfvr-go{width:100%;padding:10px;border:0;border-radius:9px;background:#4ea1ff;color:#fff;font-size:15px;',
'font-weight:600;cursor:pointer;font-family:inherit}',
'.jfvr-go:disabled{background:#3a3f47;color:#888;cursor:default}',
'.jfvr-diag{margin-top:10px;font-size:11px;color:#8b93a1}',
'.jfvr-diag summary{cursor:pointer;user-select:none}',
'.jfvr-diag pre{white-space:pre-wrap;word-break:break-all;margin:8px 0 0;font-size:10px;line-height:1.45;',
'max-height:230px;overflow:auto;color:#9fb0c4;background:rgba(0,0,0,.35);padding:8px;border-radius:7px}',
'.jfvr-msg{margin-top:8px;font-size:12px;color:#ffb3b3;line-height:1.55;white-space:pre-line;word-break:break-all}',
'.jfvr-sec{margin:12px 0 6px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#6d7684;',
'border-top:1px solid rgba(255,255,255,.09);padding-top:9px}',
'.jfvr-sl{margin-bottom:7px}',
'.jfvr-sl .jfvr-lbl{display:flex;justify-content:space-between;font-size:12px;margin-bottom:2px}',
'.jfvr-sl input[type=range]{width:100%;accent-color:#4ea1ff;height:18px;cursor:pointer}'
].join('');
function injectCss() {
if (document.getElementById('jfvr-css')) return;
var s = NS.makeEl('style');
s.id = 'jfvr-css';
s.textContent = CSS;
document.head.appendChild(s);
}
var btn = null, panel = null, diagTimer = null;
// Every sliderRow registers a re-read here, so a value changed from anywhere
// (VR control bar, grab & drag, the lock toggle) is reflected in the open panel.
var panelSync = null;
var panelSyncs = [];
function ensureButton() {
if (btn && document.body.contains(btn)) return;
injectCss();
var b = NS.makeEl('button', 'jfvr-btn');
b.type = 'button';
b.innerHTML = '<span>&#127909;</span><span>VR 播放</span>';
b.addEventListener('click', function (ev) { ev.stopPropagation(); togglePanel(); });
document.body.appendChild(b);
btn = b;
}
function removeButton() {
if (btn) { btn.remove(); btn = null; }
hidePanel();
}
function segRow(label, getValue, setValue, options, disabledFn) {
var row = NS.makeEl('div', 'jfvr-row');
row.appendChild(NS.makeEl('span', 'jfvr-lbl', label));
var seg = NS.makeEl('div', 'jfvr-seg');
options.forEach(function (o) {
var b = NS.makeEl('button', null, o.label);
b.type = 'button';
if (getValue() === o.value) b.classList.add('on');
if (disabledFn && disabledFn(o.value)) { b.disabled = true; }
b.addEventListener('click', function (ev) {
ev.stopPropagation();
setValue(o.value);
Array.prototype.forEach.call(seg.children, function (c) { c.classList.remove('on'); });
b.classList.add('on');
refreshHint();
});
seg.appendChild(b);
});
row.appendChild(seg);
return row;
}
function sliderRow(label, min, max, step, fmt, getValue, setValue) {
var wrap = NS.makeEl('div', 'jfvr-sl');
var lab = NS.makeEl('div', 'jfvr-lbl');
var name = NS.makeEl('span', null, label);
var val = NS.makeEl('span', null, fmt(getValue()));
lab.appendChild(name); lab.appendChild(val);
wrap.appendChild(lab);
var inp = NS.makeEl('input');
inp.type = 'range';
inp.min = min; inp.max = max; inp.step = step;
inp.value = getValue();
inp.addEventListener('input', function (ev) {
ev.stopPropagation();
var v = parseFloat(inp.value);
setValue(v);
val.textContent = fmt(v);
});
wrap.appendChild(inp);
panelSyncs.push(function () {
var v = getValue();
if (document.activeElement !== inp) inp.value = v;
val.textContent = fmt(v);
});
return wrap;
}
function togglePanel() {
if (panel) { hidePanel(); return; }
injectCss();
panelSyncs = [];
// Subtitles must be prepared BEFORE entering VR: libass does not recompute
// its backing store while an immersive session is running.
if (S.subtitles && NS.Subtitles) {
try { NS.Subtitles.prepare(); } catch (e) { NS.recordError('prepare', e); }
}
panel = NS.makeEl('div', 'jfvr-panel');
panel.addEventListener('click', function (ev) { ev.stopPropagation(); });
var head = NS.makeEl('div', 'jfvr-head');
head.appendChild(NS.makeEl('span', null, 'VR 播放'));
var x = NS.makeEl('button', 'jfvr-x', '\u00d7');
x.type = 'button';
x.addEventListener('click', function (ev) { ev.stopPropagation(); hidePanel(); });
head.appendChild(x);
panel.appendChild(head);
var body = NS.makeEl('div', 'jfvr-body');
if (!window.isSecureContext) {
body.appendChild(NS.makeEl('div', 'jfvr-msg',
'\u26a0 当前不是安全上下文(' + location.origin + '),点了也进不去 VR。\n' +
'先在 Quest 浏览器 chrome://flags 里启用 unsafely-treat-insecure-origin-as-secure,' +
'填入 http://192.168.123.199:8096,Relaunch 后重开本页。'));
}
body.appendChild(NS.makeEl('div', 'jfvr-sec', '画面'));
body.appendChild(segRow('投影', function () { return S.projection; },
function (v) { S.projection = v; S.detected = 'manual'; saveSettings(); },
[{ label: '180\u00b0', value: '180' }, { label: '360\u00b0', value: '360' }]));
body.appendChild(segRow('立体', function () { return S.stereo; },
function (v) { S.stereo = v; S.detected = 'manual'; saveSettings(); },
[{ label: '单目', value: 'mono' }, { label: '左右', value: 'sbs' }, { label: '上下', value: 'ou' }]));
// ADDENDUM 7: the ONLY subtitle setting left before entering VR. Everything
// else (mode / alpha / opacity / position / depth / size / lock) is set IN
// VR, where the user can actually judge it - slider values chosen on a flat
// screen do not transfer to the headset. 视角宽度 keeps its default; the
// in-VR "小/大" buttons and the subtitle-row caption are the controls.
body.appendChild(NS.makeEl('div', 'jfvr-sec', '字幕'));
body.appendChild(segRow('显示', function () { return S.subtitles ? 'on' : 'off'; },
function (v) { S.subtitles = v === 'on'; saveSettings(); },
[{ label: '开', value: 'on' }, { label: '关', value: 'off' }]));
// ADDENDUM 9: dual-eye ASS vs a normal (mono) subtitle. 'auto' detects from
// the libass canvas; force it only if the detection gets it wrong.
body.appendChild(segRow('字幕布局', function () { return S.subLayout || 'auto'; },
function (v) {
S.subLayout = v;
if (NS.Subtitles && NS.Subtitles.setLayout) { try { NS.Subtitles.setLayout(v); } catch (e) {} }
saveSettings();
},
[{ label: '自动', value: 'auto' }, { label: '双目', value: 'dual' }, { label: '普通', value: 'mono' }]));
body.appendChild(NS.makeEl('div', 'jfvr-hint',
'字幕的位置 / 距离 / 大小 / 不透明度都在 VR 里用控制条调(控制条最下面一行),' +
'调好会自动记住。VR 空间右侧有个锁图标:锁上后面板不会再被唤出。'));
// ADDENDUM 8: the picture-pan mechanism. Only touch this if panning does not
// move the picture live (see stats.videoRotMode).
body.appendChild(segRow('画面旋转', function () { return S.videoRotMode || 'auto'; },
function (v) {
S.videoRotMode = v;
if (S.session) {
try { videoSpaceCache = null; S.videoTransformLive = undefined; applyVideoAngle(true); } catch (e) {}
}
saveSettings();
},
[{ label: '自动', value: 'auto' }, { label: '兼容', value: 'rebuild' }]));
body.appendChild(NS.makeEl('div', 'jfvr-sec', '控制'));
body.appendChild(segRow('VR 内控制条', function () { return S.controls ? 'on' : 'off'; },
function (v) { S.controls = v === 'on'; saveSettings(); },
[{ label: '开', value: 'on' }, { label: '关', value: 'off' }]));
body.appendChild(sliderRow('自动收起', 1000, 10000, 500,
function (v) { return (v / 1000).toFixed(1) + ' s'; },
function () { return S.ctlAutoHideMs; },
function (v) { S.ctlAutoHideMs = v; saveSettings(); }));
var hint = NS.makeEl('div', 'jfvr-hint');
hint.id = 'jfvr-hint';
body.appendChild(hint);
var det = document.createElement('details');
det.className = 'jfvr-diag';
var sum = document.createElement('summary');
sum.textContent = '诊断信息(可复制发我)';
det.appendChild(sum);
var pre = document.createElement('pre');
pre.id = 'jfvr-diag';
det.appendChild(pre);
body.appendChild(det);
panel.appendChild(body);
// The status line and the CTA live in a sticky footer so neither can scroll
// off-screen - the CTA did before, once the settings grew past a short viewport.
var foot = NS.makeEl('div', 'jfvr-foot');
var msg = NS.makeEl('div', 'jfvr-msg');
msg.id = 'jfvr-msg';
foot.appendChild(msg);
var go = NS.makeEl('button', 'jfvr-go', '进入 VR');
go.type = 'button';
go.id = 'jfvr-go';
go.addEventListener('click', function (ev) {
ev.stopPropagation();
if (S.subtitles && NS.Subtitles) { try { NS.Subtitles.prepare(); } catch (e) {} }
go.disabled = true;
go.textContent = '进入中\u2026';
enterVR().catch(function (e) { log('enterVR threw', e); }).then(function () {
go.disabled = false;
go.textContent = '进入 VR';
});
});
foot.appendChild(go);
panel.appendChild(foot);
document.body.appendChild(panel);
panelSync = function () {
for (var i = 0; i < panelSyncs.length; i++) {
try { panelSyncs[i](); } catch (e) {}
}
};
refreshHint();
updateDiag();
if (!diagTimer) {
diagTimer = setInterval(function () {
if (panel) updateDiag(); else { clearInterval(diagTimer); diagTimer = null; }
}, 1000);
}
}
function hidePanel() {
if (panel) { panel.remove(); panel = null; }
panelSync = null;
panelSyncs = [];
// Only shrink the subtitle canvas back when we are not in / about to be in VR.
if (!S.session && NS.Subtitles) { try { NS.Subtitles.restore(); } catch (e) {} }
}
function refreshHint() {
var h = document.getElementById('jfvr-hint');
if (!h) return;
var v = S.video;
var shape = v && v.videoWidth ? (v.videoWidth + '\u00d7' + v.videoHeight) : '未知';
var txt = '画面 ' + shape + ' · ' + (S.detected || '自动');
var proj = S.projection === '360' ? 'VR360' : 'VR180';
var st = S.stereo === 'sbs' ? '左右' : S.stereo === 'ou' ? '上下' : '单目';
txt += ' → ' + proj + ' ' + st;
var cs = NS.Subtitles && NS.Subtitles.canvasSize ? NS.Subtitles.canvasSize() : null;
if (cs) txt += ' · 字幕画布 ' + cs.w + '\u00d7' + cs.h;
h.textContent = txt;
}
function updateDiag() {
var pre = document.getElementById('jfvr-diag');
if (!pre) return;
var v = S.video;
var video = v ? [
'size : ' + v.videoWidth + ' x ' + v.videoHeight,
'readyState : ' + v.readyState + ' paused: ' + v.paused,
't / dur : ' + v.currentTime.toFixed(1) + ' / ' + (isFinite(v.duration) ? v.duration.toFixed(1) : 'n/a'),
'src : ' + (v.currentSrc || '').slice(0, 100)
].join('\n') : 'no <video>';
var keys = Object.keys(S.stats).sort();
var runtime = keys.map(function (k) {
var val = S.stats[k];
return ' ' + k + ' = ' + (typeof val === 'object' ? JSON.stringify(val) : val);
}).join('\n');
pre.textContent =
'--- 能力 ---\n' + NS.capsDiag() +
'\n\n--- 视频 ---\n' + video +
'\n\n--- 运行 ---\n' +
' rafPumped = ' + RAFQ.pumped + ' pending=' + RAFQ.queue.size + (RAFQ.err ? ' err=' + RAFQ.err : '') + '\n' +
runtime +
(S.errors.length ? '\n\n--- 错误 ---\n' + S.errors.slice(-6).map(function (e) { return ' ' + e; }).join('\n') : '');
}
function setMsg(t) {
var m = document.getElementById('jfvr-msg');
if (m) m.textContent = t || '';
}
/* ================================================================== *
* XR session lifecycle
* ================================================================== */
function pushRenderState() {
var session = S.session;
if (!session || S.ending) return;
var layers = NS.getLayers();
if (!layers.length) return;
try {
session.updateRenderState({ layers: layers });
} catch (e) {
// A teardown race: modules drop their layers while the session is already
// ending. Harmless, and not worth surfacing as an error.
S.stats.renderStateErr = String((e && e.message) || e);
}
}
NS.setRenderStatePusher(pushRenderState);
function enterVR() {
var video = S.video;
if (!video) { setMsg('未找到视频元素。'); return Promise.resolve(); }
if (!window.isSecureContext) {
setMsg('当前页不是安全上下文,WebXR 不可用。\n\nQuest 浏览器:chrome://flags → 搜 insecure → ' +
'启用 unsafely-treat-insecure-origin-as-secure → 填 ' + location.origin +
' → Relaunch。');
return Promise.resolve();
}
if (!navigator.xr) { setMsg('此浏览器没有暴露 WebXR。'); return Promise.resolve(); }
setMsg('');
// requestSession() must be called synchronously inside the click's
// transient-activation task. Never await before it.
var sessionPromise;
try {
log('requesting immersive-vr \u2026');
sessionPromise = navigator.xr.requestSession('immersive-vr', {
optionalFeatures: ['local-floor', 'bounded-floor', 'layers', 'hand-tracking']
});
} catch (e) {
setMsg('进入 VR 失败:' + ((e && e.message) || e));
return Promise.resolve();
}
try { video.play().catch(function () {}); } catch (e) {}
var pre = Promise.resolve();
try { if (document.pictureInPictureElement) pre = document.exitPictureInPicture().catch(function () {}); } catch (e) {}
try { if (document.fullscreenElement) pre = pre.then(function () { return document.exitFullscreen().catch(function () {}); }); } catch (e) {}
return pre.then(function () { return sessionPromise; }).then(function (session) {
S.session = session;
log('session started', session);
// --- frame-rate fix -------------------------------------------------
// 59.94 fps video on a 90 Hz session shows each frame 1 or 2 refreshes
// alternately (90/59.94 = 1.5) => 3:2 pulldown judder. 120 Hz is an exact
// multiple (2.002), so every frame gets the same number of refreshes.
try {
var rates = session.supportedFrameRates ? Array.prototype.slice.call(session.supportedFrameRates) : [];
var want = rates.indexOf(120) >= 0 ? 120 : (rates.length ? rates[rates.length - 1] : 0);
S.stats.supportedFrameRates = rates;
if (want && typeof session.updateTargetFrameRate === 'function') {
session.updateTargetFrameRate(want);
S.stats.targetFrameRate = want;
log('updateTargetFrameRate ->', want, 'Hz (supported: ' + rates.join('/') + ')');
}
} catch (e) { log('updateTargetFrameRate failed', e); }
session.addEventListener('end', onSessionEnd, { once: true });
session.addEventListener('select', onSelect);
try { session.addEventListener('selectend', onSelectEnd); } catch (e) {}
// --- reference spaces ------------------------------------------------
var p = session.requestReferenceSpace('local').then(function (rs) { S.refSpace = rs; NS.refSpace = rs; })
.catch(function (e) { NS.recordError('local refSpace', e); });
p = p.then(function () {
return session.requestReferenceSpace('viewer')
.then(function (vs) { S.viewerSpace = vs; NS.viewerSpace = vs; })
.catch(function (e) { NS.recordError('viewer refSpace', e); });
});
// --- rAF broker, layers, frame loop ---------------------------------
return p.then(function () {
startRafPump(video);
var made = [];
// ORDER MATTERS: layers composite in array order, later = on top.
// video (bottom) -> hands -> subtitles -> controls (top)
try {
var vlayer = createVideoLayer(session);
if (vlayer) {
NS.addLayer(vlayer);
S.videoLayer = vlayer;
made.push('video');
// ADDENDUM 8: angles start dead ahead every session (never restored),
// then the transform is applied so probe + apply see the real layer.
S.videoYaw = 0;
S.videoPitch = 0;
videoSpaceCache = null;
S.videoTransformLive = probeVideoTransformWritable(vlayer);
S.stats.videoTransformWritable = !!S.videoTransformLive;
applyVideoAngle(true); // restores the probe marker, sets the aim
log('video aim: ' + videoRotStrategy() + ' (transform writable: ' + !!S.videoTransformLive + ')');
updateVideoAngleStats();
}
} catch (e) { NS.recordError('video layer', e); made.push('video:err'); }
// System hand models (WebXR Input Profiles 'generic-hand'), rendered into
// their own projection layer. Placed above the video but below the panel
// so the panel stays readable when a hand is behind it.
try {
if (NS.Hands && NS.Hands.create) {
var hl = NS.Hands.create(session);
if (hl) { NS.addLayer(hl); made.push('hands'); }
else made.push('hands:null');
}
} catch (e) { NS.recordError('hands.create', e); made.push('hands:err'); }
try {
if (S.subtitles && NS.Subtitles && S.subMode !== 'off') {
NS.Subtitles.setMode(S.subMode);
var sl = NS.Subtitles.create(session);
if (sl) made.push('subtitles'); else made.push('subtitles:null');
}
} catch (e) { NS.recordError('subtitles.create', e); made.push('subtitles:err'); }
try {
if (S.controls && NS.Controls) {
NS.Controls.setVideo(video, controlsExtra());
NS.Controls.onAction(handleControlAction);
// ADDENDUM 7: the panel lock is per VR session - a new session always
// starts unlocked so it can never be left in a state where the bar
// refuses to appear and the user does not know why.
S.ctlLock = false;
barShownAt = -1e9;
if (NS.Controls.setLock) { try { NS.Controls.setLock(false); } catch (e) {} }
var cl = NS.Controls.create(session);
if (cl) made.push('controls'); else made.push('controls:null');
}
} catch (e) { NS.recordError('controls.create', e); made.push('controls:err'); }
S.stats.layersBuilt = made.join(',');
var frames = 0, lastT = 0, lastFrameT = 0;
var loop = function (time, frame) {
if (S.session !== session) return;
frames++;
if (!lastT) lastT = time;
var dt = lastFrameT ? Math.min(0.1, (time - lastFrameT) / 1000) : 0.016;
lastFrameT = time;
if (time - lastT >= 1000) {
S.stats.fps = +(frames * 1000 / (time - lastT)).toFixed(1);
frames = 0; lastT = time;
}
if (frame) {
// One bad frame must never stop the loop: if this throws, rAF is never
// requested again and the whole session freezes.
try {
updatePointer(frame);
pollGamepads(frame);
updatePanelPose(frame, dt);
updateGrabFrame(frame);
updateViewDrag(frame);
NS.runFrameHooks(frame, time, session);
} catch (e) {
NS.recordError('frame', e);
S.stats.frameErr = (e && e.message) || String(e);
}
}
session.requestAnimationFrame(loop);
};
session.requestAnimationFrame(loop);
log('layers:', S.stats.layersBuilt, '| freespace ok');
});
}).then(function () {
try { video.play().catch(function () {}); } catch (e) {}
setMsg('已进入 VR。');
refreshHint();
}).catch(function (e) {
NS.recordError('enterVR', e);
setMsg('进入 VR 失败:' + ((e && e.message) || e));
});
}
// video equirect layer (equirect via XRMediaBinding, or WebGL fallback)
function createVideoLayer(session) {
var video = S.video;
if (!video) return null;
var useMedia = NS.caps.hasEquirectLayer;
if (!useMedia) { log('XRMediaBinding.createEquirectLayer unavailable'); return null; }
var opts = {
space: S.refSpace,
layout: NS.stereoLayout(),
centralHorizontalAngle: NS.centralAngle(),
upperVerticalAngle: Math.PI / 2,
lowerVerticalAngle: -Math.PI / 2
};
// ADDENDUM 8: the picture's aim. radius stays 0 (content at infinity), so this
// is a pure rotation about the eye point.
// 'space' -> the rotation lives in an offset reference space, which a layer
// pose is recomputed from every frame (live updates).
// 'rebuild' -> the rotation is supplied as the creation transform, which is
// the only form this runtime honours.
// The transform must NOT be baked in for the transform strategy: the probe
// writes to it right after creation, and baking it in as well would apply the
// aim twice. Only the rebuild strategy bakes it in, because a fresh layer is the
// only surviving form of the write it can rely on.
if (videoRotStrategy() === 'rebuild') {
var t = videoAngleTransform();
if (t) opts.transform = t;
}
var layer = new XRMediaBinding(session).createEquirectLayer(video, opts);
log('video layer', JSON.stringify({ layout: opts.layout, central: opts.centralHorizontalAngle,
yaw: Math.round(S.videoYaw * 180 / Math.PI), pitch: Math.round(S.videoPitch * 180 / Math.PI) }));
return layer;
}
// frame reference kept for select handling; re-installed after every
// session teardown because clearFrameHooks() would otherwise remove it.
var frameTracker = function (frame) { S.lastFrame = frame; };
function installFrameTracker() { NS.addFrameHook(frameTracker); }
function onSessionEnd() {
log('session ended', S.stats);
S.ending = true; // stop pushRenderState from racing the teardown
stopRafPump();
try { if (NS.Subtitles) NS.Subtitles.destroy(); } catch (e) {}
try { if (NS.Controls) NS.Controls.destroy(); } catch (e) {}
try { if (NS.Hands) NS.Hands.destroy(); } catch (e) {}
NS.clearLayers();
NS.clearFrameHooks();
installFrameTracker();
S.lastFrame = null;
grab = null;
S.stats.grab = 'reset';
viewDrag = null;
cancelVideoRebuild();
videoSpaceCache = null;
S.videoTransformLive = undefined;
S.videoLayer = null;
S.videoYaw = 0;
S.videoPitch = 0;
if (NS.Controls && NS.Controls.hold) { try { NS.Controls.hold(false); } catch (e) {} }
S.ctlLock = false;
panelPose = null;
pointer = { visible: false, beam: false, source: 'none', origin: { x: 0, y: 0, z: 0 }, dir: { x: 0, y: 0, z: -1 }, hit: null };
activeSrcKey = null; // ADDENDUM 11: fresh hand choice every session
lastActivateByKey = {};
S.pointer = null;
S.session = null;
S.refSpace = null;
S.viewerSpace = null;
NS.session = null; NS.refSpace = null; NS.viewerSpace = null;
S.ending = false;
if (!panel && NS.Subtitles) { try { NS.Subtitles.restore(); } catch (e) {} }
setMsg('');
try { if (S.video) S.video.play().catch(function () {}); } catch (e) {}
}
/* ================================================================== *
* input
* ================================================================== */
// Unified pointer: hands and controllers both expose targetRaySpace, so one
// code path serves both. Everything is computed in VIEWER space, which is also
// where the head-locked control quad lives, so the beam quad can use the ray
// coordinates directly.
var pointer = {
visible: false,
source: 'gaze',
origin: { x: 0, y: 0, z: 0 },
dir: { x: 0, y: 0, z: -1 },
hit: { nx: 0.5, ny: 0.5 }
};
// Quads expose width/height; equirect layers do not. Find the control quad
// without depending on a specific property name on the Controls module.
function controlsLayer() {
if (!NS.Controls) return null;
if (NS.Controls.layer) return NS.Controls.layer;
if (typeof NS.Controls.getLayer === 'function') {
try { var l = NS.Controls.getLayer(); if (l) return l; } catch (e) {}
}
var all = NS.getLayers();
for (var i = all.length - 1; i >= 0; i--) {
if (typeof all[i].width === 'number' && typeof all[i].height === 'number') return all[i];
}
return null;
}
// Intersect an input source's ray with the head-locked control quad.
// Returns { origin, dir, hit:{nx,ny}, distance } all in viewer space, or null.
// Raw pointer ray for an input source, in LOCAL space. The control panel now
// lives in local space too (ADDENDUM 5), so the ray and the panel share one
// coordinate system and no per-frame conversion is needed.
function rayOf(frame, src) {
if (!NS.refSpace || !src || !src.targetRaySpace) return null;
var pose;
try { pose = frame.getPose(src.targetRaySpace, NS.refSpace); } catch (e) { return null; }
if (!pose) return null;
var o = pose.transform.position;
var q = pose.transform.orientation;
// forward = -Z rotated by q
var x = q.x, y = q.y, z = q.z, w = q.w;
var dx = -(2 * (x * z + w * y));
var dy = -(2 * (y * z - w * x));
var dz = -(1 - 2 * (x * x + y * y));
var len = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;
return {
origin: { x: o.x, y: o.y, z: o.z },
dir: { x: dx / len, y: dy / len, z: dz / len }
};
}
// The gaze ray: the head's forward direction in LOCAL space.
//
// Hands use this instead of their own targetRaySpace. Meta documents the hand
// ray as an EMULATED ray, and on device it measured (-0.874, 0.461, -0.154) -
// 87 % sideways while the panel was straight ahead - so aiming with it lands
// somewhere the user is not looking. Gaze + pinch is Meta's documented
// recommendation for hands and needs no ray accuracy at all.
function gazeRay(frame) {
if (!NS.refSpace || !NS.viewerSpace) return null;
var pose;
try { pose = frame.getPose(NS.viewerSpace, NS.refSpace); } catch (e) { return null; }
if (!pose) return null;
var o = pose.transform.position;
var q = pose.transform.orientation;
var x = q.x, y = q.y, z = q.z, w = q.w;
var dx = -(2 * (x * z + w * y));
var dy = -(2 * (y * z - w * x));
var dz = -(1 - 2 * (x * x + y * y));
var len = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;
return {
origin: { x: o.x, y: o.y, z: o.z },
dir: { x: dx / len, y: dy / len, z: dz / len }
};
}
/* ---------------- pose helpers (ADDENDUM 5) ---------------- *
* The panel can carry a yaw now (lazy follow) and the subtitle strip still
* lives in VIEWER space while the pointer rays are computed in LOCAL space, so
* the hit test can no longer assume an axis-aligned plane in the ray's own
* frame. Everything below transforms the ray into the LAYER's own space.
*/
function qMul(a, b) {
return {
x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z
};
}
function qRot(q, v) {
var ux = q.x, uy = q.y, uz = q.z, s = q.w;
var tx = 2 * (uy * v.z - uz * v.y);
var ty = 2 * (uz * v.x - ux * v.z);
var tz = 2 * (ux * v.y - uy * v.x);
return {
x: v.x + s * tx + (uy * tz - uz * ty),
y: v.y + s * ty + (uz * tx - ux * tz),
z: v.z + s * tz + (ux * ty - uy * tx)
};
}
// Pose of a layer expressed in NS.refSpace, composing the layer space's pose
// with the layer's own transform.
function layerPoseInLocal(frame, layer) {
var t = layer.transform || null;
var tPos = t ? t.position : { x: 0, y: 0, z: 0 };
var tQuat = t ? t.orientation : { x: 0, y: 0, z: 0, w: 1 };
if (!layer.space || layer.space === NS.refSpace) {
return { p: { x: tPos.x, y: tPos.y, z: tPos.z }, q: tQuat };
}
var lp;
try { lp = frame.getPose(layer.space, NS.refSpace); } catch (e) { return null; }
if (!lp) return null;
var off = qRot(lp.transform.orientation, tPos);
return {
p: {
x: lp.transform.position.x + off.x,
y: lp.transform.position.y + off.y,
z: lp.transform.position.z + off.z
},
q: qMul(lp.transform.orientation, tQuat)
};
}
// Widen the acceptance window so a near-miss still counts as a press: the
// finger ray is good but not surgical, and a missed press looks like a
// completely dead UI.
function panelHitWide(frame, ray, layer) {
return panelHit(frame, ray, layer, 0.25, 0.6);
}
// Intersect a LOCAL-space ray with a layer's plane and return panel-space
// normalised coordinates. `padN`/`padY` widen the acceptance window beyond the
// quad (0..1), which is needed for the thin subtitle strip.
function panelHit(frame, ray, layer, padN, padY) {
if (!ray || !layer || !NS.refSpace) return null;
var pose = layerPoseInLocal(frame, layer);
if (!pose) return null;
// ray -> panel space (translate by -p, then rotate by q^-1)
var o = qRot({ x: -pose.q.x, y: -pose.q.y, z: -pose.q.z, w: pose.q.w },
{ x: ray.origin.x - pose.p.x, y: ray.origin.y - pose.p.y, z: ray.origin.z - pose.p.z });
var d = qRot({ x: -pose.q.x, y: -pose.q.y, z: -pose.q.z, w: pose.q.w }, ray.dir);
if (Math.abs(d.z) < 1e-6) return null;
var tt = -o.z / d.z; // the layer plane is z = 0 in panel space
if (tt <= 0) return null;
var px = o.x + d.x * tt;
var py = o.y + d.y * tt;
var hw = (layer.width || 1) / 2;
var hh = (layer.height || 0.2) / 2;
var nx = (px + hw) / (hw * 2);
var ny = (hh - py) / (hh * 2);
var pn = (padN == null) ? 0.1 : padN;
var pv = (padY == null) ? 0.4 : padY;
if (nx < -pn || nx > 1 + pn || ny < -pv || ny > 1 + pv) return null;
return {
nx: NS.clamp(nx, 0, 1),
ny: NS.clamp(ny, 0, 1),
distance: tt,
inBounds: (nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1)
};
}
// ADDENDUM 7: the "index finger ray" option was removed - the system ray is
// the only mode (an index-finger ray carries fingertip jitter straight into
// the cursor, and nobody wants to point with one finger).
// Identity for an input source that survives the runtime re-listing it.
function srcKey(src) {
if (!src) return null;
return (src.hand ? 'hand' : 'ctrl') + ':' + (src.handedness || '?');
}
function candByKey(cands, key) {
for (var i = 0; i < cands.length; i++) if (cands[i].key === key) return cands[i];
return null;
}
// ADDENDUM 11 — pure: choose which input source owns the pointer.
// cands [{ key, onPanel, ... }] in runtime order
// preferKey the source that is acting right now (select / gamepad press)
// activeKey the source that acted last
// When `preferKey` is given the acting source OWNS the shot: if it is not among
// the candidates (no resolvable ray) we return null so the press MISSES rather
// than silently reusing another hand's pointer. Otherwise:
// last-active-while-on-panel -> any-on-panel -> last-active -> first.
function pickPointerCand(cands, preferKey, activeKey) {
if (preferKey) return candByKey(cands, preferKey);
if (!cands || !cands.length) return null;
var i, c;
if (activeKey) {
c = candByKey(cands, activeKey);
if (c && c.onPanel) return c;
}
for (i = 0; i < cands.length; i++) if (cands[i].onPanel) return cands[i];
if (activeKey) { c = candByKey(cands, activeKey); if (c) return c; }
return cands[0];
}
// ADDENDUM 11: which hand owns the pointer.
var activeSrcKey = null;
function updatePointer(frame, preferSrc) {
if (!S.session) return;
var next = {
visible: false, beam: false, source: 'none',
origin: { x: 0, y: 0, z: 0 }, dir: { x: 0, y: 0, z: -1 },
hit: null, distance: null
};
var srcs = S.session.inputSources ? Array.prototype.slice.call(S.session.inputSources) : [];
var layer = controlsLayer();
// Use the SYSTEM ray for everything - including hands.
//
// Meta's WebXR Hands doc: "the targetRaySpace for hands is populated with an
// emulated ray that matches the behaviors of the pointing ray of hands
// present in Meta Horizon Home". That emulated ray is STABILISED by the
// platform; an index-finger ray computed from joint poses carries the
// per-frame fingertip jitter straight into the cursor, so its landing point
// is visibly less steady. Meta's own samples use targetRaySpace too.
//
// ADDENDUM 11: with two hands BOTH report a tracked-pointer ray, and the
// runtime's order is not "the hand the user is using". Taking the first one
// pinned the guide line to one hand AND made the OTHER hand's select land
// wherever the pinned hand pointed. The pointer now follows, in order:
// 1. the source acting right now (select / gamepad press),
// 2. the last acting source, while it is aiming at the panel,
// 3. any source aiming at the panel,
// 4. the last acting source, then the first one.
var cands = [];
for (var i = 0; i < srcs.length; i++) {
var src = srcs[i];
if (src.targetRayMode !== 'tracked-pointer') continue;
var ray = rayOf(frame, src);
if (!ray) continue;
var hit = null;
try { hit = panelHit(frame, ray, layer, 0.25, 0.6); } catch (e) { hit = null; }
cands.push({
src: src, ray: ray, hit: hit, key: srcKey(src),
onPanel: !!(hit && hit.inBounds)
});
}
var pick = pickPointerCand(cands, preferSrc ? srcKey(preferSrc) : null, activeSrcKey);
if (pick) {
activeSrcKey = pick.key;
next = {
visible: true,
beam: true,
source: (pick.src.hand ? 'hand' : 'controller') + ':' + pick.src.handedness,
origin: pick.ray.origin,
dir: pick.ray.dir,
// ADDENDUM 11b: only a hit that is really ON the panel becomes the
// cursor. panelHit() clamps an off-panel intersection to the border, and
// drawing the cursor at that clamped point while the beam ended at the
// true intersection made the two drift apart - the further off the panel
// the ray pointed, the worse the gap. `distance` is still published so the
// beam still reaches the panel plane.
hit: (pick.hit && pick.hit.inBounds) ? { nx: pick.hit.nx, ny: pick.hit.ny } : null,
distance: pick.hit ? pick.hit.distance : null,
pressed: performance.now() < pressUntil
};
}
pointer = next;
S.pointer = next;
if (NS.Controls && NS.Controls.setPointer) {
try { NS.Controls.setPointer(next); } catch (e) {}
}
S.stats.activeSrc = next.visible ? (activeSrcKey || '(none)') : '(none)';
S.stats.pointer = next.source +
(next.hit ? ' HIT ' + next.hit.nx.toFixed(2) + ',' + next.hit.ny.toFixed(2) : ' (no hit)');
S.stats.inputSources = srcs.map(function (s) {
var gp = s.gamepad;
var padInfo = '';
if (gp && gp.buttons) {
var down = [];
for (var b = 0; b < gp.buttons.length; b++) {
if (gp.buttons[b] && (gp.buttons[b].pressed || gp.buttons[b].value > 0.5)) down.push(b);
}
padInfo = ':pad(' + gp.buttons.length + ')' + (down.length ? '@' + down.join(',') : '');
}
return (s.hand ? 'hand' : 'ctrl') + ':' + s.handedness + padInfo;
}).join(' ') || '(none)';
}
/* ================================================================== *
* ADDENDUM 8 — panning the video window
*
* The video layer is an equirect sphere with radius 0, i.e. the content sits at
* infinity. That has an important consequence: only the sphere's ORIENTATION
* decides which direction you see, and translating it does nothing. So panning
* the picture is purely `layer.transform`'s rotation, which rotates the content
* about the eye point — no parallax, no swimming when the head moves, and no
* decode/upload cost (8K HEVC DirectPlay is untouched).
*
* Only the video rotates. The control panel lives at a fixed pose in refSpace
* and the subtitles are head-locked in viewer space, so the UI stays in front of
* the user while the picture moves.
* ================================================================== */
var VIDEO_PITCH_LIMIT = Math.PI / 2 - 0.02; // "unlimited", minus a gimbal guard
function wrapYaw(a) {
while (a > Math.PI) a -= Math.PI * 2;
while (a < -Math.PI) a += Math.PI * 2;
return a;
}
function clampPitch(p) { return NS.clamp(p, -VIDEO_PITCH_LIMIT, VIDEO_PITCH_LIMIT); }
// q = qy(-yaw) * qx(pitch): pitch about the content's own X first, then yaw about
// the world Y — the standard look-around composition. The yaw sign is flipped so
// the STATE reads the way the user thinks about it: +yaw = the picture has been
// moved to the RIGHT, +pitch = UP (so a scene that used to need a physical
// head-down is brought up to eye level).
//
// The window's aim direction (the layer's local -Z) then works out to
// (cos p · sin yaw, sin p, -cos p · cos yaw)
// and the drag adds the ray's own yaw/pitch deltas directly, so the content point
// under the cursor stays under the cursor.
function videoQuat(yaw, pitch) {
var qy = { x: 0, y: Math.sin(-yaw / 2), z: 0, w: Math.cos(-yaw / 2) };
var qx = { x: Math.sin(pitch / 2), y: 0, z: 0, w: Math.cos(pitch / 2) };
return qMul(qy, qx);
}
function videoOrigin() { return { x: 0, y: 0, z: 0 }; }
function videoAngleTransform() {
if (typeof XRRigidTransform === 'undefined') return undefined;
return new XRRigidTransform(videoOrigin(), videoQuat(S.videoYaw, S.videoPitch));
}
function updateVideoAngleStats() {
S.stats.videoYaw = Math.round(S.videoYaw * 180 / Math.PI);
S.stats.videoPitch = Math.round(S.videoPitch * 180 / Math.PI);
S.stats.videoRotMode = videoRotStrategy();
}
/* ------------------------------------------------------------------
* HOW the aim is applied. Measured on the Quest 3 browser:
*
* * A transform passed to createEquirectLayer IS honoured -> rebuilding the
* media layer visibly moves the picture. That is the only reason the first
* version appeared to work "on release".
* * Writing layer.transform AFTER creation is ignored: the drag updated the
* angle every frame but nothing moved until the layer was rebuilt.
*
* So the primary strategy changes the layer's SPACE instead. getOffsetReference-
* Space is the recentering path every WebXR app uses for teleport/roomscale, and
* a layer's pose is recomputed from its space each frame, so assigning a rotated
* offset space rotates the picture live:
*
* layer.space = refSpace.getOffsetReferenceSpace(XRRigidTransform(0, q))
*
* The fallback ('rebuild') recreates the media layer with the transform supplied
* at creation. It is throttled, done OUTSIDE the XR frame callback, and destroys
* the old layer BEFORE creating the replacement - doing it inline with two
* XRMediaBinding layers alive on the same <video> crashed the browser.
* ------------------------------------------------------------------ */
function videoRotStrategy() {
if (S.videoRotMode === 'rebuild') return 'rebuild'; // manual escape hatch
if (S.videoRotMode === 'space') return 'space'; // manual
return S.videoTransformLive === false ? 'space' : 'transform';
}
// Is a post-creation `layer.transform` write honoured?
//
// Compare the POSITION, not the orientation. The first version compared
// orientation components and was sign/normalisation sensitive, so a perfectly
// good runtime could look read-only - and that false negative is what made the
// drag fall back to rebuilding the layer. Positions are exact.
function probeVideoTransformWritable(layer) {
if (!layer || typeof XRRigidTransform === 'undefined') return false;
var marker = { x: 0.123, y: -0.456, z: 0.789 };
try {
layer.transform = new XRRigidTransform(marker, { x: 0, y: 0, z: 0, w: 1 });
var p = layer.transform && layer.transform.position;
var okPos = !!p && Math.abs(p.x - marker.x) < 1e-6 &&
Math.abs(p.y - marker.y) < 1e-6 && Math.abs(p.z - marker.z) < 1e-6;
return okPos;
} catch (e) {
return false;
}
}
var videoSpaceCache = null;
function videoSpaceFor(yaw, pitch, force) {
if (typeof XRRigidTransform === 'undefined' || !S.refSpace) return null;
if (typeof S.refSpace.getOffsetReferenceSpace !== 'function') return null;
var c = videoSpaceCache;
if (!force && c && Math.abs(c.yaw - yaw) < 1e-4 && Math.abs(c.pitch - pitch) < 1e-4) return c.space;
// A throwing getOffsetReferenceSpace must not escape: this runs inside the XR
// frame loop, where an exception would stop the loop and freeze the session.
var sp;
try {
sp = S.refSpace.getOffsetReferenceSpace(
new XRRigidTransform(videoOrigin(), videoQuat(yaw, pitch)));
} catch (e) {
S.stats.videoSpace = 'throw: ' + ((e && e.message) || e);
return null;
}
if (!sp) return null;
videoSpaceCache = { space: sp, yaw: yaw, pitch: pitch };
return sp;
}
var REBUILD_MIN_MS = 120; // rebuild strategy: at most ~8 recreations/second
var rebuildTimer = null;
var lastRebuildAt = 0;
function scheduleVideoRebuild() {
if (rebuildTimer != null) return; // one pending is enough
var wait = Math.max(0, REBUILD_MIN_MS - (performance.now() - lastRebuildAt));
rebuildTimer = setTimeout(function () {
rebuildTimer = null;
lastRebuildAt = performance.now();
rebuildVideoLayerNow();
}, wait);
}
function cancelVideoRebuild() {
if (rebuildTimer != null) { clearTimeout(rebuildTimer); rebuildTimer = null; }
}
function rebuildVideoLayerNow() {
var session = S.session;
if (!session || !S.video) return;
// Destroy FIRST: two XRMediaBinding layers bound to one <video> element at the
// same time is what took the browser down.
var old = S.videoLayer;
S.videoLayer = null;
if (old) {
try { NS.removeLayer(old); } catch (e) {}
try { if (typeof old.destroy === 'function') old.destroy(); } catch (e) {}
}
try {
var fresh = createVideoLayer(session);
if (!fresh) return;
S.videoLayer = fresh;
NS.addLayer(fresh);
S.stats.videoRebuilds = (S.stats.videoRebuilds || 0) + 1;
} catch (e) {
NS.recordError('videoRebuild', e);
}
}
// Called for every angle change (and every drag frame). In 'space' mode this is a
// single space assignment; in 'rebuild' mode it schedules a throttled rebuild.
function applyVideoAngle(force) {
var layer = S.videoLayer;
if (!layer || !S.session) return;
if (videoRotStrategy() === 'transform') {
try {
layer.transform = videoAngleTransform();
if ('needsRedraw' in layer) layer.needsRedraw = true;
S.stats.videoRotMode = 'transform';
} catch (e) {
// Demote to the space path for the rest of the session.
S.videoTransformLive = false;
S.stats.videoTransformErr = (e && e.message) || String(e);
}
}
if (videoRotStrategy() === 'space') {
var sp = videoSpaceFor(S.videoYaw, S.videoPitch, !!force);
if (sp) {
try {
layer.space = sp;
S.stats.videoSpace = 'assigned';
} catch (e) {
S.stats.videoSpace = 'err: ' + ((e && e.message) || e);
S.videoRotMode = 'rebuild'; // fall back for good
}
} else {
S.stats.videoSpace = 'unavailable';
S.videoRotMode = 'rebuild';
}
}
if (videoRotStrategy() === 'rebuild') scheduleVideoRebuild();
updateVideoAngleStats();
void force;
}
function resetVideoAngle(why) {
S.videoYaw = 0;
S.videoPitch = 0;
if (S.session) { try { applyVideoAngle(true); } catch (e) {} }
S.stats.videoReset = why || 'reset';
updateVideoAngleStats();
}
/* ---------------- drag the picture (ADDENDUM 8) ----------------
* The pointer ray's own direction is the drag handle: rotating the aiming ray by
* δ rotates the picture by the same δ, so the content follows the hand 1:1 with
* no range limit (a panel-space cursor would run off the panel's edge).
* -------------------------------------------------------------- */
var viewDrag = null;
var lastPressSrc = null; // source / frame of the last accepted press, for
var lastPressFrame = null; // hold-style actions (the picture drag)
// Owner's gesture: HOLD the strip for half a second and move -> pan the picture.
// Anything else (a plain tap, or a hold with no movement) resets to dead ahead.
var VIEW_HOLD_MS = 500;
var VIEW_DEADZONE = 0.017; // ~1 deg of ray movement before a drag counts
function rayAngles(ray) {
if (!ray || !ray.dir) return null;
var d = ray.dir;
var len = Math.sqrt(d.x * d.x + d.y * d.y + d.z * d.z) || 1;
var dx = d.x / len, dy = d.y / len, dz = d.z / len;
return {
yaw: Math.atan2(dx, -dz),
pitch: Math.asin(NS.clamp(dy, -1, 1))
};
}
function beginViewDrag(src, frame) {
var ray = rayOf(frame, src);
var a = rayAngles(ray);
if (!a) { S.stats.viewDrag = 'no ray'; return; }
viewDrag = {
src: src, t0: performance.now(), armed: false,
a0: null, yaw0: S.videoYaw, pitch0: S.videoPitch, moved: false
};
S.stats.viewDrag = 'pressed (hold ' + VIEW_HOLD_MS + 'ms to pan)';
if (NS.Controls && NS.Controls.hold) { try { NS.Controls.hold(true); } catch (e) {} }
}
function updateViewDrag(frame) {
if (!viewDrag || !frame) return;
var ray = rayOf(frame, viewDrag.src);
if (!ray) return;
var a = rayAngles(ray);
if (!a) return;
if (!viewDrag.armed) {
// Still inside the hold window: this may yet turn out to be a reset tap.
if (performance.now() - viewDrag.t0 < VIEW_HOLD_MS) return;
// Armed. Measure deltas from HERE, not from the press, so the half second the
// user spent holding does not fling the picture.
viewDrag.armed = true;
viewDrag.a0 = a;
S.stats.viewDrag = 'armed (drag to pan)';
return;
}
var dyaw = wrapYaw(a.yaw - viewDrag.a0.yaw);
var dpitch = a.pitch - viewDrag.a0.pitch;
if (Math.abs(dyaw) < VIEW_DEADZONE && Math.abs(dpitch) < VIEW_DEADZONE) return;
var ny = wrapYaw(viewDrag.yaw0 + dyaw);
var np = clampPitch(viewDrag.pitch0 + dpitch);
if (Math.abs(ny - S.videoYaw) < 1e-4 && Math.abs(np - S.videoPitch) < 1e-4) return;
viewDrag.moved = true;
S.videoYaw = ny;
S.videoPitch = np;
applyVideoAngle(false);
}
// Release. A press that never panned is a reset (owner: "按住 0.5s 后拖动才是
// 拖动,否则算复位"), which also means a hold with no movement resets.
function endViewDrag() {
if (!viewDrag) return;
var moved = viewDrag.moved;
viewDrag = null;
if (NS.Controls && NS.Controls.hold) { try { NS.Controls.hold(false); } catch (e) {} }
applyVideoAngle(true); // settle the final angle
if (moved) {
S.stats.viewDrag = 'ended (moved)';
return;
}
resetVideoAngle('tap');
S.stats.viewDrag = 'reset (tap)';
}
/* ================================================================== *
* Fixed panel pose
*
* The panel simply floats at a fixed spot in front of the session origin:
* lower middle of the view. It does NOT follow the head at all - no lazy
* follow, no gaze tracking, no re-centring. Identity rotation, matching the
* orientation that was verified working when the panel lived in viewer space.
* ================================================================== */
var PANEL_Y = -0.34;
var PANEL_Z = -1.45;
var panelPose = null;
function updatePanelPose(frame) {
if (panelPose) return; // set once; never moves again
var layer = controlsLayer();
if (!layer) return;
panelPose = { x: 0, y: PANEL_Y, z: PANEL_Z };
try {
layer.transform = new XRRigidTransform({ x: 0, y: PANEL_Y, z: PANEL_Z });
S.stats.panelPose = '0,' + PANEL_Y + ',' + PANEL_Z + ' (fixed)';
} catch (e) {
if (!S.stats.panelPoseErr) S.stats.panelPoseErr = String((e && e.message) || e);
}
}
// ADDENDUM 7: selectstart used to show() the bar unconditionally — the second,
// independent reason the bar appeared on every pinch. Summoning is now decided
// in pointerDown() from the actual aim, so this listener is gone.
/* ------------------------------------------------------------------
* Activation.
*
* The platform already does gesture recognition for us, so we do NOT compute
* thumb/index joint distances ourselves:
* - controllers and (on some builds) hands fire selectstart/select/selectend
* - Meta documents hand pinch as "implemented in the emulated Gamepad
* attribute for the hand as a button press", which does NOT always raise a
* select event - so the gamepad buttons must be polled as well.
* Palm pinch is reserved by the system (left hand = menu, leaves the session),
* so only the ordinary pinch/trigger reaches us.
* ------------------------------------------------------------------ */
var ACTIVATE_COOLDOWN_MS = 250;
var lastActivate = 0;
// ADDENDUM 11b: the cooldown is per INPUT SOURCE, not global. With hands, a
// stray gamepad edge from one hand used to swallow the other hand's `select`
// within 250 ms, so the click silently used the first hand's position.
var lastActivateByKey = {};
var padPrev = new WeakMap();
/* ---------------- grab & drag the subtitle strip ---------------- *
* The strip is a head-locked quad in viewer space, so the ray and the strip
* share one coordinate system - no world-space math is needed.
* y follows the drag on a FIXED reference plane
* z follows the hand moving toward/away (pulling a real object closer)
* ---------------------------------------------------------------- */
var grab = null;
function subtitleStripLayer() {
if (!NS.Subtitles || typeof NS.Subtitles.getLayer !== 'function') return null;
try { return NS.Subtitles.getLayer(); } catch (e) { return null; }
}
// Returns a hit on the subtitle strip, or null.
//
// Two deliberate restrictions, both needed because the strip occupies the
// lower centre of the view by default:
// 1. only a REAL quad hit counts (no padding)
// 2. only the central 40% counts - the visible text is centred in the quad
// (the crop is letterboxed into the texture), so this is the text itself.
// Without them the strip would swallow every aim in the lower half of the view
// and shadow the control bar, which overlaps it in y.
function subtitleStripHit(frame, src) {
if (!S.subtitles || !NS.Subtitles) return null;
var layer = subtitleStripLayer();
if (!layer) return null;
var ray = rayOf(frame, src);
if (!ray) return null;
var h = panelHit(frame, ray, layer, 0.35, 2.0);
if (!h || !h.inBounds) return null;
if (h.nx < 0.30 || h.nx > 0.70 || h.ny < 0.30 || h.ny > 0.70) return null;
return { ray: ray, hit: h, layer: layer };
}
function beginGrab(src, s, frame) {
var p0 = sourcePointInViewer(frame, src);
if (!p0) { S.stats.grab = 'no source point'; return; }
grab = {
src: src,
p0: p0,
place0: { y: S.subPlacement.y, z: S.subPlacement.z, width: S.subPlacement.width },
moved: false
};
S.stats.grab = 'started';
S.stats.grabValue = 'y=' + S.subPlacement.y.toFixed(2) + ' z=' + S.subPlacement.z.toFixed(2);
log('grab start', S.stats.grabValue);
}
// The hand/controller position in VIEWER space. The subtitle strip is
// head-locked, so moving the strip with a hand delta in the SAME head-relative
// frame is what keeps the drag stable while the head turns.
//
// Note: with hands the aiming is gaze-based, so the drag must NOT follow the
// gaze (that would swing the strip every time the head moves). The hand does
// the dragging; the gaze only decides WHICH thing is grabbed.
function sourcePointInViewer(frame, src) {
if (!frame || !src || !NS.viewerSpace) return null;
try {
if (src.hand) {
var joint = src.hand.get('wrist') || src.hand.get('index-finger-tip');
var jp = joint ? frame.getJointPose(joint, NS.viewerSpace) : null;
if (jp) return { x: jp.transform.position.x, y: jp.transform.position.y, z: jp.transform.position.z };
return null;
}
var sp = src.gripSpace || src.targetRaySpace;
var pp = sp ? frame.getPose(sp, NS.viewerSpace) : null;
if (pp) return { x: pp.transform.position.x, y: pp.transform.position.y, z: pp.transform.position.z };
} catch (e) {}
return null;
}
function updateGrabFrame(frame) {
if (!grab || !frame) return;
var p = sourcePointInViewer(frame, grab.src);
if (!p) return;
var ny = NS.clamp(grab.place0.y + (p.y - grab.p0.y), -0.95, -0.05);
// viewer space forward is -Z, so pulling the hand back increases p.z and the
// strip comes closer - matching how pulling a real object behaves
var nz = NS.clamp(grab.place0.z + (p.z - grab.p0.z), -2.6, -0.35);
// ADDENDUM 6: with the angular lock on, pulling the strip closer keeps its
// screen position, so the hand's depth motion must also carry y by the
// locked y/z ratio of the grab start. Vertical hand motion still adds on top.
if (S.subLockAngle && grab.place0.z) {
var k0 = grab.place0.y / grab.place0.z;
ny = NS.clamp(k0 * nz + (p.y - grab.p0.y), -0.95, -0.05);
}
if (Math.abs(ny - S.subPlacement.y) < 0.001 && Math.abs(nz - S.subPlacement.z) < 0.001) return;
grab.moved = true;
S.subPlacement.y = ny;
S.subPlacement.z = nz;
try { NS.Subtitles.setPlacement({ y: ny, z: nz, width: S.subPlacement.width }); } catch (e) {}
if (NS.Subtitles && NS.Subtitles.getPlacement) { try { S.subPlacement = NS.Subtitles.getPlacement(); } catch (e) {} }
S.stats.grabValue = 'y=' + ny.toFixed(2) + ' z=' + nz.toFixed(2);
}
function endGrab() {
if (!grab) return;
var moved = grab.moved;
grab = null;
S.stats.grab = moved ? 'ended (moved)' : 'ended';
if (moved) saveSettings();
}
/* ---------------- activation ---------------- */
// ADDENDUM 7 — how the control bar is summoned:
// * pressing/aiming now only SUMMONS the bar when the ray actually lands on
// (or near) the bar. It used to appear on ANY pinch anywhere in the view,
// which made it pop up constantly.
// * the summoning press never also clicks a button, and for PANEL_ARM_MS
// after the bar appears all activations are ignored — otherwise the hand
// travelling onto the bar right after the summon triggers a random button.
// * while LOCKED, summoning shows only the padlock panel (see the padlock
// section below) — no progress bar, nothing adjustable.
var PANEL_ARM_MS = 500;
var barShownAt = -1e9;
/* ---------------- ADDENDUM 7b: the padlock ----------------
* The padlock is an ordinary button on the control panel (the `lock` action),
* so it uses the same cursor, hit test and activation path as every other
* button. Locking swaps the panel to the minimal "locked" mode: only the
* padlock is drawn and only the padlock is hit-tested. The panel then auto-hides
* like it always does; the next summon brings up the padlock alone.
*/
function toggleControlsLock() {
S.ctlLock = !S.ctlLock;
S.stats.ctlLock = S.ctlLock;
if (NS.Controls && NS.Controls.setLock) { try { NS.Controls.setLock(S.ctlLock); } catch (e) {} }
// show() re-picks the mode from the new lock state and restarts the auto-hide
// timer, so locking -> padlock-only -> auto-hide all fall out of one lifecycle.
if (NS.Controls && NS.Controls.show) { try { NS.Controls.show(); } catch (e) {} }
// Arm the panel again: the press that UNLOCKS must not also land on whatever
// button is now under the cursor.
barShownAt = performance.now();
S.stats.pressAt = (S.ctlLock ? 'LOCKED' : 'UNLOCKED') + ' (armed ' + PANEL_ARM_MS + 'ms)';
}
function pointerDown(src, frame, via) {
if (!S.session) return;
var now = performance.now();
var actKey = srcKey(src) || (via || '?');
if (now - (lastActivateByKey[actKey] || 0) < ACTIVATE_COOLDOWN_MS) return;
lastActivateByKey[actKey] = now;
lastActivate = now;
S.stats.lastActivate = (via || '?') + (src && src.handedness ? ':' + src.handedness : '');
S.stats.pressSrc = actKey;
// Captured BEFORE show(): when the control bar is already up, a pinch belongs
// to the bar, so it must not also yank the subtitles.
var barWasShown = NS.Controls && NS.Controls.isVisible ? !!NS.Controls.isVisible() : false;
// ADDENDUM 11b: attribute the shot to the acting source. If its ray cannot be
// resolved, MISS - never fall back to whatever hand the per-frame pointer was
// on, which is exactly how a right-hand pinch ended up landing on the left
// hand's position.
frame = frame || S.lastFrame;
if (src) {
if (frame) { try { updatePointer(frame, src); } catch (e) {} }
if (!pointer || !pointer.visible) {
S.stats.pressAt = 'MISS (acting source has no ray)';
S.stats.pressPtr = '(no ray)';
return;
}
S.stats.pressPtr = pointer.source + (pointer.hit ? ' HIT' : ' nohit');
} else if (frame) {
try { updatePointer(frame); } catch (e) {}
}
// 1) grabbing the subtitle strip wins, but only while the bar is down
if (frame && !barWasShown) {
try {
var s = subtitleStripHit(frame, src);
if (s) {
if (NS.Controls && NS.Controls.show) { try { NS.Controls.show(); } catch (e) {} }
barShownAt = now;
beginGrab(src, s, frame);
return;
}
} catch (e) { NS.recordError('grabStart', e); }
}
var onPanel = !!(pointer && pointer.visible && pointer.hit);
// Summoning is deliberately MORE forgiving than button hitting: the ray only
// has to pass near the bar to bring it up (the arming delay is what prevents
// a mis-click), while the on-bar cursor stays exact. Without this, a ray that
// grazed the bar's edge could never summon it at all.
var summonable = onPanel;
if (!summonable && frame && pointer && pointer.visible) {
try {
summonable = !!panelHit(frame, { origin: pointer.origin, dir: pointer.dir },
controlsLayer(), 0.5, 0.9);
} catch (e) { summonable = false; }
}
// 2) bar is down -> normal action, once it is armed
if (barWasShown) {
if (now - barShownAt < PANEL_ARM_MS) {
S.stats.pressAt = 'IGNORED (arming)'; // the summon is still settling
return;
}
if (!onPanel) { S.stats.pressAt = 'MISS (no hit on the panel)'; return; }
if (NS.Controls && NS.Controls.show) { try { NS.Controls.show(); } catch (e) {} } // extend auto-hide
pressUntil = now + 300;
S.stats.pressAt = pointer.hit.nx.toFixed(2) + ',' + pointer.hit.ny.toFixed(2);
// Remembered for hold-style actions (the ADDENDUM 8 picture drag), which need
// the input source and frame that started them.
lastPressSrc = src;
lastPressFrame = frame;
try { NS.Controls.handleSelect(src, frame); }
catch (e) { NS.recordError('handleSelect', e); }
return;
}
// 3) bar is up? no. Only a real aim summons it (and only when unlocked).
if (S.ctlLock) { S.stats.pressAt = 'MISS (panel locked)'; return; }
if (!summonable) { S.stats.pressAt = 'MISS (not aiming at the panel)'; return; }
if (NS.Controls && NS.Controls.show) { try { NS.Controls.show(); } catch (e) {} }
barShownAt = now;
S.stats.pressAt = 'SUMMON (armed ' + PANEL_ARM_MS + 'ms)';
}
var pressUntil = 0;
function pointerUp() {
endGrab();
endViewDrag();
}
function pollGamepads(frame) {
if (!S.session) return;
var srcs = S.session.inputSources ? Array.prototype.slice.call(S.session.inputSources) : [];
for (var i = 0; i < srcs.length; i++) {
var src = srcs[i];
var gp = src.gamepad;
if (!gp || !gp.buttons) continue;
var pressed = false;
for (var b = 0; b < gp.buttons.length; b++) {
var bt = gp.buttons[b];
if (bt && (bt.pressed || bt.value > 0.5)) { pressed = true; break; }
}
var prev = padPrev.get(src) || false;
padPrev.set(src, pressed);
if (pressed && !prev) pointerDown(src, frame, 'gamepad');
else if (!pressed && prev) pointerUp();
}
}
function onSelect(ev) {
pointerDown(ev && ev.inputSource, S.lastFrame, 'select');
}
function onSelectEnd() {
pointerUp();
}
/* ---------------- live subtitle setters (single source of truth) ---------------- */
// state.subPlacement / subAngleDeg are re-read from the module after every
// call: with the angular lock on the module DERIVES width (and, for a depth
// change, y), which is what gets persisted.
function setSubPlacementLive(p) {
if (NS.Subtitles && NS.Subtitles.setPlacement) {
try { NS.Subtitles.setPlacement(p); } catch (e) { NS.recordError('setPlacement', e); }
if (NS.Subtitles.getPlacement) { try { S.subPlacement = NS.Subtitles.getPlacement(); } catch (e) {} }
if (NS.Subtitles.getAngleDeg) { try { S.subAngleDeg = NS.Subtitles.getAngleDeg(); } catch (e) {} }
} else {
if (typeof p.y === 'number') S.subPlacement.y = NS.clamp(p.y, -0.95, -0.05);
if (typeof p.z === 'number') S.subPlacement.z = NS.clamp(p.z, -2.6, -0.35);
if (typeof p.width === 'number') S.subPlacement.width = NS.clamp(p.width, 0.2, 4.0);
}
if (panelSync) panelSync();
saveSettings();
}
// Locked angular width, in degrees. With the lock on this is the size control.
function setSubAngleLive(deg) {
S.subAngleDeg = NS.clamp(deg, 20, 120);
if (NS.Subtitles && NS.Subtitles.setAngleDeg) {
try { NS.Subtitles.setAngleDeg(S.subAngleDeg); } catch (e) { NS.recordError('setAngleDeg', e); }
}
if (NS.Subtitles && NS.Subtitles.getPlacement) { try { S.subPlacement = NS.Subtitles.getPlacement(); } catch (e) {} }
if (NS.Subtitles && NS.Subtitles.getAngleDeg) { try { S.subAngleDeg = NS.Subtitles.getAngleDeg(); } catch (e) {} }
if (panelSync) panelSync();
saveSettings();
}
// ADDENDUM 6 switch: depth-only moves (locked) vs the old free placement.
// Extra live readers handed to the control bar. The bar is a separate module
// with its own private state, so anything it needs to DISPLAY (rather than
// mutate) has to be readable through here or through __JFVR.state.
function controlsExtra() {
return { subtitlesOn: function () { return !!S.subtitles; } };
}
function setSubOpacityLive(a) {
S.subOpacity = NS.clamp(a, 0.1, 1.0);
if (NS.Subtitles && NS.Subtitles.setOpacity) {
try { NS.Subtitles.setOpacity(S.subOpacity); } catch (e) {}
}
if (panelSync) panelSync();
saveSettings();
}
function handleControlAction(action) {
var v = S.video;
if (!action) return;
S.stats.ctlLastAction = JSON.stringify(action);
log('control action', action);
// The padlock and the subtitle actions do not need a <video>.
switch (action.type) {
case 'lock': toggleControlsLock(); break;
case 'view_drag':
if (lastPressSrc && lastPressFrame) beginViewDrag(lastPressSrc, lastPressFrame);
else S.stats.viewDrag = 'no press context';
break;
case 'sub_up': setSubPlacementLive({ y: S.subPlacement.y + 0.04 }); break;
case 'sub_down': setSubPlacementLive({ y: S.subPlacement.y - 0.04 }); break;
case 'sub_near': setSubPlacementLive({ z: S.subPlacement.z + 0.15 }); break;
case 'sub_far': setSubPlacementLive({ z: S.subPlacement.z - 0.15 }); break;
case 'sub_smaller':
if (S.subLockAngle) setSubAngleLive(S.subAngleDeg - 5);
else setSubPlacementLive({ width: S.subPlacement.width - 0.15 });
break;
case 'sub_bigger':
if (S.subLockAngle) setSubAngleLive(S.subAngleDeg + 5);
else setSubPlacementLive({ width: S.subPlacement.width + 0.15 });
break;
case 'sub_opaque_down': setSubOpacityLive(S.subOpacity - 0.05); break;
case 'sub_opaque_up': setSubOpacityLive(S.subOpacity + 0.05); break;
case 'sub_reset':
if (NS.Subtitles && NS.Subtitles.resetPlacement) { try { NS.Subtitles.resetPlacement(); } catch (e) {} }
if (NS.Subtitles && NS.Subtitles.getPlacement) { try { S.subPlacement = NS.Subtitles.getPlacement(); } catch (e) {} }
if (NS.Subtitles && NS.Subtitles.getAngleDeg) { try { S.subAngleDeg = NS.Subtitles.getAngleDeg(); } catch (e) {} }
setSubOpacityLive(0.85);
if (panelSync) panelSync();
S.stats.subResetAt = Date.now();
break;
}
if (!v) { updateDiag(); return; }
switch (action.type) {
case 'playpause':
if (v.paused) v.play().catch(function () {}); else v.pause();
break;
case 'back10':
v.currentTime = Math.max(0, v.currentTime - 10);
break;
case 'fwd10':
v.currentTime = Math.min(isFinite(v.duration) ? v.duration : v.currentTime + 10, v.currentTime + 10);
break;
case 'seek':
if (isFinite(v.duration)) v.currentTime = NS.clamp(action.value, 0, 1) * v.duration;
break;
case 'subs':
S.subtitles = !S.subtitles;
if (NS.Subtitles) {
NS.Subtitles.setMode(S.subtitles ? (S.subMode === 'off' ? 'hud' : S.subMode) : 'off');
if (S.subtitles) { try { NS.Subtitles.prepare(); } catch (e) {} }
}
saveSettings();
break;
}
updateDiag();
}
/* ================================================================== *
* boot
* ================================================================== */
var lastVideo = null;
function scan() {
var v = findVideo();
if (v === lastVideo) return;
lastVideo = v;
S.video = v;
NS.video = v;
if (v) {
log('video found', v.videoWidth + 'x' + v.videoHeight, (v.currentSrc || '').slice(0, 80));
ensureButton();
S.detected = '';
S.stats = { fps: null, frames: 0 };
applyAutoDetect().then(function () { refreshHint(); updateDiag(); });
if (NS.Controls && NS.Controls.setVideo) { try { NS.Controls.setVideo(v, controlsExtra()); } catch (e) {} }
} else {
removeButton();
}
}
function boot() {
log('boot v' + NS.version + ' | secure=' + window.isSecureContext +
' xr=' + !!navigator.xr + ' hand=' + NS.caps.hasHandTracking);
loadSettings();
// Subtitles are per-session: never restored as OFF, always ON at boot. Both
// `subtitles` and `subMode` could otherwise leave the layer uncreated.
S.subtitles = true;
if (S.subMode === 'off') S.subMode = 'hud';
S.subLayout = 'auto'; // ADDENDUM 10: the override is per-session only
try { if (NS.Subtitles && NS.Subtitles.init) NS.Subtitles.init(); } catch (e) { NS.recordError('Subtitles.init', e); }
try { if (NS.Controls && NS.Controls.init) NS.Controls.init(); } catch (e) { NS.recordError('Controls.init', e); }
try { if (NS.Hands && NS.Hands.init) NS.Hands.init(); } catch (e) { NS.recordError('Hands.init', e); }
scan();
new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true });
setInterval(scan, 1500);
window.addEventListener('beforeunload', function () {
if (S.session) { try { S.session.end(); } catch (e) {} }
});
installFrameTracker();
window.__JFVR_STATE__ = S;
window.__JFVR_API = NS;
log('ready');
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot, { once: true });
} else {
boot();
}
})();