File size: 25,867 Bytes
4e6a175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homography Viewer — RGB/IR overlay</title>

<!--
  ============================================================================
   HOMOGRAPHY VIEWER   (read-only companion to image-register.html)
  ============================================================================
   Loads a FilteredDataset10s-style tree and DISPLAYS each Pair-ID folder's
   already-fitted homographies. No picking, no fitting — just viewing.

   Folder layout it understands (select the dataset root or one Pair-ID folder):
        <key>/rgb/f02100.png
        <key>/ir /f02100.png
        <key>/homography/homography.json      <- the fit to view

   homography.json carries one or more SUBSETS, each with a 3x3 matrix that maps
   IR_pixel -> RGB_pixel and a frame range (frame_start/frame_end names). We show
   the frames PRESENT in rgb/ & ir/, warp each frame's IR by the matrix of the
   subset whose frame-number range contains it, and lay it over the RGB.

   Not all frames a subset was fit on are necessarily present (a subset fit on
   f00300–f08100 may only ship f02100–f04800). Missing frames are simply skipped.
   A present frame that falls in NO subset range is skipped too.

   The perspective warp is done natively by the browser via CSS matrix3d — the IR
   <img> sits in RGB-pixel space and matrix3d applies the homography, so it runs
   straight from file:// with no server.
  ============================================================================
-->

<style>
  :root {
    --bg: #0e0f13; --panel: #191b22; --panel-2: #21242d; --border: #2c303b;
    --text: #e6e8ee; --muted: #9aa0ac; --accent: #4f8cff; --accent-2: #3a6fd8; --danger: #ff5a5a; --ok: #57c97a;
    color-scheme: dark;
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text);
    font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; height: 100%; }
  body { display: flex; flex-direction: column; height: 100vh; }

  header { padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--border);
    display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
  header h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: .2px; }

  .loaders { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
  .file-btn { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    padding: 6px 10px; border-radius: 7px; cursor: pointer; font-size: 12px; }
  .file-btn:hover { border-color: var(--accent); }
  input[type=file] { display: none; }
  select#groupSel { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    border-radius: 7px; padding: 6px 8px; font-size: 12px; max-width: 280px; }

  .filepath { flex: 1; min-width: 0; font-size: 11px; color: var(--muted);
    font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; direction: rtl; text-align: left; }

  .error { display: none; margin: 8px 16px 0; padding: 10px 14px; background: #2a1416;
    border: 1px solid #6b2b30; border-radius: 8px; color: #ffd7da; font-size: 12px; white-space: pre-wrap; }
  .error.show { display: block; }

  /* Thin bar: which subset the current frame falls in + the matrix. */
  .info-bar { display: none; align-items: center; gap: 14px; flex-wrap: wrap;
    padding: 6px 16px; background: var(--panel-2); border-bottom: 1px solid var(--border); font-size: 12px; }
  .info-bar.show { display: flex; }
  .info-bar .lab { color: var(--muted); font-weight: 600; }
  .info-bar .val { color: var(--text); font-variant-numeric: tabular-nums; }
  .info-bar .val.accent { color: var(--accent); }
  .subset-pills { display: flex; gap: 4px; flex-wrap: wrap; }
  .sp { background: var(--panel); border: 1px solid var(--border); color: var(--muted);
    padding: 3px 8px; border-radius: 6px; font-size: 11px; font-variant-numeric: tabular-nums; cursor: pointer; }
  .sp:hover { border-color: var(--accent); }
  .sp.active { border-color: var(--accent); color: var(--accent); background: #262a34; }
  button.mini { background: var(--panel); border: 1px solid var(--border); color: var(--text);
    padding: 3px 9px; border-radius: 6px; cursor: pointer; font-size: 11px; margin-left: auto; }
  button.mini:hover { border-color: var(--accent); }

  main { flex: 1; display: flex; padding: 8px; min-height: 0; }
  .stage { position: relative; flex: 1; width: 100%; background: #000; border: 1px solid var(--border);
    border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; min-height: 0; }
  /* #scene is sized in RGB pixels; a single transform (fit + user zoom/pan) scales
     it into the stage. The IR img lives inside in RGB-pixel space via matrix3d,
     so it stays locked to the RGB underneath at every zoom. */
  #scene { position: absolute; top: 0; left: 0; transform-origin: 0 0; will-change: transform; }
  #scene img { position: absolute; top: 0; left: 0; -webkit-user-drag: none; user-select: none; display: block; }
  #scene img.rgb { image-rendering: auto; }
  #scene img.ir  { transform-origin: 0 0; opacity: var(--ir-opacity, .7); }
  #scene img.ir.hidden { opacity: 0; }

  .badge { position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,.6); color: #fff;
    padding: 3px 8px; border-radius: 6px; font-size: 11px; pointer-events: none; z-index: 2;
    font-variant-numeric: tabular-nums; }
  .empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
    color: var(--muted); font-size: 13px; text-align: center; padding: 20px; pointer-events: none; }
  .loading { position: absolute; inset: 0; z-index: 10; display: none; pointer-events: none;
    flex-direction: column; align-items: center; justify-content: center; gap: 12px;
    background: rgba(14,15,19,.55); color: var(--text); font-size: 13px; }
  .loading.show { display: flex; }
  .loading .spinner { width: 34px; height: 34px; border-radius: 50%;
    border: 3px solid var(--panel-2); border-top-color: var(--accent); animation: spin .8s linear infinite; }
  @keyframes spin { to { transform: rotate(360deg); } }

  footer { background: var(--panel); border-top: 1px solid var(--border); padding: 10px 16px 12px;
    display: flex; flex-direction: column; gap: 10px; }
  .scrubber-row { display: flex; align-items: center; gap: 12px; }
  .frameLabel { font-variant-numeric: tabular-nums; font-size: 12px; color: var(--muted); min-width: 260px; }
  input[type=range].seek { flex: 1; height: 6px; -webkit-appearance: none; appearance: none;
    background: var(--panel-2); border-radius: 4px; outline: none; cursor: pointer; }
  input[type=range].seek::-webkit-slider-thumb { -webkit-appearance: none; appearance: none;
    width: 15px; height: 15px; border-radius: 50%; background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].seek::-moz-range-thumb { width: 15px; height: 15px; border-radius: 50%;
    background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].seek:disabled { opacity: .45; cursor: not-allowed; }

  .controls { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  button.ctrl { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    padding: 8px 12px; border-radius: 8px; cursor: pointer; font-size: 13px; min-width: 40px;
    display: inline-flex; align-items: center; justify-content: center; gap: 6px; }
  button.ctrl:hover:not(:disabled) { border-color: var(--accent); background: #262a34; }
  button.ctrl:disabled { opacity: .4; cursor: not-allowed; }
  .group { display: flex; align-items: center; gap: 8px; padding-left: 12px; margin-left: 4px; border-left: 1px solid var(--border); }
  .group:first-child { border-left: none; padding-left: 0; margin-left: 0; }
  .group label { font-size: 12px; color: var(--muted); }
  input[type=range].ir-opacity { width: 130px; height: 6px; -webkit-appearance: none; appearance: none;
    background: var(--panel-2); border-radius: 4px; outline: none; cursor: pointer; }
  input[type=range].ir-opacity::-webkit-slider-thumb { -webkit-appearance: none; appearance: none;
    width: 14px; height: 14px; border-radius: 50%; background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].ir-opacity::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%;
    background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].ir-opacity:disabled { opacity: .45; cursor: not-allowed; }
  .opacity-badge { font-size: 12px; color: var(--accent); font-variant-numeric: tabular-nums; min-width: 38px; text-align: right; }
  .spacer { flex: 1; }
  pre.mat { background: var(--panel-2); padding: 4px 8px; border-radius: 6px; font-size: 11px; margin: 0;
    font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre; color: var(--muted); }
  kbd { background: var(--panel-2); border: 1px solid var(--border); border-bottom-width: 2px; border-radius: 4px;
    padding: 1px 5px; font-size: 11px; font-family: inherit; color: var(--text); }
  .hint { font-size: 11px; color: var(--muted); }
</style>
</head>
<body>
  <header>
    <h1>🗺️ Homography Viewer</h1>
    <div class="loaders">
      <label><span class="file-btn">📁 Load folder</span><input type="file" id="dirInput" webkitdirectory></label>
      <select id="groupSel" style="display:none" title="Pair-ID folder to view"></select>
    </div>
    <span class="filepath" id="pathLbl" title="No folder loaded">—</span>
  </header>

  <div id="error" class="error"></div>

  <div id="infoBar" class="info-bar">
    <span><span class="lab">Subset</span> <span class="subset-pills" id="subsetPills"></span></span>
    <span><span class="lab">range</span> <span class="val" id="subsetRange">—</span></span>
    <span><span class="lab">model</span> <span class="val accent" id="subsetModel">—</span></span>
    <span><span class="lab">n_pairs</span> <span class="val" id="subsetN">—</span></span>
    <span><span class="lab">rmse</span> <span class="val" id="subsetRmse">—</span></span>
    <button class="mini" id="btnMat" title="Show the 3x3 IR→RGB matrix">H ▾</button>
  </div>

  <main>
    <div class="stage" id="stage">
      <span class="badge" id="badge">—</span>
      <div id="scene">
        <img class="rgb" id="imgRGB" alt="RGB">
        <img class="ir"  id="imgIR"  alt="warped IR">
      </div>
      <div class="empty" id="empty">Click “📁 Load folder” and choose the dataset root<br>
        (or one Pair-ID folder like Graminoid-01)</div>
      <div class="loading" id="loading"><div class="spinner"></div><div>Loading…</div></div>
    </div>
  </main>

  <footer>
    <div class="scrubber-row">
      <span class="frameLabel" id="frameLabel">No folder loaded</span>
      <input type="range" class="seek" id="seek" min="0" max="1" value="0" step="1" disabled>
    </div>
    <div class="controls">
      <div class="group">
        <button class="ctrl" id="btnFirst" title="First frame (Home)" disabled>⏮</button>
        <button class="ctrl" id="btnPrev"  title="Previous frame (←)"  disabled>◀ Prev</button>
        <button class="ctrl" id="btnNext"  title="Next frame (→)"      disabled>Next ▶</button>
        <button class="ctrl" id="btnLast"  title="Last frame (End)"    disabled>⏭</button>
      </div>
      <div class="spacer"></div>
      <div class="group">
        <label for="irOpacity">IR opacity</label>
        <input type="range" class="ir-opacity" id="irOpacity" min="0" max="100" value="70" step="1" disabled>
        <span class="opacity-badge" id="irOpacityValue">70%</span>
        <button class="ctrl" id="btnToggleIR" title="Hide / Show IR overlay (I)" disabled>Hide IR</button>
      </div>
      <div class="group">
        <button class="ctrl" id="btnResetView" title="Reset zoom/pan (0)" disabled>↺ View</button>
      </div>
    </div>
    <div class="hint">
      Shortcuts: <kbd>←</kbd>/<kbd>→</kbd> prev/next · <kbd>Home</kbd>/<kbd>End</kbd> first/last · <kbd>I</kbd> hide/show IR ·
      <kbd>scroll</kbd> zoom · <kbd>right-drag</kbd> pan · <kbd>0</kbd> reset view
    </div>
  </footer>

<script>
"use strict";
// ============================================================================
//  Small helpers
// ============================================================================
const $ = (id) => document.getElementById(id);
const clamp = (x, lo, hi) => x < lo ? lo : (x > hi ? hi : x);
const errorEl = $("error");
const showError = (m) => { errorEl.textContent = m; errorEl.classList.add("show"); };
const clearError = () => { errorEl.textContent = ""; errorEl.classList.remove("show"); };
const frameNo = (name) => { const m = name.match(/\d+/); return m ? +m[0] : Infinity; };
const shortLabel = (key) => key.split("/").filter(Boolean).pop() || key;

// ============================================================================
//  DATA MODEL
//  GROUPS = [ { key, frames: [ {name, num, rgbFile, irFile, subset} ], subsets, rgbSize, irSize } ]
//  Each frame already carries the subset (and thus matrix) it belongs to; frames
//  outside every subset range were dropped at discovery time.
// ============================================================================
let GROUPS = [];
let gi = 0;   // active group index
let fi = 0;   // active frame index within the active group's PRESENT frames

// Discover Pair-ID groups from a webkitdirectory file list. A file at
// "<key>/rgb|ir/<name>.png" is a frame; "<key>/homography/homography.json" is the fit.
async function discoverGroups(files) {
  const map = new Map();   // key -> { rgb:Map, ir:Map, homographyJson:File|null }
  for (const f of files) {
    const path = f.webkitRelativePath || f.name;
    const m = /^(.*)\/(rgb|ir|homography)\/([^\/]+)$/i.exec(path);
    if (!m) continue;
    const key = m[1], role = m[2].toLowerCase(), name = m[3];
    if ((role === "rgb" || role === "ir") && !/\.png$/i.test(name)) continue;
    if (!map.has(key)) map.set(key, { rgb: new Map(), ir: new Map(), homographyJson: null });
    const g = map.get(key);
    if (role === "homography") { if (name.toLowerCase() === "homography.json") g.homographyJson = f; }
    else g[role].set(name, f);
  }

  const out = [];
  for (const [key, g] of map) {
    if (!g.homographyJson) continue;   // nothing to view without a fit
    let doc; try { doc = JSON.parse(await g.homographyJson.text()); } catch { continue; }
    const subsets = (doc && doc.subsets) || [];
    if (!subsets.length) continue;
    // Frame present in BOTH rgb/ and ir/, tagged with the subset whose frame-NUMBER
    // range contains it (robust to frames the subset was fit on but that aren't shipped).
    const frames = [];
    for (const [name, rgbFile] of g.rgb) {
      const irFile = g.ir.get(name);
      if (!irFile) continue;
      const num = frameNo(name);
      const subset = subsets.find(s => num >= frameNo(s.frame_start) && num <= frameNo(s.frame_end));
      if (!subset) continue;                          // in no subset's range — skip
      if (!Array.isArray(subset.matrix)) continue;    // no usable matrix — skip
      frames.push({ name, num, rgbFile, irFile, subset });
    }
    if (!frames.length) continue;
    frames.sort((a, b) => a.num - b.num);
    out.push({ key, frames, subsets,
      rgbSize: (doc && doc.rgb_size) || [2688, 1512],
      irSize:  (doc && doc.ir_size)  || [640, 360] });
  }
  out.sort((a, b) => a.key.localeCompare(b.key));
  return out;
}

// ============================================================================
//  VIEW (fit + user zoom/pan) — one transform on #scene, in RGB-pixel space.
// ============================================================================
const stage = $("stage"), scene = $("scene");
let view = { scale: 1, tx: 0, ty: 0 };   // scene.transform = translate(tx,ty) scale(scale)
let fitScale = 1;

function applyView() {
  scene.style.transform = `translate(${view.tx}px, ${view.ty}px) scale(${view.scale})`;
}
function fitView() {
  const g = GROUPS[gi]; if (!g) return;
  const [w, h] = g.rgbSize;
  const sw = stage.clientWidth, sh = stage.clientHeight;
  fitScale = Math.min(sw / w, sh / h);
  view.scale = fitScale;
  view.tx = (sw - w * fitScale) / 2;
  view.ty = (sh - h * fitScale) / 2;
  applyView();
}
// Zoom about the cursor: keep the scene point under the pointer fixed.
stage.addEventListener("wheel", (e) => {
  if (!GROUPS.length) return;
  e.preventDefault();
  const r = stage.getBoundingClientRect();
  const px = e.clientX - r.left, py = e.clientY - r.top;
  const factor = Math.exp(-e.deltaY * 0.0015);
  const ns = clamp(view.scale * factor, fitScale, fitScale * 40);   // never zoom out past fit
  const k = ns / view.scale;
  view.tx = px - k * (px - view.tx);
  view.ty = py - k * (py - view.ty);
  view.scale = ns;
  applyView();
}, { passive: false });
// Right-drag to pan.
let panning = null;
stage.addEventListener("contextmenu", (e) => e.preventDefault());
stage.addEventListener("pointerdown", (e) => {
  if (e.button !== 2 || !GROUPS.length) return;
  panning = { x: e.clientX, y: e.clientY, tx: view.tx, ty: view.ty };
  stage.setPointerCapture(e.pointerId);
});
stage.addEventListener("pointermove", (e) => {
  if (!panning) return;
  view.tx = panning.tx + (e.clientX - panning.x);
  view.ty = panning.ty + (e.clientY - panning.y);
  applyView();
});
stage.addEventListener("pointerup", (e) => { if (panning) { panning = null; try { stage.releasePointerCapture(e.pointerId); } catch {} } });
window.addEventListener("resize", () => { if (GROUPS.length) fitView(); });

// ============================================================================
//  FRAME LOADING + DRAW
// ============================================================================
const imgRGB = $("imgRGB"), imgIR = $("imgIR"), loadingEl = $("loading");
let curURLs = [];
let loadToken = 0;

// CSS matrix3d (column-major 4x4) equivalent of a 2D homography H (3x3, IR->RGB).
// The IR <img> is placed at natural size at (0,0); matrix3d maps its pixels into
// RGB-pixel space, giving a true perspective warp.
function matrix3dFromH(H) {
  const a = H[0][0], b = H[0][1], c = H[0][2];
  const d = H[1][0], e = H[1][1], f = H[1][2];
  const g = H[2][0], h = H[2][1], i = H[2][2];
  return `matrix3d(${a},${d},0,${g}, ${b},${e},0,${h}, 0,0,1,0, ${c},${f},0,${i})`;
}

function loadImage(file) {
  return new Promise((res, rej) => {
    const url = URL.createObjectURL(file); curURLs.push(url);
    const im = new Image();
    im.onload = () => res({ im, url });
    im.onerror = () => rej(new Error("could not read " + (file.webkitRelativePath || file.name)));
    im.src = url;
  });
}

async function gotoFrame(i) {
  const g = GROUPS[gi]; if (!g) return;
  fi = clamp(i, 0, g.frames.length - 1);
  const fr = g.frames[fi];
  const myToken = ++loadToken;
  loadingEl.classList.add("show");
  let rgb, ir;
  try { [rgb, ir] = await Promise.all([loadImage(fr.rgbFile), loadImage(fr.irFile)]); }
  catch (e) { if (myToken === loadToken) { showError(e.message); loadingEl.classList.remove("show"); } return; }
  if (myToken !== loadToken) { URL.revokeObjectURL(rgb.url); URL.revokeObjectURL(ir.url); return; }

  // Swap in the new frame, then revoke everything but the two URLs now on screen.
  imgRGB.src = rgb.url; imgIR.src = ir.url;
  const keep = new Set([rgb.url, ir.url]);
  for (const u of curURLs) if (!keep.has(u)) URL.revokeObjectURL(u);
  curURLs = [rgb.url, ir.url];

  // Scene is RGB-pixel sized; IR warped by its subset's matrix.
  const [rw, rh] = g.rgbSize;
  scene.style.width = rw + "px"; scene.style.height = rh + "px";
  imgRGB.style.width = rw + "px"; imgRGB.style.height = rh + "px";
  imgIR.style.width = g.irSize[0] + "px"; imgIR.style.height = g.irSize[1] + "px";
  imgIR.style.transform = matrix3dFromH(fr.subset.matrix);

  loadingEl.classList.remove("show");
  updateFrameUI(fr);
}

function updateFrameUI(fr) {
  const g = GROUPS[gi];
  $("frameLabel").textContent = `${shortLabel(g.key)} · frame ${fi + 1}/${g.frames.length} · ${fr.name}`;
  $("badge").textContent = fr.name;
  $("pathLbl").textContent = fr.rgbFile.webkitRelativePath || fr.name;
  $("pathLbl").title = $("pathLbl").textContent;
  $("seek").max = String(g.frames.length - 1);
  $("seek").value = String(fi);
  renderInfoBar(fr.subset);
}

// ---- info bar: subset pills + stats + collapsible matrix --------------------
let matShown = false;
function renderInfoBar(active) {
  const g = GROUPS[gi];
  const pills = $("subsetPills"); pills.innerHTML = "";
  g.subsets.forEach((s, k) => {
    const p = document.createElement("span");
    p.className = "sp" + (s === active ? " active" : "");
    p.textContent = String(k + 1);
    p.title = `${s.label || (s.frame_start + "–" + s.frame_end)} · jump to first present frame`;
    p.addEventListener("click", () => jumpToSubset(s));
    pills.appendChild(p);
  });
  $("subsetRange").textContent = active.label || `${active.frame_start}–${active.frame_end}`;
  $("subsetModel").textContent = active.model || "—";
  $("subsetN").textContent = active.n_pairs != null ? active.n_pairs : "—";
  $("subsetRmse").textContent = active.rmse_px != null ? (+active.rmse_px).toFixed(2) + " px" : "—";
  if (matShown) showMat(active);
}
function jumpToSubset(s) {
  const g = GROUPS[gi];
  const idx = g.frames.findIndex(fr => fr.subset === s);
  if (idx >= 0) gotoFrame(idx);
}
function showMat(s) {
  let pre = document.getElementById("matPre");
  if (!pre) {
    pre = document.createElement("pre"); pre.id = "matPre"; pre.className = "mat";
    pre.style.flexBasis = "100%";
    $("infoBar").appendChild(pre);
  }
  const rows = s.matrix.map(r => "[ " + r.map(v => (+v).toExponential(4).padStart(12)).join(", ") + " ]");
  pre.textContent = "IR → RGB (3×3):\n" + rows.join("\n");
}
$("btnMat").addEventListener("click", () => {
  matShown = !matShown;
  $("btnMat").textContent = matShown ? "H ▴" : "H ▾";
  const g = GROUPS[gi];
  if (matShown) showMat(g.frames[fi].subset);
  else { const pre = document.getElementById("matPre"); if (pre) pre.remove(); }
});

// ============================================================================
//  FOLDER LOAD WIRING
// ============================================================================
async function selectGroup(index) {
  gi = clamp(index, 0, GROUPS.length - 1);
  setControlsEnabled(true);
  $("infoBar").classList.add("show");
  // Fit AFTER the frame lands: gotoFrame fills the info bar, which can wrap to a
  // second line and shrink the stage. Fitting first would use a stale height.
  await gotoFrame(0);
  fitView();
}

$("dirInput").addEventListener("change", async (e) => {
  clearError();
  const files = e.target.files;
  if (!files || !files.length) return;
  loadingEl.classList.add("show");
  GROUPS = await discoverGroups(files);
  loadingEl.classList.remove("show");
  if (!GROUPS.length) {
    showError("No viewable folders found.\nPick the dataset root, or a Pair-ID folder that contains rgb/, ir/ and\nhomography/homography.json (with at least one subset present in the shipped frames).");
    return;
  }
  const sel = $("groupSel");
  sel.innerHTML = "";
  GROUPS.forEach((g, i) => {
    const o = document.createElement("option");
    o.value = String(i);
    o.textContent = `${shortLabel(g.key)}  (${g.frames.length})`;
    sel.appendChild(o);
  });
  sel.style.display = GROUPS.length > 1 ? "" : "none";
  sel.value = "0";
  $("empty").style.display = "none";
  selectGroup(0);
});
$("groupSel").addEventListener("change", (e) => selectGroup(+e.target.value));

function setControlsEnabled(on) {
  ["btnFirst","btnPrev","btnNext","btnLast","btnToggleIR","btnResetView"].forEach(id => $(id).disabled = !on);
  $("seek").disabled = !on; $("irOpacity").disabled = !on;
}

// ---- transport --------------------------------------------------------------
$("btnFirst").addEventListener("click", () => gotoFrame(0));
$("btnPrev").addEventListener("click",  () => gotoFrame(fi - 1));
$("btnNext").addEventListener("click",  () => gotoFrame(fi + 1));
$("btnLast").addEventListener("click",  () => { const g = GROUPS[gi]; if (g) gotoFrame(g.frames.length - 1); });
$("seek").addEventListener("input", (e) => gotoFrame(+e.target.value));
$("btnResetView").addEventListener("click", fitView);

// ---- IR opacity / hide ------------------------------------------------------
const irOpacity = $("irOpacity"), irOpacityValue = $("irOpacityValue"), btnToggleIR = $("btnToggleIR");
let irHidden = false;
function applyOpacity() {
  scene.style.setProperty("--ir-opacity", (irOpacity.value / 100).toString());
  irOpacityValue.textContent = irOpacity.value + "%";
}
irOpacity.addEventListener("input", applyOpacity);
function toggleIR() {
  irHidden = !irHidden;
  imgIR.classList.toggle("hidden", irHidden);
  btnToggleIR.textContent = irHidden ? "Show IR" : "Hide IR";
}
btnToggleIR.addEventListener("click", toggleIR);
applyOpacity();

// ---- keyboard ---------------------------------------------------------------
window.addEventListener("keydown", (e) => {
  if (!GROUPS.length) return;
  if (e.target.tagName === "INPUT" || e.target.tagName === "SELECT") return;
  switch (e.key) {
    case "ArrowLeft":  gotoFrame(fi - 1); break;
    case "ArrowRight": gotoFrame(fi + 1); break;
    case "Home":       gotoFrame(0); break;
    case "End":        gotoFrame(GROUPS[gi].frames.length - 1); break;
    case "i": case "I": toggleIR(); break;
    case "0":          fitView(); break;
    default: return;
  }
  e.preventDefault();
});
</script>
</body>
</html>