SharpMeow commited on
Commit
f6dcaa7
·
1 Parent(s): 7a534f8

Data-driven scroll framework and Open your own

Browse files

- scrolls/index.json registry and per-scroll manifests (windings with ranges, ink layers with sources and resolutions, credits, data terms); PHerc. 139 migrated with no visible change
- scroll picker (hidden with one scroll), per-scroll and per-winding lazy loading
- lib/manifest.js validator shared by the page and tools/validate_scroll.mjs; docs/ADDING_A_SCROLL.md; tools/precompute_template.py
- Open your own: files, folders, zips or a URL, read in the browser only (nothing uploaded), OBJ/PLY with UVs, PNG/JPG/TIFF layers, size limits, clear errors, kept in IndexedDB and labelled local; downloadable synthetic example package
- atlases as WebP with JPG fallback (about 2.1 MB smaller)
- rename layers: Published ink (2.4 µm) and Our ink model (9 µm)

.gitattributes CHANGED
@@ -84,3 +84,4 @@ data/hi/w057.jpg filter=lfs diff=lfs merge=lfs -text
84
  data/hi/w058.jpg filter=lfs diff=lfs merge=lfs -text
85
  data/hi/w059.jpg filter=lfs diff=lfs merge=lfs -text
86
  og.jpg filter=lfs diff=lfs merge=lfs -text
 
 
84
  data/hi/w058.jpg filter=lfs diff=lfs merge=lfs -text
85
  data/hi/w059.jpg filter=lfs diff=lfs merge=lfs -text
86
  og.jpg filter=lfs diff=lfs merge=lfs -text
87
+ *.webp filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -25,21 +25,31 @@ PHerc. 139 is a papyrus roll carbonized when Vesuvius buried Herculaneum in 79 C
25
 
26
  - **Shapes**: the 9.362 µm tifxyz meshes of the 37 traced windings (`w023` to `w059`), decimated to 579,450 vertices.
27
  - **X-ray layer**: the CT intensity on each surface, from the public 9.362 µm surface volumes.
28
- - **Ink layer (amber)**: the Vesuvius Challenge's public ink detection on the 2.4 µm scan. In 3D it is drawn through a local-contrast filter so letter-sized strokes stand out. The close-up view shows the published preview without filtering, downscaled to 2,400 px on its long side and re-saved as JPEG.
29
- - **ZeroGPU layer (cyan)**: windings `w046` to `w051`, inked by running the public [`scrollprize/ink_9um`](https://huggingface.co/scrollprize/ink_9um) model (seed 42, step 75000) on the 9.362 µm scan. It used all 8 of a free account's daily ZeroGPU runs: 37,141 patches in 57 s of measured GPU time (ZeroGPU charged about 66 of the 300 daily GPU-seconds). The 9.362 µm scan is about four times coarser than the 2.4 µm one, so this layer is noisier. `w047` and `w050` ran with patch overlap 0.5; the other four ran with 0.25 or 0.2, and their 128 px patch grid shows as faint square tiles. Per-run records (checkpoint sha256, villa commit, requested and measured GPU seconds) are in `data/gpu/receipts/`; `data/gpu.json` is the summary the page reads.
30
 
31
  Unrolling lays the windings end to end, outermost first. Each traced winding runs a little past one full turn, so roughly a tenth of the 2.8 m strip repeats surface from its neighbour.
32
 
 
 
 
 
 
 
 
 
 
 
33
  ## Rebuilding the data
34
 
35
  From the Space's root, with Python 3, `numpy`, `scipy`, `tifffile`, `Pillow` and `curl`:
36
 
37
  1. `python tools/fetch.py` lists the public bucket and downloads the meshes and ink previews into `raw/` (about 110 MB).
38
  2. `python tools/build.py` writes `data/scroll.bin`, `data/scroll.json`, the atlases and `data/hi/`. It reads the X-ray layer straight from the bucket.
39
- 3. `python tools/gpu_layer.py` rebuilds the ZeroGPU layer. It needs the ink_9um output TIFFs in `gpu/wNNN/` (about 25 MB each, not shipped). Regenerate them with the model card's inference command on the surface-volume URLs in `data/gpu/receipts/`.
40
 
41
  ## Licence and credits
42
 
43
  Data: Giorgio Angelotti, Stephen Parsons, Sean Johnson, Elian Rafael Dal Prà, Johannes Rudolph, Paul Tafforeau, Alessandro Mirone, Paul Henderson, Hendrik Schilling, Forrest McDonald, David Josey, Youssef Nader, C. Seth Parker, W. Brent Seales. *Vesuvius Challenge - CT Scans of Herculaneum Papyri.* Vesuvius Challenge. [Data browser for PHerc. 139](https://scrollprize.org/data_browser/PHerc0139). PHerc. 139 is held by the Biblioteca Nazionale di Napoli.
44
 
45
- `data/` and `og.jpg` are derived from that data and are licensed [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). The code (`index.html`, `style.css`, `app.js` and `tools/`) is MIT, see `LICENSE`. The page uses [three.js](https://threejs.org) 0.160 from jsDelivr.
 
25
 
26
  - **Shapes**: the 9.362 µm tifxyz meshes of the 37 traced windings (`w023` to `w059`), decimated to 579,450 vertices.
27
  - **X-ray layer**: the CT intensity on each surface, from the public 9.362 µm surface volumes.
28
+ - **Published ink (2.4 µm), amber**: the Vesuvius Challenge's public ink detection on the 2.4 µm scan. In 3D it is drawn through a local-contrast filter so letter-sized strokes stand out. The close-up view shows the published preview without filtering, downscaled to 2,400 px on its long side and re-saved as JPEG.
29
+ - **Our ink model (9 µm), cyan**: windings `w046` to `w051`, inked by running the public [`scrollprize/ink_9um`](https://huggingface.co/scrollprize/ink_9um) model (seed 42, step 75000) on the 9.362 µm scan. It used all 8 of a free account's daily ZeroGPU runs: 37,141 patches in 57 s of measured GPU time (ZeroGPU charged about 66 of the 300 daily GPU-seconds). The 9.362 µm scan is about four times coarser than the 2.4 µm one, so this layer is noisier. `w047` and `w050` ran with patch overlap 0.5; the other four ran with 0.25 or 0.2, and their 128 px patch grid shows as faint square tiles. Per-run records (checkpoint sha256, villa commit, requested and measured GPU seconds) are in `data/gpu/receipts/`; `data/gpu.json` is the summary the page reads.
30
 
31
  Unrolling lays the windings end to end, outermost first. Each traced winding runs a little past one full turn, so roughly a tenth of the 2.8 m strip repeats surface from its neighbour.
32
 
33
+ ## Scrolls, windings and layers
34
+
35
+ The page is data driven. `scrolls/index.json` lists the scrolls and each one has a manifest (`scrolls/PHerc0139/manifest.json`) naming its windings, meshes, ink layers, sources, resolutions, credits and data terms. With more than one scroll a picker appears. `node tools/validate_scroll.mjs` checks the registry and every manifest with the same validator the page uses. See [docs/ADDING_A_SCROLL.md](docs/ADDING_A_SCROLL.md) to add one; `tools/precompute_template.py` is a starting point for building a package.
36
+
37
+ The atlases ship as WebP (`data/atlas_*.webp`), with the JPGs kept as a fallback.
38
+
39
+ ## Open your own
40
+
41
+ Press **+** to unroll your own scroll: a zip, a folder, or a manifest with OBJ or PLY meshes (with UVs) and PNG, JPG or TIFF layers, or the URL of one (the server must allow CORS). Everything is read in your browser and kept in its storage; nothing is uploaded. The sheet has a downloadable synthetic example package. Details and limits are in [docs/ADDING_A_SCROLL.md](docs/ADDING_A_SCROLL.md#open-your-own).
42
+
43
  ## Rebuilding the data
44
 
45
  From the Space's root, with Python 3, `numpy`, `scipy`, `tifffile`, `Pillow` and `curl`:
46
 
47
  1. `python tools/fetch.py` lists the public bucket and downloads the meshes and ink previews into `raw/` (about 110 MB).
48
  2. `python tools/build.py` writes `data/scroll.bin`, `data/scroll.json`, the atlases and `data/hi/`. It reads the X-ray layer straight from the bucket.
49
+ 3. `python tools/gpu_layer.py` rebuilds the Our ink model (9 µm) layer. It needs the ink_9um output TIFFs in `gpu/wNNN/` (about 25 MB each, not shipped). Regenerate them with the model card's inference command on the surface-volume URLs in `data/gpu/receipts/`.
50
 
51
  ## Licence and credits
52
 
53
  Data: Giorgio Angelotti, Stephen Parsons, Sean Johnson, Elian Rafael Dal Prà, Johannes Rudolph, Paul Tafforeau, Alessandro Mirone, Paul Henderson, Hendrik Schilling, Forrest McDonald, David Josey, Youssef Nader, C. Seth Parker, W. Brent Seales. *Vesuvius Challenge - CT Scans of Herculaneum Papyri.* Vesuvius Challenge. [Data browser for PHerc. 139](https://scrollprize.org/data_browser/PHerc0139). PHerc. 139 is held by the Biblioteca Nazionale di Napoli.
54
 
55
+ `data/` and `og.jpg` are derived from that data and are licensed [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). The code (`index.html`, `style.css`, `app.js`, `tear.js`, `polish.js`, `lib/`, `scrolls/*.json` and `tools/`) is MIT, see `LICENSE`. The page uses [three.js](https://threejs.org) 0.160 from jsDelivr.
app.js CHANGED
@@ -5,6 +5,9 @@ import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
5
  import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
6
  import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
7
  import { createTear } from './tear.js';
 
 
 
8
 
9
  const $ = (id) => document.getElementById(id);
10
  const params = new URLSearchParams(location.hash.slice(1));
@@ -62,20 +65,154 @@ async function loadTexture(url, guess) {
62
  return tex;
63
  }
64
 
65
- const M = await (await fetch('data/scroll.json')).json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  let GPU = null;
67
- try {
68
- const r = await fetch('data/gpu.json');
69
- if (r.ok) GPU = await r.json();
70
- } catch (e) { /* no GPU layer yet */ }
71
-
72
- const [binBuf, texInk, texCT] = await Promise.all([
73
- fetchBytes('data/scroll.bin', 3.5e6),
74
- loadTexture('data/atlas_ink.jpg', 2.5e6),
75
- loadTexture('data/atlas_ct.jpg', 4.3e6),
76
- ]);
77
- // the six small ZeroGPU textures load after the first frame; until then those sheets show the published ink
78
  const gpuTex = {};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  const blank = new THREE.DataTexture(new Uint8Array([0, 0, 0, 255]), 1, 1);
80
  blank.needsUpdate = true;
81
 
@@ -111,7 +248,7 @@ composer.addPass(new OutputPass());
111
 
112
  const VOX = M.voxelMM;
113
  const CELL = M.cellMM;
114
- const all = new Int16Array(binBuf);
115
  const shared = {
116
  uInk: { value: texInk }, uCT: { value: texCT },
117
  uRot: { value: 0 }, uRoll: { value: new THREE.Vector3() },
@@ -210,14 +347,24 @@ void main() {
210
  }`;
211
 
212
  // windings in peel order: outermost first
213
- const wins = [...M.windings].sort((a, b) => (a.id < b.id ? 1 : -1));
 
214
  let S = 0;
215
- const gpuIds = new Set(GPU ? Object.keys(GPU.windings) : []);
216
  const meshes = [];
217
  const decim = MOBILE ? 2 : 1;
218
  let Rmax = 0;
219
 
220
- for (const [j, w] of wins.entries()) {
 
 
 
 
 
 
 
 
 
221
  const R = w.rows, C = w.cols;
222
  const a = all.subarray(w.offset / 2, (w.offset + w.bytes) / 2);
223
  const pos = new Float32Array(R * C * 3);
@@ -296,6 +443,10 @@ for (const [j, w] of wins.entries()) {
296
  geo.setIndex(idx);
297
  geo.computeVertexNormals();
298
  geo.computeBoundingSphere();
 
 
 
 
299
  Rmax = Math.max(Rmax, w.radiusMM);
300
 
301
  const own = {
@@ -410,6 +561,10 @@ for (const m of meshes) {
410
  if (gpuIds.has(m.userData.w.id)) i.className = 'gpu';
411
  ticks.appendChild(i);
412
  }
 
 
 
 
413
  let playing = false;
414
  let target = t;
415
  // the one place the unroll position changes: slider, scrubber drag, keys, buttons and code all go through here
@@ -440,7 +595,7 @@ scrub.addEventListener('pointercancel', () => { scrubbing = false; setTarget(tar
440
  addEventListener('keydown', (e) => {
441
  if (e.code === 'Escape') { closeSheets(); return; }
442
  if (e.target.closest('input,textarea,select')) return;
443
- if (!$('focus').hidden || !$('about').hidden) return;
444
  if (e.code === 'Space') {
445
  if (e.target.closest('button,a,[role=tab],[role=button]')) return; // let focused controls act natively
446
  e.preventDefault(); introDone(); autoplayAt = 0; setPlaying(!playing);
@@ -456,17 +611,24 @@ scrubIn.addEventListener('change', saveHash);
456
  scrubIn.addEventListener('keydown', (e) => { if (e.code.startsWith('Arrow')) e.stopPropagation(); });
457
 
458
  let layer = 'ink';
459
- const LAYER_HINTS = {
460
- xray: 'Raw X-ray CT brightness, no ink detection.',
461
- ink: 'Published ink: Vesuvius Challenge detection, 2.4 µm scan, all windings.',
462
- gpu: 'Our GPU ink (lower res): open ink_9um model on the 9.4 µm scan, about 4x coarser, six windings. Blurrier, with patch seams; a reproducible baseline to check against the published layer.',
463
- };
 
 
 
 
 
 
464
  let layerT = 1, gpuT = 0;
465
  function setLayer(l) {
466
  layer = l;
467
  for (const b of document.querySelectorAll('.chip[data-layer]')) b.classList.toggle('on', b.dataset.layer === l);
468
  const hint = $('layerHint');
469
  if (hint) hint.textContent = LAYER_HINTS[l] || '';
 
470
  saveHash();
471
  }
472
  for (const b of document.querySelectorAll('.chip[data-layer]')) {
@@ -477,22 +639,30 @@ for (const b of document.querySelectorAll('.chip[data-layer]')) {
477
  if (b.dataset.layer === 'gpu' && target < bandEnd + 0.01) { autoplayAt = 0; setPlaying(false); setTarget(bandEnd + 0.015, 'layer'); }
478
  };
479
  }
480
- if (GPU) {
 
 
 
481
  $('gpuChip').hidden = false;
482
  const band = document.createElement('div');
483
  band.className = 'band';
484
  band.style.left = `${bandStart * 100}%`;
485
  band.style.width = `${(bandEnd - bandStart) * 100}%`;
486
- band.title = 'Windings inked live on ZeroGPU';
487
  $('scrub').appendChild(band);
488
- $('rGpuRow').hidden = false;
489
- const a = $('aboutGpu');
490
- a.hidden = false;
491
- a.innerHTML = GPU.about;
492
- }
 
 
 
 
 
493
 
494
  function saveHash() {
495
- const h = new URLSearchParams({ t: target.toFixed(3), l: layer });
496
  history.replaceState(null, '', `#${h}`);
497
  }
498
 
@@ -515,7 +685,7 @@ function overview() {
515
  const pos = new THREE.Vector3(-150, portrait ? 150 : 110, stripZ + (portrait ? 520 : 360));
516
  return [pos, tgt];
517
  }
518
- let intro = !params.has('t') && !REDUCED && !SHOT;
519
  if (!intro) shared.uSweep.value = -999;
520
  // the intro opens looking straight down the roll's axis, where the windings read as a spiral
521
  const TOP_TARGET = new THREE.Vector3(innerWidth > innerHeight ? -30 : 0, -2, 0);
@@ -537,7 +707,8 @@ function framing(st) {
537
  }
538
  if (params.has('t')) {
539
  t = tShown = Math.min(1, Math.max(0, +params.get('t') || 0)); setTarget(t, 'hash');
540
- if (['xray', 'ink', 'gpu'].includes(params.get('l'))) setLayer(params.get('l') === 'gpu' && !GPU ? 'ink' : params.get('l'));
 
541
  shared.uSweep.value = -999;
542
  }
543
  {
@@ -595,7 +766,7 @@ canvas.addEventListener('pointermove', (e) => {
595
  tip.hidden = false;
596
  tip.style.left = `${e.clientX}px`;
597
  tip.style.top = `${e.clientY}px`;
598
- tip.innerHTML = `${w.id.toUpperCase()} · r ${w.radiusMM.toFixed(1)} mm · ${w.areaCM2.toFixed(0)} cm²${gpuIds.has(w.id) ? ' · <span style="color:var(--gpu)">ZEROGPU</span>' : ''} <span class="dim">· click to read</span>`;
599
  canvas.style.cursor = 'pointer';
600
  } else {
601
  tip.hidden = true;
@@ -631,7 +802,7 @@ function vApply() {
631
  }
632
  $('fSwipe').addEventListener('input', vApply);
633
  $('fSwipe').addEventListener('pointerdown', (e) => e.stopPropagation());
634
- img.addEventListener('error', () => { if (/\.jpg/.test(img.getAttribute('src') || '')) $('fErr').hidden = false; });
635
  img.addEventListener('load', () => { $('fErr').hidden = true; });
636
  function vFit() {
637
  const r = viewer.getBoundingClientRect();
@@ -680,50 +851,87 @@ function openFocus(m) {
680
  setPlaying(false);
681
  const w = m.userData.w;
682
  $('fTitle').textContent = w.id;
 
 
 
 
683
  $('fKicker').textContent = `TRACED WINDING ${wins.length - m.userData.j} OF ${wins.length}, INNERMOST FIRST · ${w.seg}`;
684
  const seg = $('fSeg');
685
  seg.innerHTML = '';
686
- const g = GPU && GPU.windings[w.id];
687
- const views = [['vc', 'Published ink · 2.4 µm', w.hi]];
688
- if (g) views.push(['gpu', 'Our GPU ink · 9.4 µm (lower res)', g.hi]);
689
- if (g) views.push(['cmp', 'Compare (swipe)', w.hi]);
 
 
 
 
690
  focusW = w;
691
  $('fErr').hidden = true;
692
  const setCmp = (on) => {
693
  $('fImg2').hidden = $('fSwipeWrap').hidden = $('fSwipeLine').hidden = !on;
694
- if (on) { $('fImg2').src = `data/${g.hi}`; $('fImg2').onload = vApply; }
695
  };
696
  setCmp(false);
697
  for (const [k, label, src] of views) {
698
  const b = document.createElement('button');
699
  b.className = `chip${k === 'gpu' ? ' gpu' : ''}`;
700
- b.textContent = label;
701
  b.onclick = () => {
702
  for (const x of seg.children) x.classList.toggle('on', x === b);
703
  img.dataset.keep = '1';
704
- img.src = `data/${src}`;
705
  setCmp(k === 'cmp');
706
- $('fMeta').innerHTML = k === 'gpu' ? g.meta : k === 'cmp' ? 'Left of the line: Vesuvius Challenge published ink, 2.4 µm scan. Right: our GPU run of ink_9um, 9.4 µm scan. Drag the swipe control to compare.' : vcMeta(w);
707
  };
708
  seg.appendChild(b);
709
  }
710
  const start = g && layer === 'gpu' ? 1 : 0;
711
  seg.children[start].classList.add('on');
712
  img.dataset.keep = '';
713
- img.src = `data/${views[start][2]}`;
714
- $('fMeta').innerHTML = start ? g.meta : vcMeta(w);
715
  $('focus').hidden = false;
716
  $('fClose').focus();
717
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718
  function vcMeta(w) {
 
 
719
  return `${w.widthMM.toFixed(0)} × ${w.heightMM.toFixed(0)} mm · ${w.areaCM2.toFixed(1)} cm² · radius ${w.radiusMM.toFixed(1)} mm · ` +
720
- `ink: Vesuvius Challenge public detection on the 2.399 µm scan · drag to pan, scroll or pinch to zoom, double-click to fit`;
721
  }
722
  let lastOpener = null;
723
  function closeSheets() {
724
- const wasOpen = !$('focus').hidden || !$('about').hidden;
725
  $('focus').hidden = true;
726
  $('about').hidden = true;
 
727
  if (wasOpen && lastOpener) lastOpener.focus();
728
  }
729
  $('fClose').onclick = closeSheets;
@@ -762,27 +970,28 @@ function composeShot() {
762
  const x = 28 * s;
763
  g.fillStyle = 'rgba(141,133,122,1)';
764
  g.font = `${Math.round(11 * s)}px "JetBrains Mono", monospace`;
765
- g.fillText('PHERC. 0139 / HERCULANEUM / BURIED 79 CE', x, 40 * s);
 
766
  const fs = Math.round(Math.min(64, Math.max(34, innerWidth * 0.046)) * s);
767
  g.font = `${fs}px "Instrument Serif", Georgia, serif`;
768
  g.fillStyle = 'rgba(236,230,219,1)';
769
- g.fillText('Unroll a scroll nobody', x, 40 * s + fs * 1.05);
770
- const l2 = 'has opened in ';
771
  g.fillText(l2, x, 40 * s + fs * 2.03);
772
  const w2 = g.measureText(l2).width;
773
  g.font = `italic ${fs}px "Instrument Serif", Georgia, serif`;
774
  g.fillStyle = '#ffb347';
775
- g.fillText('1,947 years.', x + w2, 40 * s + fs * 2.03);
776
  g.fillStyle = 'rgba(141,133,122,1)';
777
  g.font = `${Math.round(11 * s)}px "JetBrains Mono", monospace`;
778
- g.fillText(`${(tShown * L / 1000).toFixed(2)} m of traced strip unrolled · data: Vesuvius Challenge, CC BY-NC 4.0 (creativecommons.org/licenses/by-nc/4.0)`, x, c.height - 26 * s);
779
  return c;
780
  }
781
  $('btnShot').onclick = () => {
782
  composeShot().toBlob((b) => {
783
  const a = document.createElement('a');
784
  a.href = URL.createObjectURL(b);
785
- a.download = `pherc0139-unroll-${Math.round(tShown * 100)}.png`;
786
  a.click();
787
  setTimeout(() => URL.revokeObjectURL(a.href), 4000);
788
  }, 'image/png');
@@ -889,7 +1098,7 @@ function frame() {
889
  $('rRad').textContent = `${st.radius.toFixed(1)} mm`;
890
  $('rLen').textContent = `${(st.s / 1000).toFixed(2)} / ${(L / 1000).toFixed(2)} m`;
891
  if (GPU) {
892
- const g = GPU.windings[st.cur.userData.w.id];
893
  $('rGpu').textContent = g ? `${g.patches.toLocaleString()} patches · ${g.gpuSeconds} s` : '·';
894
  $('rGpuRow').classList.toggle('live', !!g);
895
  }
@@ -903,15 +1112,8 @@ function frame() {
903
  }
904
  requestAnimationFrame(frame);
905
 
906
- if (GPU) {
907
- for (const [id, g] of Object.entries(GPU.windings)) {
908
- loadTexture(g.tex, 1.5e5).then((tex) => {
909
- gpuTex[id] = tex;
910
- const m = meshes.find((x) => x.userData.w.id === id);
911
- if (m) m.userData.own.uGpuTex.value = tex;
912
- }).catch(() => { /* keep the blank texture; the published layer still shows */ });
913
- }
914
- }
915
 
916
  // camera hooks for the keyboard shortcuts in polish.js
917
  window.unrollView = {
 
5
  import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
6
  import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
7
  import { createTear } from './tear.js';
8
+ import { loadRegistry, listLocal, getLocal, localKey, remoteSource, fileSource, findManifest, buildMeshScroll, decodeImage } from './lib/scrolls.js';
9
+ import { validateManifest, peelOrder, layerWindings, layerFile, roleOf, fill, REGISTRY_LIMITS, LOCAL_LIMITS } from './lib/manifest.js';
10
+ import { setupOpenOwn } from './lib/openown.js';
11
 
12
  const $ = (id) => document.getElementById(id);
13
  const params = new URLSearchParams(location.hash.slice(1));
 
65
  return tex;
66
  }
67
 
68
+ function texFrom(img) {
69
+ const tex = new THREE.Texture(img);
70
+ tex.flipY = false;
71
+ tex.generateMipmaps = true;
72
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
73
+ tex.magFilter = THREE.LinearFilter;
74
+ tex.colorSpace = THREE.NoColorSpace;
75
+ tex.needsUpdate = true;
76
+ return tex;
77
+ }
78
+ const um = (l) => (l.resolutionUM ? `${l.resolutionUM} µm` : '');
79
+ // keep µ lower case inside upper-case styled text (text-transform would turn it into a capital Mu, which reads as M)
80
+ const muHTML = (x) => esc(x).replace(/µ/g, '<span class="mu">µ</span>');
81
+ const esc = (x) => String(x ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
82
+ // a load failure with a reason the visitor can act on; the error state in index.html shows it
83
+ function loadFail(why, back) {
84
+ window.__unrollWhy = why;
85
+ if (back) {
86
+ const b = document.createElement('button');
87
+ b.className = 'chip'; b.textContent = 'Back to the default scroll';
88
+ b.onclick = () => { location.hash = ''; location.reload(); };
89
+ $('loadErr').appendChild(b);
90
+ }
91
+ throw new Error(why);
92
+ }
93
+
94
+ // ---------------------------------------------------------------- which scroll: the registry, or one opened in this browser
95
+
96
+ const REG = await loadRegistry();
97
+ const LOCALS = await listLocal();
98
+ const DEFAULT_ID = REG.default || REG.scrolls[0].id;
99
+ let SCROLL_KEY = params.get('s') || DEFAULT_ID;
100
+ let MAN, SRC, TRUSTED = true;
101
+ if (localKey(SCROLL_KEY)) {
102
+ const rec = await getLocal(SCROLL_KEY).catch(() => null);
103
+ if (!rec) loadFail('This scroll was opened in another browser, or removed from this one. Scrolls you open stay on the device you opened them on.', true);
104
+ try {
105
+ const f = await findManifest(rec.files);
106
+ MAN = f.manifest; SRC = fileSource(rec.files, f.path); TRUSTED = false;
107
+ } catch (e) { loadFail(e.message, true); }
108
+ } else {
109
+ const entry = REG.scrolls.find((x) => x.id === SCROLL_KEY) || REG.scrolls.find((x) => x.id === DEFAULT_ID);
110
+ SCROLL_KEY = entry.id;
111
+ MAN = await (await fetch(entry.manifest)).json();
112
+ SRC = remoteSource(entry.manifest, MAN, fetchBytes);
113
+ }
114
+ {
115
+ const v = validateManifest(MAN, { trusted: TRUSTED, limits: TRUSTED ? REGISTRY_LIMITS : LOCAL_LIMITS });
116
+ if (!v.ok) loadFail(`The scroll's manifest has problems: ${v.errors.join(' ')}`, !TRUSTED);
117
+ }
118
+ const ORDER = peelOrder(MAN);
119
+ const IDS = ORDER.map((w) => w.id);
120
+ const L_CT = roleOf(MAN, 'ct'), L_INK = roleOf(MAN, 'ink'), L_OV = roleOf(MAN, 'overlay');
121
+ const OV_IDS = new Set(L_OV ? layerWindings(L_OV, IDS) : []);
122
+ const D = (TRUSTED && MAN.display) || null;
123
+ $('loader').querySelector('.mono').textContent = D?.loaderKicker || `${MAN.name.toUpperCase()} · LOCAL FILE`;
124
+
125
+ // ---------------------------------------------------------------- page text, credits, scroll picker, "Open your own"
126
+
127
+ {
128
+ // registry manifests may carry HTML; anything opened by a visitor is shown as plain text only
129
+ const cr = MAN.credits || {}, dt = MAN.dataTerms || {};
130
+ const link = (t, u) => (u ? `<a href="${esc(u)}" target="_blank" rel="noopener">${esc(t)}</a>` : esc(t));
131
+ if (D) {
132
+ if (D.pageTitle) document.title = D.pageTitle;
133
+ if (D.kicker) document.querySelector('.hud.tl .kicker').innerHTML = D.kicker;
134
+ if (D.titleHtml) document.querySelector('.hud.tl h1').innerHTML = D.titleHtml;
135
+ if (D.lede) document.querySelector('.hud.tl .lede').innerHTML = D.lede;
136
+ if (D.aboutHtml) document.querySelector('#about .about-body').innerHTML = D.aboutHtml.join('\n');
137
+ } else {
138
+ document.title = `Unroll · ${MAN.name}`;
139
+ document.querySelector('.hud.tl .kicker').textContent = `${MAN.name.toUpperCase()} / ${TRUSTED ? 'SCROLL' : 'LOCAL, NOT UPLOADED'}`;
140
+ document.querySelector('.hud.tl h1').textContent = MAN.name;
141
+ document.querySelector('.hud.tl .lede').textContent = `${MAN.description ? `${MAN.description} ` : ''}${TRUSTED ? '' : 'Opened from your own files, in this browser only: nothing was uploaded. '}Drag to look around. Scrub to unroll.`;
142
+ const ab = document.querySelector('#about .about-body');
143
+ ab.innerHTML = '';
144
+ const P = (t, cls) => { const e = document.createElement('p'); if (cls) e.className = cls; e.textContent = t; ab.appendChild(e); return e; };
145
+ if (MAN.description) P(MAN.description);
146
+ if (!TRUSTED) P('You opened this scroll from your own files. It was read and drawn by this page in your browser. Nothing was uploaded to any server; the files are kept in this browser until you remove them under Open your own.');
147
+ for (const l of MAN.layers) P(`${l.label}: ${[l.source, um(l), l.notes].filter(Boolean).join(', ')}`);
148
+ if (cr.text || cr.citation) P(`Credits: ${[cr.text, cr.citation].filter(Boolean).join('. ')}${cr.url ? ` (${cr.url})` : ''}`, 'mono dim small');
149
+ if (dt.license || dt.notes) P(`Data terms: ${[dt.license, dt.notes].filter(Boolean).join('. ')}${dt.url ? ` (${dt.url})` : ''}`, 'mono dim small');
150
+ const ag = document.createElement('p'); ag.id = 'aboutGpu'; ag.hidden = true; ab.appendChild(ag);
151
+ }
152
+ const credit = document.querySelector('.credit');
153
+ credit.innerHTML = `Data ${link(cr.text || MAN.name, cr.url)}${dt.license ? ` · ${link(dt.license, dt.url)}` : ''}${TRUSTED ? '' : ' · <span class="local-tag">local, not uploaded</span>'}`;
154
+
155
+ // the scroll picker: hidden while there is only one scroll to choose from
156
+ const sel = $('scrollSel');
157
+ const opts = REG.scrolls.map((x) => [x.id, x.name || x.id]).concat(LOCALS.map((x) => [x.key, `${x.name} (local)`]));
158
+ for (const [k, n] of opts) { const o = document.createElement('option'); o.value = k; o.textContent = n; sel.appendChild(o); }
159
+ sel.value = SCROLL_KEY;
160
+ $('scrollPick').hidden = opts.length < 2;
161
+ sel.onchange = () => switchScroll(sel.value);
162
+ }
163
+ function switchScroll(key) {
164
+ const h = new URLSearchParams(key && key !== DEFAULT_ID ? { s: key } : {});
165
+ location.hash = h.toString();
166
+ location.reload();
167
+ }
168
+ const OPEN = setupOpenOwn({ $, onOpen: switchScroll, currentKey: SCROLL_KEY });
169
+ $('btnOpen').onclick = () => { lastOpener = $('btnOpen'); OPEN.open(); };
170
+ window.__unroll = { scroll: () => ({ key: SCROLL_KEY, id: MAN.id, trusted: TRUSTED, windings: IDS, layers: MAN.layers.map((l) => l.role) }), open: OPEN };
171
+
172
+ let M, binBuf = null, texInk, texCT, MESHB = null;
173
+ const blankImg = () => { const c = document.createElement('canvas'); c.width = c.height = 4; return c; };
174
+ if (MAN.geometry.format === 'grid-int16') {
175
+ const g = MAN.geometry;
176
+ M = JSON.parse(new TextDecoder().decode(await SRC.bytes(g.index, 6e4)));
177
+ // atlases: WebP first, and the JPG fallback if this browser cannot decode WebP or the file does not arrive
178
+ const atl = async (l) => {
179
+ if (!l) return texFrom(blankImg());
180
+ try { return texFrom(await createImageBitmap(new Blob([await SRC.bytes(l.atlas, l.sizeHint || 3e6)]))); }
181
+ catch (e) {
182
+ if (!l.atlasFallback) throw e;
183
+ return texFrom(await createImageBitmap(new Blob([await SRC.bytes(l.atlasFallback, l.sizeHint || 3e6)])));
184
+ }
185
+ };
186
+ [binBuf, texInk, texCT] = await Promise.all([SRC.bytes(g.bin, g.sizeHint || 3.5e6), atl(L_INK), atl(L_CT)]);
187
+ } else {
188
+ try {
189
+ MESHB = await buildMeshScroll(MAN, SRC, { limits: TRUSTED ? REGISTRY_LIMITS : LOCAL_LIMITS, atlasSide: MOBILE ? 2048 : 4096 });
190
+ } catch (e) { loadFail(e.message, !TRUSTED); }
191
+ texInk = texFrom(MESHB.inkCanvas); texCT = texFrom(MESHB.ctCanvas);
192
+ M = { voxelMM: MAN.voxelMM, cellMM: MESHB.cellMM, windings: MESHB.windings.map((w) => ({ ...w, seg: (ORDER.find((o) => o.id === w.id) || {}).mesh || '' })) };
193
+ }
194
+ // per-winding stats for the overlay layer (registry scrolls only: it may carry HTML)
195
  let GPU = null;
196
+ if (L_OV && L_OV.stats && TRUSTED) {
197
+ try { GPU = JSON.parse(new TextDecoder().decode(await SRC.bytes(L_OV.stats, 4e3))); } catch (e) { /* no stats */ }
198
+ }
199
+ // the overlay layer's textures load the first time it is shown, winding by winding
 
 
 
 
 
 
 
200
  const gpuTex = {};
201
+ let ovLoading = null;
202
+ function loadOverlay() {
203
+ if (!L_OV || ovLoading) return ovLoading;
204
+ ovLoading = Promise.all([...OV_IDS].map(async (id) => {
205
+ try {
206
+ const p = layerFile(L_OV, id);
207
+ const bmp = SRC.kind === 'files' ? await decodeImage(await SRC.blob(p), p) : await createImageBitmap(new Blob([await SRC.bytes(p, L_OV.sizeHint || 1.5e5)]));
208
+ gpuTex[id] = texFrom(bmp);
209
+ gpuTex[id].anisotropy = Math.min(8, maxAniso);
210
+ const m = meshes.find((x) => x.userData.w.id === id);
211
+ if (m) m.userData.own.uGpuTex.value = gpuTex[id];
212
+ } catch (e) { console.warn('overlay', id, e); }
213
+ }));
214
+ return ovLoading;
215
+ }
216
  const blank = new THREE.DataTexture(new Uint8Array([0, 0, 0, 255]), 1, 1);
217
  blank.needsUpdate = true;
218
 
 
248
 
249
  const VOX = M.voxelMM;
250
  const CELL = M.cellMM;
251
+ const all = binBuf ? new Int16Array(binBuf) : null;
252
  const shared = {
253
  uInk: { value: texInk }, uCT: { value: texCT },
254
  uRot: { value: 0 }, uRoll: { value: new THREE.Vector3() },
 
347
  }`;
348
 
349
  // windings in peel order: outermost first
350
+ const wins = ORDER.map((o) => M.windings.find((w) => w.id === o.id));
351
+ if (wins.some((w) => !w)) loadFail(`The geometry file has no data for ${ORDER.filter((o, i) => !wins[i]).map((o) => o.id).join(', ')}.`, !TRUSTED);
352
  let S = 0;
353
+ const gpuIds = OV_IDS;
354
  const meshes = [];
355
  const decim = MOBILE ? 2 : 1;
356
  let Rmax = 0;
357
 
358
+ function meshGeometry(w) {
359
+ const geo = new THREE.BufferGeometry();
360
+ geo.setAttribute('position', new THREE.BufferAttribute(w.pos, 3));
361
+ geo.setAttribute('aLocal', new THREE.BufferAttribute(w.loc, 2));
362
+ geo.setIndex(new THREE.BufferAttribute(w.index, 1));
363
+ geo.computeVertexNormals();
364
+ geo.computeBoundingSphere();
365
+ return { geo, ytop: w.ytop, colAng: w.colAng };
366
+ }
367
+ function gridGeometry(w) {
368
  const R = w.rows, C = w.cols;
369
  const a = all.subarray(w.offset / 2, (w.offset + w.bytes) / 2);
370
  const pos = new Float32Array(R * C * 3);
 
443
  geo.setIndex(idx);
444
  geo.computeVertexNormals();
445
  geo.computeBoundingSphere();
446
+ return { geo, ytop, colAng };
447
+ }
448
+ for (const [j, w] of wins.entries()) {
449
+ const { geo, ytop, colAng } = w.pos ? meshGeometry(w) : gridGeometry(w);
450
  Rmax = Math.max(Rmax, w.radiusMM);
451
 
452
  const own = {
 
561
  if (gpuIds.has(m.userData.w.id)) i.className = 'gpu';
562
  ticks.appendChild(i);
563
  }
564
+ {
565
+ const outer = wins[0].id, inner = wins[wins.length - 1].id;
566
+ $('scrub').querySelector('.ends').innerHTML = `<span><span class="long">ROLLED · OUTERMOST ${esc(outer)}</span><span class="short">OUTER ${esc(outer)}</span></span><span><span class="long">INNERMOST ${esc(inner)} · UNROLLED</span><span class="short">INNER ${esc(inner)}</span></span>`;
567
+ }
568
  let playing = false;
569
  let target = t;
570
  // the one place the unroll position changes: slider, scrubber drag, keys, buttons and code all go through here
 
595
  addEventListener('keydown', (e) => {
596
  if (e.code === 'Escape') { closeSheets(); return; }
597
  if (e.target.closest('input,textarea,select')) return;
598
+ if (!$('focus').hidden || !$('about').hidden || !$('openSheet').hidden) return;
599
  if (e.code === 'Space') {
600
  if (e.target.closest('button,a,[role=tab],[role=button]')) return; // let focused controls act natively
601
  e.preventDefault(); introDone(); autoplayAt = 0; setPlaying(!playing);
 
611
  scrubIn.addEventListener('keydown', (e) => { if (e.code.startsWith('Arrow')) e.stopPropagation(); });
612
 
613
  let layer = 'ink';
614
+ // the three layer chips map to the manifest's roles: xray = ct, ink = ink, gpu = overlay
615
+ const CHIP_LAYER = { xray: L_CT, ink: L_INK, gpu: L_OV };
616
+ const LAYER_HINTS = {};
617
+ for (const [k, l] of Object.entries(CHIP_LAYER)) {
618
+ const chip = document.querySelector(`.chip[data-layer="${k}"]`);
619
+ if (!l) { chip.hidden = true; continue; }
620
+ LAYER_HINTS[k] = l.hint || [l.label, l.source, um(l)].filter(Boolean).join(', ');
621
+ chip.title = l.title || LAYER_HINTS[k];
622
+ chip.innerHTML = (k === 'gpu' ? '<i class="dot"></i>' : '') + muHTML(l.label);
623
+ }
624
+ if (!L_INK) layer = L_OV ? 'gpu' : 'xray';
625
  let layerT = 1, gpuT = 0;
626
  function setLayer(l) {
627
  layer = l;
628
  for (const b of document.querySelectorAll('.chip[data-layer]')) b.classList.toggle('on', b.dataset.layer === l);
629
  const hint = $('layerHint');
630
  if (hint) hint.textContent = LAYER_HINTS[l] || '';
631
+ if (l === 'gpu') loadOverlay();
632
  saveHash();
633
  }
634
  for (const b of document.querySelectorAll('.chip[data-layer]')) {
 
639
  if (b.dataset.layer === 'gpu' && target < bandEnd + 0.01) { autoplayAt = 0; setPlaying(false); setTarget(bandEnd + 0.015, 'layer'); }
640
  };
641
  }
642
+ $('layerHint').textContent = LAYER_HINTS[layer] || '';
643
+ $('layerWhy').hidden = !(L_OV && (D?.layerWhy || L_OV.why));
644
+ if (!$('layerWhy').hidden) $('layerWhy').querySelector('p').textContent = D?.layerWhy || L_OV.why;
645
+ if (L_OV && OV_IDS.size) {
646
  $('gpuChip').hidden = false;
647
  const band = document.createElement('div');
648
  band.className = 'band';
649
  band.style.left = `${bandStart * 100}%`;
650
  band.style.width = `${(bandEnd - bandStart) * 100}%`;
651
+ band.title = L_OV.bandTitle || `Windings with ${L_OV.label}`;
652
  $('scrub').appendChild(band);
653
+ if (GPU) {
654
+ $('rGpuRow').hidden = false;
655
+ $('rGpuRow').querySelector('.dim').textContent = L_OV.readoutLabel || 'OVERLAY';
656
+ }
657
+ if (GPU && (L_OV.aboutHtml || GPU.about)) {
658
+ const a = $('aboutGpu');
659
+ a.hidden = false;
660
+ a.innerHTML = L_OV.aboutHtml || GPU.about;
661
+ }
662
+ } else $('gpuChip').hidden = true;
663
 
664
  function saveHash() {
665
+ const h = new URLSearchParams({ ...(SCROLL_KEY !== DEFAULT_ID ? { s: SCROLL_KEY } : {}), t: target.toFixed(3), l: layer });
666
  history.replaceState(null, '', `#${h}`);
667
  }
668
 
 
685
  const pos = new THREE.Vector3(-150, portrait ? 150 : 110, stripZ + (portrait ? 520 : 360));
686
  return [pos, tgt];
687
  }
688
+ let intro = !params.has('t') && !REDUCED && !SHOT && !localKey(SCROLL_KEY);
689
  if (!intro) shared.uSweep.value = -999;
690
  // the intro opens looking straight down the roll's axis, where the windings read as a spiral
691
  const TOP_TARGET = new THREE.Vector3(innerWidth > innerHeight ? -30 : 0, -2, 0);
 
707
  }
708
  if (params.has('t')) {
709
  t = tShown = Math.min(1, Math.max(0, +params.get('t') || 0)); setTarget(t, 'hash');
710
+ if (['xray', 'ink', 'gpu'].includes(params.get('l')) && CHIP_LAYER[params.get('l')]) setLayer(params.get('l'));
711
+ if (layer === 'gpu') await loadOverlay();
712
  shared.uSweep.value = -999;
713
  }
714
  {
 
766
  tip.hidden = false;
767
  tip.style.left = `${e.clientX}px`;
768
  tip.style.top = `${e.clientY}px`;
769
+ tip.innerHTML = `${w.id.toUpperCase()} · r ${w.radiusMM.toFixed(1)} mm · ${w.areaCM2.toFixed(0)} cm²${gpuIds.has(w.id) ? ` · <span style="color:var(--gpu)">${esc(L_OV.readoutLabel || L_OV.label.toUpperCase())}</span>` : ''} <span class="dim">· click to read</span>`;
770
  canvas.style.cursor = 'pointer';
771
  } else {
772
  tip.hidden = true;
 
802
  }
803
  $('fSwipe').addEventListener('input', vApply);
804
  $('fSwipe').addEventListener('pointerdown', (e) => e.stopPropagation());
805
+ img.addEventListener('error', () => { if (img.getAttribute('src')) $('fErr').hidden = false; });
806
  img.addEventListener('load', () => { $('fErr').hidden = true; });
807
  function vFit() {
808
  const r = viewer.getBoundingClientRect();
 
851
  setPlaying(false);
852
  const w = m.userData.w;
853
  $('fTitle').textContent = w.id;
854
+ const setSrc = async (el, which) => {
855
+ const u = await hiURL(which, w);
856
+ if (focusW === w) el.src = u;
857
+ };
858
  $('fKicker').textContent = `TRACED WINDING ${wins.length - m.userData.j} OF ${wins.length}, INNERMOST FIRST · ${w.seg}`;
859
  const seg = $('fSeg');
860
  seg.innerHTML = '';
861
+ const g = gpuIds.has(w.id) ? (GPU && GPU.windings[w.id]) || {} : null;
862
+ const base = L_INK ? 'ink' : 'ct';
863
+ const views = [['vc', closeLabel(L_INK || L_CT), base]];
864
+ if (g) views.push(['gpu', closeLabel(L_OV), 'overlay']);
865
+ if (g && views.length) views.push(['cmp', 'Compare (swipe)', base]);
866
+ $('fSwipeA').innerHTML = muHTML(shortLabel(L_INK || L_CT));
867
+ $('fSwipeB').innerHTML = muHTML(shortLabel(L_OV));
868
+ $('fSwipe').setAttribute('aria-label', `Swipe between ${shortLabel(L_INK || L_CT)} and ${shortLabel(L_OV)}`);
869
  focusW = w;
870
  $('fErr').hidden = true;
871
  const setCmp = (on) => {
872
  $('fImg2').hidden = $('fSwipeWrap').hidden = $('fSwipeLine').hidden = !on;
873
+ if (on) { $('fImg2').onload = vApply; setSrc($('fImg2'), 'overlay'); }
874
  };
875
  setCmp(false);
876
  for (const [k, label, src] of views) {
877
  const b = document.createElement('button');
878
  b.className = `chip${k === 'gpu' ? ' gpu' : ''}`;
879
+ b.innerHTML = muHTML(label);
880
  b.onclick = () => {
881
  for (const x of seg.children) x.classList.toggle('on', x === b);
882
  img.dataset.keep = '1';
883
+ setSrc(img, src);
884
  setCmp(k === 'cmp');
885
+ $('fMeta').innerHTML = k === 'gpu' ? ovMeta(w, g) : k === 'cmp' ? `Left of the line: ${esc(closeLabel(L_INK || L_CT))}. Right: ${esc(closeLabel(L_OV))}. Drag the swipe control to compare.` : vcMeta(w);
886
  };
887
  seg.appendChild(b);
888
  }
889
  const start = g && layer === 'gpu' ? 1 : 0;
890
  seg.children[start].classList.add('on');
891
  img.dataset.keep = '';
892
+ setSrc(img, views[start][2]);
893
+ $('fMeta').innerHTML = start ? ovMeta(w, g) : vcMeta(w);
894
  $('focus').hidden = false;
895
  $('fClose').focus();
896
  }
897
+ const closeLabel = (l) => (l ? l.closeupLabel || [l.label, um(l)].filter(Boolean).join(' · ') : '');
898
+ const shortLabel = (l) => (l ? l.label : '');
899
+ // the close-up image of a layer for one winding: its "hi" file, else the layer's own texture, else the atlas rectangle
900
+ const hiCache = new Map();
901
+ async function hiURL(which, w) {
902
+ const key = `${which}:${w.id}`;
903
+ if (hiCache.has(key)) return hiCache.get(key);
904
+ const l = which === 'overlay' ? L_OV : which === 'ink' ? L_INK : L_CT;
905
+ let u;
906
+ if (l && l.hi) u = SRC.kind === 'files' ? await SRC.imageURL(fill(l.hi, w.id)) : SRC.url(fill(l.hi, w.id));
907
+ else if (l && l.texture !== undefined || (l && l.files)) u = await SRC.imageURL(layerFile(l, w.id));
908
+ else u = await atlasCrop(which === 'ct' ? texCT : texInk, w);
909
+ hiCache.set(key, u);
910
+ return u;
911
+ }
912
+ async function atlasCrop(tex, w) {
913
+ const im = tex.image, [a, b, c, d] = w.atlas;
914
+ const cv = document.createElement('canvas');
915
+ cv.width = Math.max(1, Math.round((c - a) * im.width)); cv.height = Math.max(1, Math.round((d - b) * im.height));
916
+ cv.getContext('2d').drawImage(im, a * im.width, b * im.height, cv.width, cv.height, 0, 0, cv.width, cv.height);
917
+ return new Promise((ok) => cv.toBlob((bl) => ok(URL.createObjectURL(bl)), 'image/png'));
918
+ }
919
+ function ovMeta(w, g) {
920
+ if (g && g.meta) return g.meta;
921
+ return `${esc(L_OV.label)}${L_OV.source ? ` · ${esc(L_OV.source)}` : ''}${um(L_OV) ? ` · ${um(L_OV)}` : ''} · drag to pan, scroll or pinch to zoom, double-click to fit`;
922
+ }
923
  function vcMeta(w) {
924
+ const l = L_INK || L_CT;
925
+ const note = l.notes || [l === L_INK ? 'ink' : 'X-ray', l.source].filter(Boolean).join(': ');
926
  return `${w.widthMM.toFixed(0)} × ${w.heightMM.toFixed(0)} mm · ${w.areaCM2.toFixed(1)} cm² · radius ${w.radiusMM.toFixed(1)} mm · ` +
927
+ `${esc(note)} · drag to pan, scroll or pinch to zoom, double-click to fit`;
928
  }
929
  let lastOpener = null;
930
  function closeSheets() {
931
+ const wasOpen = !$('focus').hidden || !$('about').hidden || !$('openSheet').hidden;
932
  $('focus').hidden = true;
933
  $('about').hidden = true;
934
+ $('openSheet').hidden = true;
935
  if (wasOpen && lastOpener) lastOpener.focus();
936
  }
937
  $('fClose').onclick = closeSheets;
 
970
  const x = 28 * s;
971
  g.fillStyle = 'rgba(141,133,122,1)';
972
  g.font = `${Math.round(11 * s)}px "JetBrains Mono", monospace`;
973
+ const SH = D?.shot || { kicker: `${MAN.name.toUpperCase()} / OPENED LOCALLY`, line1: MAN.name, line2: '', accent: '', footer: `data: ${MAN.credits?.text || MAN.name}${MAN.dataTerms?.license ? `, ${MAN.dataTerms.license}` : ''}` };
974
+ g.fillText(SH.kicker, x, 40 * s);
975
  const fs = Math.round(Math.min(64, Math.max(34, innerWidth * 0.046)) * s);
976
  g.font = `${fs}px "Instrument Serif", Georgia, serif`;
977
  g.fillStyle = 'rgba(236,230,219,1)';
978
+ g.fillText(SH.line1, x, 40 * s + fs * 1.05);
979
+ const l2 = SH.line2;
980
  g.fillText(l2, x, 40 * s + fs * 2.03);
981
  const w2 = g.measureText(l2).width;
982
  g.font = `italic ${fs}px "Instrument Serif", Georgia, serif`;
983
  g.fillStyle = '#ffb347';
984
+ g.fillText(SH.accent, x + w2, 40 * s + fs * 2.03);
985
  g.fillStyle = 'rgba(141,133,122,1)';
986
  g.font = `${Math.round(11 * s)}px "JetBrains Mono", monospace`;
987
+ g.fillText(`${(tShown * L / 1000).toFixed(2)} m of traced strip unrolled · ${SH.footer}`, x, c.height - 26 * s);
988
  return c;
989
  }
990
  $('btnShot').onclick = () => {
991
  composeShot().toBlob((b) => {
992
  const a = document.createElement('a');
993
  a.href = URL.createObjectURL(b);
994
+ a.download = `${MAN.id.toLowerCase().replace(/[^a-z0-9_-]+/g, '-')}-unroll-${Math.round(tShown * 100)}.png`;
995
  a.click();
996
  setTimeout(() => URL.revokeObjectURL(a.href), 4000);
997
  }, 'image/png');
 
1098
  $('rRad').textContent = `${st.radius.toFixed(1)} mm`;
1099
  $('rLen').textContent = `${(st.s / 1000).toFixed(2)} / ${(L / 1000).toFixed(2)} m`;
1100
  if (GPU) {
1101
+ const g = gpuIds.has(st.cur.userData.w.id) && GPU.windings[st.cur.userData.w.id];
1102
  $('rGpu').textContent = g ? `${g.patches.toLocaleString()} patches · ${g.gpuSeconds} s` : '·';
1103
  $('rGpuRow').classList.toggle('live', !!g);
1104
  }
 
1112
  }
1113
  requestAnimationFrame(frame);
1114
 
1115
+ // the overlay textures load after the first frame; until then those sheets show the main ink layer
1116
+ requestAnimationFrame(() => loadOverlay());
 
 
 
 
 
 
 
1117
 
1118
  // camera hooks for the keyboard shortcuts in polish.js
1119
  window.unrollView = {
data/atlas_ct.webp ADDED

Git LFS Details

  • SHA256: 1d19327e2f4858a0a12e813f29c06f2554ae8543fd92ab4add827ed8d0182375
  • Pointer size: 132 Bytes
  • Size of remote file: 3.48 MB
data/atlas_ink.webp ADDED

Git LFS Details

  • SHA256: 12ccca96a5910308b99403ccbfb03aae7c1943885d3899d33e7bd8d8a2f2166a
  • Pointer size: 132 Bytes
  • Size of remote file: 1.88 MB
data/gpu.json CHANGED
@@ -9,7 +9,7 @@
9
  "calls": 1,
10
  "overlap": 0.25,
11
  "started": "2026-10-16T00:22:15Z",
12
- "meta": "ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 4,891 patches of 128\u00d7128 px, overlap 0.25 (patch seams visible) \u00b7 7.5 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
13
  },
14
  "w047": {
15
  "tex": "data/gpu/w047.jpg",
@@ -20,7 +20,7 @@
20
  "calls": 3,
21
  "overlap": 0.5,
22
  "started": "2026-10-15T20:09:32Z",
23
- "meta": "ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 10,950 patches of 128\u00d7128 px, overlap 0.5 \u00b7 18.4 s of GPU in 3 calls \u00b7 2026-10-15 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
24
  },
25
  "w048": {
26
  "tex": "data/gpu/w048.jpg",
@@ -31,7 +31,7 @@
31
  "calls": 1,
32
  "overlap": 0.25,
33
  "started": "2026-10-16T00:23:44Z",
34
- "meta": "ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 4,885 patches of 128\u00d7128 px, overlap 0.25 (patch seams visible) \u00b7 7.6 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
35
  },
36
  "w049": {
37
  "tex": "data/gpu/w049.jpg",
@@ -42,7 +42,7 @@
42
  "calls": 1,
43
  "overlap": 0.25,
44
  "started": "2026-10-16T00:25:23Z",
45
- "meta": "ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 5,306 patches of 128\u00d7128 px, overlap 0.25 (patch seams visible) \u00b7 8.2 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
46
  },
47
  "w050": {
48
  "tex": "data/gpu/w050.jpg",
@@ -53,7 +53,7 @@
53
  "calls": 1,
54
  "overlap": 0.5,
55
  "started": "2026-10-16T00:26:27Z",
56
- "meta": "ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 4,629 patches of 128\u00d7128 px, overlap 0.5 \u00b7 6.4 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
57
  },
58
  "w051": {
59
  "tex": "data/gpu/w051.jpg",
@@ -64,7 +64,7 @@
64
  "calls": 1,
65
  "overlap": 0.2,
66
  "started": "2026-10-16T00:28:35Z",
67
- "meta": "ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 6,480 patches of 128\u00d7128 px, overlap 0.2 (patch seams visible) \u00b7 9.1 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
68
  }
69
  },
70
  "totals": {
@@ -74,5 +74,5 @@
74
  "calls": 8,
75
  "device": "NVIDIA RTX PRO 6000 Blackwell Server Edition MIG 2g.48gb"
76
  },
77
- "about": "<b>The cyan band</b> is ours. We used all 8 of a free Hugging Face account's daily ZeroGPU runs (the limit is 8; most of the daily GPU-time quota was left over) to run the public <a href=\"https://huggingface.co/scrollprize/ink_9um\" target=\"_blank\" rel=\"noopener\">scrollprize/ink_9um</a> model over windings w046 to w051: 37,141 patches in 57 s of measured GPU time on half an NVIDIA RTX PRO 6000 Blackwell. It reads the 9.362 \u00b5m scan, about four times coarser than the 2.4 \u00b5m scan behind the amber layer, so its ink map is noisier. w047 and w050 ran with patch overlap 0.5; w046, w048, w049 and w051 ran with less overlap, so their 128 px patch grid shows as faint square tiles. That grid is a stitching artifact, not ink. Click a cyan winding to compare the two maps."
78
  }
 
9
  "calls": 1,
10
  "overlap": 0.25,
11
  "started": "2026-10-16T00:22:15Z",
12
+ "meta": "Our ink model (9 \u00b5m): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 4,891 patches of 128\u00d7128 px, overlap 0.25 (patch seams visible) \u00b7 7.5 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
13
  },
14
  "w047": {
15
  "tex": "data/gpu/w047.jpg",
 
20
  "calls": 3,
21
  "overlap": 0.5,
22
  "started": "2026-10-15T20:09:32Z",
23
+ "meta": "Our ink model (9 \u00b5m): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 10,950 patches of 128\u00d7128 px, overlap 0.5 \u00b7 18.4 s of GPU in 3 calls \u00b7 2026-10-15 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
24
  },
25
  "w048": {
26
  "tex": "data/gpu/w048.jpg",
 
31
  "calls": 1,
32
  "overlap": 0.25,
33
  "started": "2026-10-16T00:23:44Z",
34
+ "meta": "Our ink model (9 \u00b5m): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 4,885 patches of 128\u00d7128 px, overlap 0.25 (patch seams visible) \u00b7 7.6 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
35
  },
36
  "w049": {
37
  "tex": "data/gpu/w049.jpg",
 
42
  "calls": 1,
43
  "overlap": 0.25,
44
  "started": "2026-10-16T00:25:23Z",
45
+ "meta": "Our ink model (9 \u00b5m): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 5,306 patches of 128\u00d7128 px, overlap 0.25 (patch seams visible) \u00b7 8.2 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
46
  },
47
  "w050": {
48
  "tex": "data/gpu/w050.jpg",
 
53
  "calls": 1,
54
  "overlap": 0.5,
55
  "started": "2026-10-16T00:26:27Z",
56
+ "meta": "Our ink model (9 \u00b5m): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 4,629 patches of 128\u00d7128 px, overlap 0.5 \u00b7 6.4 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
57
  },
58
  "w051": {
59
  "tex": "data/gpu/w051.jpg",
 
64
  "calls": 1,
65
  "overlap": 0.2,
66
  "started": "2026-10-16T00:28:35Z",
67
+ "meta": "Our ink model (9 \u00b5m): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 \u00b5m scan \u00b7 6,480 patches of 128\u00d7128 px, overlap 0.2 (patch seams visible) \u00b7 9.1 s of GPU in 1 call \u00b7 2026-10-16 \u00b7 drag to pan, scroll or pinch to zoom, double-click to fit"
68
  }
69
  },
70
  "totals": {
 
74
  "calls": 8,
75
  "device": "NVIDIA RTX PRO 6000 Blackwell Server Edition MIG 2g.48gb"
76
  },
77
+ "about": "<b>Our ink model (9 \u00b5m)</b>, the cyan band, is ours. We used all 8 of a free Hugging Face account's daily ZeroGPU runs (the limit is 8; most of the daily GPU-time quota was left over) to run the public <a href=\"https://huggingface.co/scrollprize/ink_9um\" target=\"_blank\" rel=\"noopener\">scrollprize/ink_9um</a> model over windings w046 to w051: 37,141 patches in 57 s of measured GPU time on half an NVIDIA RTX PRO 6000 Blackwell. It reads the 9.362 \u00b5m scan, about four times coarser than the 2.4 \u00b5m scan behind the amber layer, so its ink map is noisier. w047 and w050 ran with patch overlap 0.5; w046, w048, w049 and w051 ran with less overlap, so their 128 px patch grid shows as faint square tiles. That grid is a stitching artifact, not ink. Click a cyan winding to compare the two maps."
78
  }
docs/ADDING_A_SCROLL.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adding a scroll
2
+
3
+ The page draws whatever is listed in `scrolls/index.json`. Each entry points to a manifest that describes one scroll: its windings, the meshes and images behind them, its ink layers, and who made the data. Nothing about a particular scroll is hardcoded in `app.js`.
4
+
5
+ When the registry holds more than one scroll, a scroll picker appears at the top right. With only one (and nothing opened locally) the picker stays hidden.
6
+
7
+ ## Files
8
+
9
+ ```
10
+ scrolls/index.json the registry
11
+ scrolls/<id>/manifest.json one manifest per scroll
12
+ lib/manifest.js schema helpers and the validator (shared by the page and Node)
13
+ lib/scrolls.js loading: registry, local storage, mesh scrolls, atlases
14
+ lib/formats.js OBJ, PLY, TIFF and zip readers, all in the browser
15
+ lib/openown.js, lib/example.js "Open your own" and the example package
16
+ tools/validate_scroll.mjs the validator, from the command line
17
+ tools/precompute_template.py a starting point for turning traced windings into a package
18
+ ```
19
+
20
+ ## The registry
21
+
22
+ ```json
23
+ {
24
+ "schema": "unroll-registry/1",
25
+ "default": "PHerc0139",
26
+ "scrolls": [
27
+ { "id": "PHerc0139", "name": "PHerc. 139", "manifest": "scrolls/PHerc0139/manifest.json" }
28
+ ]
29
+ }
30
+ ```
31
+
32
+ `default` is the scroll shown when the URL does not name one. Other scrolls open with `#s=<id>` in the URL.
33
+
34
+ ## The manifest
35
+
36
+ ```json
37
+ {
38
+ "schema": "unroll-scroll/1",
39
+ "id": "MyScroll",
40
+ "name": "My scroll",
41
+ "description": "One or two sentences.",
42
+ "voxelMM": 0.00791,
43
+ "geometry": { "format": "mesh", "units": "voxels", "axis": "z" },
44
+ "windings": [
45
+ { "id": "w012", "mesh": "meshes/w012.obj" },
46
+ { "id": "w011", "mesh": "meshes/w011.ply" }
47
+ ],
48
+ "outermost": "first",
49
+ "layers": [
50
+ { "id": "xray", "role": "ct", "label": "X-ray", "texture": "xray/{id}.jpg", "source": "Surface volume, 7.91 um scan", "resolutionUM": 7.91 },
51
+ { "id": "ink", "role": "ink", "label": "Published ink (2.4 µm)", "texture": "ink/{id}.png", "files": { "w011": "ink/w011.tif" },
52
+ "source": "Which model, on which scan", "resolutionUM": 2.4, "hi": "closeups/{id}.jpg" },
53
+ { "id": "model", "role": "overlay", "label": "Our ink model (9 µm)", "windings": { "range": ["w011", "w012"] },
54
+ "texture": "model/{id}.png", "source": "ink_9um on the 9.4 um scan", "resolutionUM": 9.362 }
55
+ ],
56
+ "credits": { "text": "Who made the data", "url": "https://scrollprize.org", "citation": "How to cite it" },
57
+ "dataTerms": { "license": "CC BY-NC 4.0", "url": "https://creativecommons.org/licenses/by-nc/4.0/", "notes": "Anything else" }
58
+ }
59
+ ```
60
+
61
+ | Field | Meaning |
62
+ | --- | --- |
63
+ | `schema` | Always `unroll-scroll/1`. |
64
+ | `id` | Letters, digits, `.`, `-`, `_`; up to 64 characters. Used in the URL. |
65
+ | `voxelMM` | Scan voxel size in millimetres. Meshes in voxel units are scaled by it. |
66
+ | `base` | Optional folder that asset paths are relative to, itself relative to the manifest. Registry manifests use `"../../"` to reach `data/`. |
67
+ | `geometry.format` | `mesh` (OBJ or PLY per winding) or `grid-int16` (the packed format `tools/build.py` writes; registry only). |
68
+ | `geometry.units` | `voxels` (default) or `mm`. |
69
+ | `geometry.axis` | `z` (default: the scan convention, roll axis along z) or `y`. The page centres the roll on its bounding box. |
70
+ | `geometry.flipV` | Default `true`: OBJ and PLY have v pointing up, so the image's top row is v = 1. Set `false` if your v points down. |
71
+ | `windings` | A list of `{ "id", "mesh" }`, or `{ "range": ["w023", "w059"], "mesh": "meshes/{id}.obj", "skip": [], "outermost": "last" }`. A range keeps the zero padding. |
72
+ | `outermost` | `first` (default) or `last`: which end of the list is the outside of the roll. The page unrolls from the outside in. |
73
+ | `layers` | Up to one layer per role: `ct` (the X-ray chip), `ink` (amber) and `overlay` (cyan, with the compare swipe). At least `ct` or `ink`. |
74
+ | `layers[].windings` | `"all"` (default), `{ "range": [first, last] }`, or a list of ids. |
75
+ | `layers[].texture` | Path pattern with `{id}`, for mesh scrolls and overlays. `files` overrides it for single windings. |
76
+ | `layers[].atlas` | One atlas image for the whole scroll (`grid-int16` only). |
77
+ | `layers[].hi` | Optional close-up image per winding (pattern with `{id}`). Without it the close-up uses the layer's texture. |
78
+ | `layers[].label`, `hint`, `title`, `closeupLabel`, `readoutLabel`, `bandTitle`, `notes`, `source`, `resolutionUM` | What the page says about the layer: chip text, the line under the chips, the tooltip, the close-up tab, the readout, the scrubber band, and the close-up caption. |
79
+ | `layers[].stats` | Registry only: a JSON file with per-winding run details (see `data/gpu.json`). |
80
+ | `credits`, `dataTerms` | Shown in the footer and the About sheet. |
81
+ | `display` | Registry only: page title, headline, lede, About paragraphs and share-image text, as HTML. Manifests opened by visitors are always shown as plain text. |
82
+
83
+ ### Image layers on a mesh
84
+
85
+ Each layer image covers its winding's UV square: the left edge is u = 0, the right edge u = 1, the top row v = 1. Images can be PNG, JPG or TIFF (8, 16 or 32 bit; none, LZW, Deflate or PackBits compression); colour images use their red channel. 16- and 32-bit images are stretched to the range they use.
86
+
87
+ The page measures each winding's flattened width and height from the mesh and its UVs, packs the X-ray and ink images into two atlases (4096 px, 2048 on phones), and lays the windings end to end. Without an X-ray layer it paints the mesh's UV footprint instead, so Tear and Crush still know where the papyrus is.
88
+
89
+ ### What works with what
90
+
91
+ | Feature | Needs |
92
+ | --- | --- |
93
+ | Unroll, X-ray, ink | a mesh and one image layer per winding |
94
+ | Tear, Crush, Shake | the same (Tear cuts along the X-ray or the UV footprint) |
95
+ | Compare swipe | an `overlay` layer on that winding |
96
+ | Scale bar | always (the width comes from the mesh) |
97
+ | Readout row for the overlay | `stats` (registry only) |
98
+
99
+ ## Adding a scroll to the registry
100
+
101
+ 1. Build the package. `tools/precompute_template.py` turns tifxyz folders or OBJ files plus layer images into meshes, images and a manifest. Fill in its TODOs.
102
+ 2. Put it at `scrolls/<id>/` and add an entry to `scrolls/index.json`.
103
+ 3. Run `node tools/validate_scroll.mjs`. It checks the registry, every manifest, every referenced file and the size limits, with the same code the page uses.
104
+ 4. Serve the folder (`python3 -m http.server`) and open `http://localhost:8000/#s=<id>`.
105
+ 5. Store images and meshes with Git LFS or Xet when you push to the Space; Hugging Face refuses plain binary files.
106
+
107
+ Assets load per scroll: only the chosen scroll's files are fetched. Within a scroll the overlay images load the first time the overlay is shown, and close-up images load per winding when a winding is opened.
108
+
109
+ ## Open your own
110
+
111
+ Visitors can open a scroll without adding it to the registry. Press **+** at the top right (or drag files onto the page).
112
+
113
+ - **Nothing is uploaded.** The files are read by the page in the browser with the File API, checked with the same validator, and kept in this browser's IndexedDB until removed. No server receives them.
114
+ - **Ways in:** drop or pick a zip, a folder, or a manifest together with its files; or paste the URL of a manifest or a zip. A URL is fetched by the browser directly from that server, so the server must allow cross-origin requests (CORS). Files beside a manifest URL are fetched relative to it.
115
+ - **Formats:** OBJ or PLY meshes with UVs (`geometry.format` must be `mesh`), PNG, JPG or TIFF layers.
116
+ - **Limits:** 64 MB per file, 128 MB per zip, 256 MB in all, 64 windings, 2 million vertices, 8192 px per image side.
117
+ - **Errors** are listed by file and field: a missing file, a mesh without UVs, an image the browser cannot decode, a size over the limit.
118
+ - A scroll opened this way appears in the picker as "(local)", with its own URL (`#s=local-...`) that only works in the browser that opened it. Remove it under **+**.
119
+ - Manifests opened this way are shown as plain text: `display` and other HTML fields are ignored, so a shared link cannot inject markup into the page.
120
+
121
+ ### The example package
122
+
123
+ **Download example package** in the Open your own sheet builds `unroll-synthetic-scroll.zip` in the browser: three windings of a made-up spiral (two OBJ, one binary PLY, in millimetres with the roll axis along y), fake X-ray fibres, Greek text as ink in PNG, JPG and TIFF, and a blurred overlay on the middle winding so the compare swipe has something to show. Drop the zip straight back onto the page to see it unroll, then use its `manifest.json` as a starting point.
index.html CHANGED
@@ -29,10 +29,12 @@
29
  <link rel="stylesheet" href="style.css">
30
  <!-- start the big downloads and the 3D library in parallel with the page instead of one after another -->
31
  <link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js" crossorigin>
32
- <link rel="preload" href="data/scroll.json" as="fetch" crossorigin>
33
- <link rel="preload" href="data/scroll.bin" as="fetch" crossorigin>
34
- <link rel="preload" href="data/atlas_ink.jpg" as="fetch" crossorigin>
35
- <link rel="preload" href="data/atlas_ct.jpg" as="fetch" crossorigin>
 
 
36
  <script type="importmap">
37
  { "imports": {
38
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
@@ -65,14 +67,14 @@
65
  var box = document.getElementById('loadErr');
66
  if (!box || !document.getElementById('loader')) return;
67
  var msg = String((e && (e.reason || e.error || e.message)) || '');
68
- var why = /webgl|context/i.test(msg) ? 'Your browser could not start 3D graphics (WebGL). Try another browser or turn on hardware acceleration.'
69
  : 'A data file did not arrive. Check your connection and try again.';
70
  document.getElementById('loadErrWhy').textContent = why;
71
  box.hidden = false;
72
  document.getElementById('loader').classList.add('failed');
73
  }
74
  addEventListener('unhandledrejection', fail);
75
- addEventListener('error', function (e) { if (e.filename && /app\.js|tear\.js|three/.test(e.filename)) fail(e); });
76
  })();
77
  </script>
78
 
@@ -80,16 +82,17 @@
80
  <div class="mono dim kicker">PHERC. 0139 <span class="sep">/</span> HERCULANEUM <span class="sep">/</span> BURIED 79 CE</div>
81
  <h1>Unroll a scroll nobody has opened in <em>1,947 years.</em></h1>
82
  <p class="lede">37 of its windings have been traced through X‑ray CT by the Vesuvius Challenge, and neural networks found the ink on them. Drag to look around. Scrub to unroll.</p>
 
83
  </header>
84
 
85
  <nav class="hud tr" aria-label="Layers">
86
  <div class="seg" role="tablist">
87
  <button class="chip" data-layer="xray" role="tab" title="Raw X-ray CT brightness on each winding. No ink detection.">X‑ray</button>
88
- <button class="chip on" data-layer="ink" role="tab" title="Vesuvius Challenge's published ink detection on the fine 2.4 µm scan, covering all 37 windings.">Published ink</button>
89
- <button class="chip gpu" data-layer="gpu" role="tab" id="gpuChip" hidden title="Lower resolution comparison: the open ink_9um model run by us on free Hugging Face GPU, on the coarser 9.4 µm scan (about 4x coarser than 2.4 µm), for six windings. It looks blurrier and shows patch seams. It&#39;s here to show what an open model can recover from cheaper, more widely available scans, as a reproducible baseline you can check against the published result."><i class="dot"></i>Our GPU ink (lower res)</button>
90
  </div>
91
- <p class="layer-hint" id="layerHint" aria-live="polite">Published ink: Vesuvius Challenge detection, 2.4 µm scan, all windings.</p>
92
- <details class="layer-why"><summary>Why two ink layers?</summary><p>Published ink is the Vesuvius Challenge result on the fine 2.4 µm scan. Our GPU ink is the open ink_9um model run by us on a scan about 4x coarser, so it is blurrier. It shows what an open model can recover from cheaper scans, as a baseline you can check.</p></details>
93
  <div class="seg tear-seg">
94
  <button class="chip" id="btnTear" aria-pressed="false" title="Rip the carbonized papyrus: brittle, layered and fused like the real scrolls. Just for fun, not a real unrolling.">Tear apart</button>
95
  <button class="chip" id="btnReset" hidden title="Put every sheet back">Reset</button>
@@ -98,6 +101,7 @@
98
  <button class="chip" id="btnSound" hidden aria-pressed="false" title="Soft crackle when it breaks">Sound off</button>
99
  </div>
100
  <div class="tools">
 
101
  <button class="icon" id="btnInfo" title="About this page" aria-label="About">i</button>
102
  <button class="icon" id="btnShot" title="Save a picture" aria-label="Save a picture">
103
  <svg viewBox="0 0 24 24" width="15" height="15"><path d="M4 8h3l2-3h6l2 3h3v11H4z" fill="none" stroke="currentColor" stroke-width="1.5"/><circle cx="12" cy="13" r="3.5" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>
@@ -109,7 +113,7 @@
109
  <div><span class="dim">WINDING</span> <b id="rWind">w059</b></div>
110
  <div><span class="dim">RADIUS</span> <b id="rRad">13.3 mm</b></div>
111
  <div><span class="dim">STRIP</span> <b id="rLen">0.00 m</b></div>
112
- <div id="rGpuRow" hidden><span class="dim">ZEROGPU</span> <b id="rGpu">·</b></div>
113
  <button class="chip read" id="btnRead">Read w059</button>
114
  </aside>
115
 
@@ -141,15 +145,39 @@
141
  <button class="icon" id="fClose" aria-label="Close">✕</button>
142
  </div>
143
  </div>
144
- <div class="viewer" id="viewer"><img id="fImg" alt="Ink detection of this winding, flattened" draggable="false"><img id="fImg2" class="cmp" alt="Our GPU ink of the same winding, for comparison" draggable="false" hidden>
145
  <div class="swipe-line" id="fSwipeLine" hidden></div>
146
  <div class="scalebar mono" id="fScale" aria-hidden="true"><i></i><span>10 mm</span></div>
147
  <div class="img-err mono dim" id="fErr" hidden>This image could not be loaded.</div>
148
- <label class="swipe mono" id="fSwipeWrap" hidden>Published <input type="range" id="fSwipe" min="0" max="100" value="50" aria-label="Swipe between published ink and our GPU ink"> Our GPU</label>
149
  </div>
150
  <div class="sheet-foot mono dim" id="fMeta"></div>
151
  </section>
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  <section id="about" class="sheet about" hidden>
154
  <div class="sheet-head">
155
  <div><div class="mono dim">ABOUT</div><h2>What you are looking at</h2></div>
@@ -157,7 +185,7 @@
157
  </div>
158
  <div class="about-body">
159
  <p>PHerc. 139 is one of the papyrus rolls carbonized when Vesuvius buried Herculaneum in 79 CE. It is too fragile to open, so it was scanned with X‑rays at the ESRF synchrotron in Grenoble. It is held by the Biblioteca Nazionale di Napoli.</p>
160
- <p>Each sheet in the 3D view is one winding of the roll, traced through the CT volume by the <a href="https://scrollprize.org" target="_blank" rel="noopener">Vesuvius Challenge</a>. The shapes are the real ones, from the public 9.362 µm meshes. The <b>X‑ray</b> layer is the CT intensity on each surface. The <b>Ink</b> layer is the Vesuvius Challenge's public ink detection on the 2.4 µm scan. In 3D it is drawn through a local‑contrast filter so letter‑sized strokes stand out; the close‑up view shows the published preview unfiltered, downscaled to 2,400 px.</p>
161
  <p id="aboutGpu" hidden></p>
162
  <p>Unrolling lays the windings end to end, outermost first, the way a reader would open the roll. Each traced winding runs a little past one full turn, so roughly a tenth of the 2.8 m strip repeats surface from its neighbour.</p>
163
  <p class="mono dim small">Sources: open data bucket <code>PHerc0139/segments/*/mesh/*9.362um.tifxyz</code>, <code>surface-volumes/9.362um…zarr</code> and <code>ink-detection/downsampled</code>. Data: Giorgio Angelotti, Stephen Parsons, Sean Johnson, Elian Rafael Dal Prà, Johannes Rudolph, Paul Tafforeau, Alessandro Mirone, Paul Henderson, Hendrik Schilling, Forrest McDonald, David Josey, Youssef Nader, C. Seth Parker, W. Brent Seales. <i>Vesuvius Challenge - CT Scans of Herculaneum Papyri.</i> Vesuvius Challenge. Licensed <a href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank" rel="noopener">CC BY‑NC 4.0</a>. The page's code (HTML, CSS, JS and <code>tools/</code>) is MIT; see the Space's README.</p>
 
29
  <link rel="stylesheet" href="style.css">
30
  <!-- start the big downloads and the 3D library in parallel with the page instead of one after another -->
31
  <link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js" crossorigin>
32
+ <script>
33
+ // the default scroll's big files, fetched while three.js loads; skipped when the URL opens another scroll (#s=...)
34
+ if (!/(^|[#&])s=/.test(location.hash)) ['scrolls/index.json', 'scrolls/PHerc0139/manifest.json', 'data/scroll.json', 'data/scroll.bin', 'data/atlas_ink.webp', 'data/atlas_ct.webp'].forEach(function (h) {
35
+ var l = document.createElement('link'); l.rel = 'preload'; l.as = 'fetch'; l.crossOrigin = 'anonymous'; l.href = h; document.head.appendChild(l);
36
+ });
37
+ </script>
38
  <script type="importmap">
39
  { "imports": {
40
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
 
67
  var box = document.getElementById('loadErr');
68
  if (!box || !document.getElementById('loader')) return;
69
  var msg = String((e && (e.reason || e.error || e.message)) || '');
70
+ var why = window.__unrollWhy ? window.__unrollWhy : /webgl|context/i.test(msg) ? 'Your browser could not start 3D graphics (WebGL). Try another browser or turn on hardware acceleration.'
71
  : 'A data file did not arrive. Check your connection and try again.';
72
  document.getElementById('loadErrWhy').textContent = why;
73
  box.hidden = false;
74
  document.getElementById('loader').classList.add('failed');
75
  }
76
  addEventListener('unhandledrejection', fail);
77
+ addEventListener('error', function (e) { if (e.filename && /app\.js|tear\.js|lib\/|three/.test(e.filename)) fail(e); });
78
  })();
79
  </script>
80
 
 
82
  <div class="mono dim kicker">PHERC. 0139 <span class="sep">/</span> HERCULANEUM <span class="sep">/</span> BURIED 79 CE</div>
83
  <h1>Unroll a scroll nobody has opened in <em>1,947 years.</em></h1>
84
  <p class="lede">37 of its windings have been traced through X‑ray CT by the Vesuvius Challenge, and neural networks found the ink on them. Drag to look around. Scrub to unroll.</p>
85
+ <div class="scroll-pick" id="scrollPick" hidden><label class="mono dim" for="scrollSel">SCROLL</label> <select id="scrollSel"></select></div>
86
  </header>
87
 
88
  <nav class="hud tr" aria-label="Layers">
89
  <div class="seg" role="tablist">
90
  <button class="chip" data-layer="xray" role="tab" title="Raw X-ray CT brightness on each winding. No ink detection.">X‑ray</button>
91
+ <button class="chip on" data-layer="ink" role="tab" title="Vesuvius Challenge's published ink detection on the fine 2.4 µm scan, covering all 37 windings.">Published ink (2.4 <span class="mu">µ</span>m)</button>
92
+ <button class="chip gpu" data-layer="gpu" role="tab" id="gpuChip" hidden title="Lower resolution comparison: the open ink_9um model run by us on free Hugging Face GPU, on the coarser 9.4 µm scan (about 4x coarser than 2.4 µm), for six windings. It looks blurrier and shows patch seams. It&#39;s here to show what an open model can recover from cheaper, more widely available scans, as a reproducible baseline you can check against the published result."><i class="dot"></i>Our ink model (9 <span class="mu">µ</span>m)</button>
93
  </div>
94
+ <p class="layer-hint" id="layerHint" aria-live="polite">Published ink (2.4 µm): Vesuvius Challenge detection, 2.4 µm scan, all windings.</p>
95
+ <details class="layer-why" id="layerWhy"><summary>Why two ink layers?</summary><p>Published ink is the Vesuvius Challenge result on the fine 2.4 µm scan. Our ink model (9 µm) is the open ink_9um model run by us on a scan about 4x coarser, so it is blurrier. It shows what an open model can recover from cheaper scans, as a baseline you can check.</p></details>
96
  <div class="seg tear-seg">
97
  <button class="chip" id="btnTear" aria-pressed="false" title="Rip the carbonized papyrus: brittle, layered and fused like the real scrolls. Just for fun, not a real unrolling.">Tear apart</button>
98
  <button class="chip" id="btnReset" hidden title="Put every sheet back">Reset</button>
 
101
  <button class="chip" id="btnSound" hidden aria-pressed="false" title="Soft crackle when it breaks">Sound off</button>
102
  </div>
103
  <div class="tools">
104
+ <button class="icon" id="btnOpen" title="Open your own scroll: files stay in your browser, nothing is uploaded" aria-label="Open your own scroll">+</button>
105
  <button class="icon" id="btnInfo" title="About this page" aria-label="About">i</button>
106
  <button class="icon" id="btnShot" title="Save a picture" aria-label="Save a picture">
107
  <svg viewBox="0 0 24 24" width="15" height="15"><path d="M4 8h3l2-3h6l2 3h3v11H4z" fill="none" stroke="currentColor" stroke-width="1.5"/><circle cx="12" cy="13" r="3.5" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>
 
113
  <div><span class="dim">WINDING</span> <b id="rWind">w059</b></div>
114
  <div><span class="dim">RADIUS</span> <b id="rRad">13.3 mm</b></div>
115
  <div><span class="dim">STRIP</span> <b id="rLen">0.00 m</b></div>
116
+ <div id="rGpuRow" hidden><span class="dim">OUR INK</span> <b id="rGpu">·</b></div>
117
  <button class="chip read" id="btnRead">Read w059</button>
118
  </aside>
119
 
 
145
  <button class="icon" id="fClose" aria-label="Close">✕</button>
146
  </div>
147
  </div>
148
+ <div class="viewer" id="viewer"><img id="fImg" alt="Ink detection of this winding, flattened" draggable="false"><img id="fImg2" class="cmp" alt="The comparison layer for the same winding" draggable="false" hidden>
149
  <div class="swipe-line" id="fSwipeLine" hidden></div>
150
  <div class="scalebar mono" id="fScale" aria-hidden="true"><i></i><span>10 mm</span></div>
151
  <div class="img-err mono dim" id="fErr" hidden>This image could not be loaded.</div>
152
+ <label class="swipe mono" id="fSwipeWrap" hidden><span id="fSwipeA">Published ink (2.4 <span class="mu">µ</span>m)</span> <input type="range" id="fSwipe" min="0" max="100" value="50" aria-label="Swipe between Published ink (2.4 µm) and Our ink model (9 µm)"> <span id="fSwipeB">Our ink model (9 <span class="mu">µ</span>m)</span></label>
153
  </div>
154
  <div class="sheet-foot mono dim" id="fMeta"></div>
155
  </section>
156
 
157
+ <section id="openSheet" class="sheet about open-own" hidden aria-label="Open your own scroll">
158
+ <div class="sheet-head">
159
+ <div><div class="mono dim">OPEN YOUR OWN</div><h2>Unroll your own scroll</h2></div>
160
+ <button class="icon" id="oClose" aria-label="Close">✕</button>
161
+ </div>
162
+ <div class="about-body">
163
+ <p class="o-private"><b>Nothing is uploaded.</b> Your files are read by this page inside your browser and kept on this device (in browser storage) until you remove them. No server sees them.</p>
164
+ <div class="o-drop" id="oDrop" tabindex="0" role="button" aria-label="Drop files here or press Enter to pick files">
165
+ <div class="o-drop-text">Drop a <b>zip</b>, or a <b>manifest.json</b> with its meshes and images, or a folder</div>
166
+ <div class="o-drop-btns">
167
+ <label class="chip">Pick files<input type="file" id="oPick" multiple accept=".zip,.json,.obj,.ply,.png,.jpg,.jpeg,.tif,.tiff" hidden></label>
168
+ <label class="chip">Pick a folder<input type="file" id="oPickDir" webkitdirectory multiple hidden></label>
169
+ </div>
170
+ </div>
171
+ <form class="o-url" id="oURLForm"><input type="url" id="oURL" placeholder="https://example.org/my-scroll/manifest.json or .zip" aria-label="URL of a manifest or zip"><button class="chip" type="submit">Open URL</button></form>
172
+ <p class="mono dim small">A URL is fetched by your browser straight from that server, which must allow cross-origin requests (CORS).</p>
173
+ <div class="o-status mono" id="oStatus" role="status" aria-live="polite" hidden></div>
174
+ <div id="oSaved" hidden><div class="mono dim">IN THIS BROWSER</div><ul class="o-list" id="oSavedList"></ul></div>
175
+ <p>Meshes: OBJ or PLY with texture coordinates (UVs), one per winding. Layers: PNG, JPG or TIFF images laid out on those UVs: an X-ray layer, an ink layer and an optional comparison layer. The manifest says which file is which, the voxel size, and who made the data.</p>
176
+ <p><button class="chip" id="oExample">Download example package</button> <a href="https://huggingface.co/spaces/SharpMeow/unroll/blob/main/docs/ADDING_A_SCROLL.md#open-your-own" target="_blank" rel="noopener">How to make one</a></p>
177
+ <p class="mono dim small" id="oLimits"></p>
178
+ </div>
179
+ </section>
180
+
181
  <section id="about" class="sheet about" hidden>
182
  <div class="sheet-head">
183
  <div><div class="mono dim">ABOUT</div><h2>What you are looking at</h2></div>
 
185
  </div>
186
  <div class="about-body">
187
  <p>PHerc. 139 is one of the papyrus rolls carbonized when Vesuvius buried Herculaneum in 79 CE. It is too fragile to open, so it was scanned with X‑rays at the ESRF synchrotron in Grenoble. It is held by the Biblioteca Nazionale di Napoli.</p>
188
+ <p>Each sheet in the 3D view is one winding of the roll, traced through the CT volume by the <a href="https://scrollprize.org" target="_blank" rel="noopener">Vesuvius Challenge</a>. The shapes are the real ones, from the public 9.362 µm meshes. The <b>X‑ray</b> layer is the CT intensity on each surface. The <b>Published ink (2.4 µm)</b> layer is the Vesuvius Challenge's public ink detection on the 2.4 µm scan. In 3D it is drawn through a local‑contrast filter so letter‑sized strokes stand out; the close‑up view shows the published preview unfiltered, downscaled to 2,400 px.</p>
189
  <p id="aboutGpu" hidden></p>
190
  <p>Unrolling lays the windings end to end, outermost first, the way a reader would open the roll. Each traced winding runs a little past one full turn, so roughly a tenth of the 2.8 m strip repeats surface from its neighbour.</p>
191
  <p class="mono dim small">Sources: open data bucket <code>PHerc0139/segments/*/mesh/*9.362um.tifxyz</code>, <code>surface-volumes/9.362um…zarr</code> and <code>ink-detection/downsampled</code>. Data: Giorgio Angelotti, Stephen Parsons, Sean Johnson, Elian Rafael Dal Prà, Johannes Rudolph, Paul Tafforeau, Alessandro Mirone, Paul Henderson, Hendrik Schilling, Forrest McDonald, David Josey, Youssef Nader, C. Seth Parker, W. Brent Seales. <i>Vesuvius Challenge - CT Scans of Herculaneum Papyri.</i> Vesuvius Challenge. Licensed <a href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank" rel="noopener">CC BY‑NC 4.0</a>. The page's code (HTML, CSS, JS and <code>tools/</code>) is MIT; see the Space's README.</p>
lib/example.js ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // A small synthetic scroll, generated in the browser: three windings of a spiral with UVs,
2
+ // one OBJ per winding (and one PLY), X-ray, ink and overlay images in PNG, JPG and TIFF.
3
+ // Used for the "Download example package" button and for testing "Open your own".
4
+ import { writeZip } from './formats.js';
5
+
6
+ const IDS = ['s03', 's02', 's01']; // outermost first
7
+ const H = 30, TURN = 1.08, R0 = 13, PITCH = 2.2;
8
+
9
+ function spiral(j) {
10
+ // winding j (0 outermost): a little more than one turn of an Archimedean spiral, wavy like real papyrus
11
+ const C = 72, R = 13, v = [], t = [], f = [];
12
+ for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
13
+ const u = c / (C - 1), h = r / (R - 1);
14
+ const th = -(j + u * TURN) * 2 * Math.PI;
15
+ const rad = R0 - PITCH * (j + u * TURN) + 0.25 * Math.sin(u * 23 + h * 5);
16
+ v.push([rad * Math.cos(th), (0.5 - h) * H + 0.6 * Math.sin(u * 9), rad * Math.sin(th)]);
17
+ t.push([u, 1 - h]);
18
+ }
19
+ for (let r = 0; r + 1 < R; r++) for (let c = 0; c + 1 < C; c++) {
20
+ const a = r * C + c;
21
+ f.push([a, a + C, a + 1], [a + 1, a + C, a + C + 1]);
22
+ }
23
+ return { v, t, f };
24
+ }
25
+ function obj({ v, t, f }, id) {
26
+ const L = [`# synthetic winding ${id}, millimetres, roll axis along y`];
27
+ for (const p of v) L.push(`v ${p.map((x) => x.toFixed(4)).join(' ')}`);
28
+ for (const q of t) L.push(`vt ${q.map((x) => x.toFixed(5)).join(' ')}`);
29
+ for (const k of f) L.push(`f ${k.map((i) => `${i + 1}/${i + 1}`).join(' ')}`);
30
+ return new TextEncoder().encode(L.join('\n') + '\n');
31
+ }
32
+ function ply({ v, t, f }) {
33
+ const head = `ply\nformat binary_little_endian 1.0\ncomment synthetic winding\nelement vertex ${v.length}\nproperty float x\nproperty float y\nproperty float z\nproperty float s\nproperty float t\nelement face ${f.length}\nproperty list uchar int vertex_indices\nend_header\n`;
34
+ const hb = new TextEncoder().encode(head);
35
+ const buf = new ArrayBuffer(hb.length + v.length * 20 + f.length * 13);
36
+ new Uint8Array(buf).set(hb);
37
+ const dv = new DataView(buf); let o = hb.length;
38
+ v.forEach((p, i) => { for (const x of [...p, ...t[i]]) { dv.setFloat32(o, x, true); o += 4; } });
39
+ for (const k of f) { dv.setUint8(o++, 3); for (const i of k) { dv.setInt32(o, i, true); o += 4; } }
40
+ return new Uint8Array(buf);
41
+ }
42
+ function canvas(w, h) { const c = document.createElement('canvas'); c.width = w; c.height = h; return [c, c.getContext('2d')]; }
43
+ let seed = 7;
44
+ const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
45
+ function ctImage(w, h) {
46
+ const [c, g] = canvas(w, h);
47
+ g.fillStyle = '#2a2a2a'; g.fillRect(0, 0, w, h);
48
+ for (let i = 0; i < 900; i++) { const y = rnd() * h; g.strokeStyle = `rgba(${150 + rnd() * 100 | 0},${150 + rnd() * 100 | 0},${150 + rnd() * 100 | 0},${0.08 + rnd() * 0.2})`; g.lineWidth = 1 + rnd() * 2; g.beginPath(); g.moveTo(0, y); g.lineTo(w, y + (rnd() - 0.5) * 6); g.stroke(); }
49
+ for (let i = 0; i < 400; i++) { const x = rnd() * w; g.strokeStyle = `rgba(200,200,200,${0.04 + rnd() * 0.1})`; g.beginPath(); g.moveTo(x, 0); g.lineTo(x + (rnd() - 0.5) * 6, h); g.stroke(); }
50
+ return c;
51
+ }
52
+ function inkImage(w, h, text, blur) {
53
+ const [c, g] = canvas(w, h);
54
+ g.fillStyle = '#000'; g.fillRect(0, 0, w, h);
55
+ g.fillStyle = '#fff'; g.filter = blur ? `blur(${blur}px)` : 'none';
56
+ g.font = `${Math.round(h * 0.13)}px Georgia, serif`;
57
+ const lines = text.split('\n');
58
+ lines.forEach((l, i) => g.fillText(l, w * 0.06, h * (0.2 + i * 0.17)));
59
+ return c;
60
+ }
61
+ const png = (c) => new Promise((ok) => c.toBlob(async (b) => ok(new Uint8Array(await b.arrayBuffer())), 'image/png'));
62
+ const jpg = (c) => new Promise((ok) => c.toBlob(async (b) => ok(new Uint8Array(await b.arrayBuffer())), 'image/jpeg', 0.9));
63
+ function tif(c) {
64
+ // 8-bit greyscale, uncompressed, one strip
65
+ const g = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;
66
+ const W = c.width, Hh = c.height, n = W * Hh, tags = [[256, 3, W], [257, 3, Hh], [258, 3, 8], [259, 3, 1], [262, 3, 1], [273, 4, 8 + 2 + 10 * 12 + 4], [277, 3, 1], [278, 3, Hh], [279, 4, n], [284, 3, 1]];
67
+ const buf = new ArrayBuffer(8 + 2 + tags.length * 12 + 4 + n); const dv = new DataView(buf);
68
+ dv.setUint16(0, 0x4949); dv.setUint16(2, 42, true); dv.setUint32(4, 8, true); dv.setUint16(8, tags.length, true);
69
+ tags.forEach(([t, ty, v], i) => { const o = 10 + i * 12; dv.setUint16(o, t, true); dv.setUint16(o + 2, ty, true); dv.setUint32(o + 4, 1, true); if (ty === 3) dv.setUint16(o + 8, v, true); else dv.setUint32(o + 8, v, true); });
70
+ const px = new Uint8Array(buf, 8 + 2 + tags.length * 12 + 4);
71
+ for (let i = 0; i < n; i++) px[i] = g[i * 4];
72
+ return new Uint8Array(buf);
73
+ }
74
+
75
+ export const EXAMPLE_TEXT = { s03: 'ΒΙΟΣ ΓΑΡ\nΟΥ ΒΙΩΤΟΣ\nΑΝΕΞΕΤΑΣΤΟΣ', s02: 'ΗΔΟΝΗ ΚΑΙ\nΑΤΑΡΑΞΙΑ\nΦΙΛΟΔΗΜΟΣ', s01: 'ΤΕΛΟΣ ΤΟΥ\nΒΙΒΛΙΟΥ\nΕΡΡΩΣΘΕ' };
76
+
77
+ export async function exampleFiles() {
78
+ seed = 7;
79
+ const files = [];
80
+ const add = (name, bytes) => files.push({ name: `synthetic-scroll/${name}`, bytes });
81
+ for (const [j, id] of IDS.entries()) {
82
+ const s = spiral(j);
83
+ add(`meshes/${id}.${id === 's02' ? 'ply' : 'obj'}`, id === 's02' ? ply(s) : obj(s, id));
84
+ const w = Math.round(2 * Math.PI * (R0 - PITCH * (j + TURN / 2)) * TURN * 8), h = H * 8;
85
+ add(`xray/${id}.png`, await png(ctImage(w, h)));
86
+ const ink = inkImage(w, h, EXAMPLE_TEXT[id], 0);
87
+ add(`ink/${id}.${id === 's01' ? 'tif' : id === 's02' ? 'jpg' : 'png'}`, id === 's01' ? tif(ink) : id === 's02' ? await jpg(ink) : await png(ink));
88
+ if (id === 's02') add(`overlay/${id}.png`, await png(inkImage(w, h, EXAMPLE_TEXT[id], 3)));
89
+ }
90
+ const manifest = {
91
+ schema: 'unroll-scroll/1',
92
+ id: 'synthetic-example',
93
+ name: 'Synthetic example scroll',
94
+ description: 'Three windings of a made-up spiral, with fake X-ray fibres and Greek text as ink. For testing "Open your own".',
95
+ voxelMM: 0.01,
96
+ geometry: { format: 'mesh', units: 'mm', axis: 'y' },
97
+ windings: [{ id: 's03', mesh: 'meshes/s03.obj' }, { id: 's02', mesh: 'meshes/s02.ply' }, { id: 's01', mesh: 'meshes/s01.obj' }],
98
+ outermost: 'first',
99
+ layers: [
100
+ { id: 'xray', role: 'ct', label: 'X-ray', texture: 'xray/{id}.png', source: 'Synthetic fibre noise', resolutionUM: 125 },
101
+ { id: 'ink', role: 'ink', label: 'Ink', texture: 'ink/{id}.png', source: 'Synthetic text', resolutionUM: 125 },
102
+ { id: 'model', role: 'overlay', label: 'Blurred ink', windings: ['s02'], texture: 'overlay/{id}.png', source: 'The ink layer, blurred, to show the compare swipe', resolutionUM: 125 },
103
+ ],
104
+ credits: { text: 'Generated by the Unroll page', url: 'https://huggingface.co/spaces/SharpMeow/unroll' },
105
+ dataTerms: { license: 'CC0 1.0', url: 'https://creativecommons.org/publicdomain/zero/1.0/' },
106
+ };
107
+ // the ink files use three formats on purpose: per-winding paths are listed in "files" overrides
108
+ manifest.layers[1].texture = 'ink/{id}.png';
109
+ manifest.layers[1].files = { s02: 'ink/s02.jpg', s01: 'ink/s01.tif' };
110
+ add('manifest.json', new TextEncoder().encode(JSON.stringify(manifest, null, 1)));
111
+ add('README.txt', new TextEncoder().encode('Synthetic example for Unroll (huggingface.co/spaces/SharpMeow/unroll).\nOpen the page, press + (Open your own) and drop this zip or the whole folder.\nEverything stays in your browser. See docs/ADDING_A_SCROLL.md for the manifest format.\n'));
112
+ return files;
113
+ }
114
+ export async function exampleZip() { return writeZip(await exampleFiles()); }
lib/formats.js ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // File formats for "Open your own", all decoded in the browser: OBJ and PLY meshes with UVs,
2
+ // baseline TIFF images, and zip archives (read and write). No dependencies.
3
+
4
+ // ------------------------------------------------------------ meshes
5
+ // Both parsers return { pos: Float32Array (xyz), uv: Float32Array (uv), index: Uint32Array, vertices, faces }.
6
+ // A vertex is a unique (position, uv) pair; polygons are fanned into triangles.
7
+
8
+ export function parseOBJ(text) {
9
+ const P = [], T = [], key = new Map(), pos = [], uv = [], idx = [];
10
+ let line = 0;
11
+ const vert = (tok) => {
12
+ const k = tok;
13
+ let v = key.get(k);
14
+ if (v !== undefined) return v;
15
+ const [a, b] = tok.split('/');
16
+ let pi = parseInt(a, 10), ti = parseInt(b, 10);
17
+ if (!Number.isFinite(pi)) throw new Error(`OBJ line ${line}: bad face vertex "${tok}"`);
18
+ if (!Number.isFinite(ti)) throw new Error(`OBJ line ${line}: face vertex "${tok}" has no texture coordinate. Every face needs v/vt indices (UVs).`);
19
+ pi = pi < 0 ? P.length / 3 + pi : pi - 1;
20
+ ti = ti < 0 ? T.length / 2 + ti : ti - 1;
21
+ if (pi < 0 || pi * 3 >= P.length) throw new Error(`OBJ line ${line}: vertex index out of range`);
22
+ if (ti < 0 || ti * 2 >= T.length) throw new Error(`OBJ line ${line}: texture index out of range`);
23
+ v = pos.length / 3;
24
+ pos.push(P[pi * 3], P[pi * 3 + 1], P[pi * 3 + 2]);
25
+ uv.push(T[ti * 2], T[ti * 2 + 1]);
26
+ key.set(k, v);
27
+ return v;
28
+ };
29
+ let i0 = 0;
30
+ while (i0 < text.length) {
31
+ let i1 = text.indexOf('\n', i0);
32
+ if (i1 < 0) i1 = text.length;
33
+ const s = text.slice(i0, i1).trim();
34
+ i0 = i1 + 1; line++;
35
+ if (!s || s[0] === '#') continue;
36
+ const t = s.split(/\s+/);
37
+ if (t[0] === 'v') P.push(+t[1], +t[2], +t[3]);
38
+ else if (t[0] === 'vt') T.push(+t[1], +(t[2] ?? 0));
39
+ else if (t[0] === 'f') {
40
+ const f = t.slice(1).map(vert);
41
+ for (let k = 1; k + 1 < f.length; k++) idx.push(f[0], f[k], f[k + 1]);
42
+ }
43
+ }
44
+ if (!P.length) throw new Error('OBJ has no vertices ("v" lines).');
45
+ if (!T.length) throw new Error('OBJ has no texture coordinates ("vt" lines). The mesh needs UVs to place the image layers.');
46
+ if (!idx.length) throw new Error('OBJ has no faces ("f" lines).');
47
+ return finish(pos, uv, idx);
48
+ }
49
+
50
+ function finish(pos, uv, idx) {
51
+ const out = { pos: Float32Array.from(pos), uv: Float32Array.from(uv), index: Uint32Array.from(idx) };
52
+ out.vertices = out.pos.length / 3; out.faces = out.index.length / 3;
53
+ for (let i = 0; i < out.pos.length; i++) if (!Number.isFinite(out.pos[i])) throw new Error('The mesh has a vertex with a non-numeric coordinate.');
54
+ for (let i = 0; i < out.uv.length; i++) if (!Number.isFinite(out.uv[i])) throw new Error('The mesh has a non-numeric texture coordinate.');
55
+ return out;
56
+ }
57
+
58
+ const PLY_TYPES = {
59
+ char: ['getInt8', 1], int8: ['getInt8', 1], uchar: ['getUint8', 1], uint8: ['getUint8', 1],
60
+ short: ['getInt16', 2], int16: ['getInt16', 2], ushort: ['getUint16', 2], uint16: ['getUint16', 2],
61
+ int: ['getInt32', 4], int32: ['getInt32', 4], uint: ['getUint32', 4], uint32: ['getUint32', 4],
62
+ float: ['getFloat32', 4], float32: ['getFloat32', 4], double: ['getFloat64', 8], float64: ['getFloat64', 8],
63
+ };
64
+
65
+ export function parsePLY(buf) {
66
+ const u8 = new Uint8Array(buf);
67
+ const head = new TextDecoder().decode(u8.subarray(0, Math.min(u8.length, 8192)));
68
+ const end = head.indexOf('end_header');
69
+ if (!head.startsWith('ply') || end < 0) throw new Error('Not a PLY file (no "ply" header).');
70
+ const hlen = head.indexOf('\n', end) + 1;
71
+ const lines = head.slice(0, hlen).split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
72
+ let fmt = null; const els = [];
73
+ for (const l of lines) {
74
+ const t = l.split(/\s+/);
75
+ if (t[0] === 'format') fmt = t[1];
76
+ else if (t[0] === 'element') els.push({ name: t[1], n: +t[2], props: [] });
77
+ else if (t[0] === 'property') {
78
+ const e = els[els.length - 1];
79
+ if (t[1] === 'list') e.props.push({ list: true, ct: t[2], it: t[3], name: t[4] });
80
+ else e.props.push({ type: t[1], name: t[2] });
81
+ }
82
+ }
83
+ if (!['ascii', 'binary_little_endian', 'binary_big_endian'].includes(fmt)) throw new Error(`PLY format "${fmt}" is not supported.`);
84
+ const V = els.find((e) => e.name === 'vertex');
85
+ if (!V) throw new Error('PLY has no vertex element.');
86
+ const pn = V.props.map((p) => p.name);
87
+ const uName = ['u', 's', 'texture_u', 'texture_s'].find((n) => pn.includes(n));
88
+ const vName = ['v', 't', 'texture_v', 'texture_t'].find((n) => pn.includes(n));
89
+ if (!uName || !vName) throw new Error('PLY vertices have no texture coordinates (u, v or s, t). The mesh needs UVs to place the image layers.');
90
+ const pos = new Float32Array(V.n * 3), uv = new Float32Array(V.n * 2), idx = [];
91
+ const store = (e, i, rec) => {
92
+ if (e === V) {
93
+ pos[i * 3] = rec.x; pos[i * 3 + 1] = rec.y; pos[i * 3 + 2] = rec.z;
94
+ uv[i * 2] = rec[uName]; uv[i * 2 + 1] = rec[vName];
95
+ } else if (e.name === 'face') {
96
+ const f = rec.vertex_indices || rec.vertex_index;
97
+ if (!f) throw new Error('PLY faces have no vertex_indices list.');
98
+ for (let k = 1; k + 1 < f.length; k++) idx.push(f[0], f[k], f[k + 1]);
99
+ }
100
+ };
101
+ if (fmt === 'ascii') {
102
+ const body = new TextDecoder().decode(u8.subarray(hlen)).split(/\s+/).filter(Boolean);
103
+ let p = 0;
104
+ for (const e of els) for (let i = 0; i < e.n; i++) {
105
+ const rec = {};
106
+ for (const pr of e.props) {
107
+ if (pr.list) { const n = +body[p++]; rec[pr.name] = body.slice(p, p + n).map(Number); p += n; }
108
+ else rec[pr.name] = +body[p++];
109
+ }
110
+ store(e, i, rec);
111
+ }
112
+ } else {
113
+ const dv = new DataView(buf, 0), le = fmt === 'binary_little_endian';
114
+ let o = hlen;
115
+ const rd = (type) => { const [fn, n] = PLY_TYPES[type] || []; if (!fn) throw new Error(`PLY type "${type}" is not supported.`); const v = dv[fn](o, le); o += n; return v; };
116
+ for (const e of els) for (let i = 0; i < e.n; i++) {
117
+ const rec = {};
118
+ for (const pr of e.props) {
119
+ if (pr.list) { const n = rd(pr.ct); const a = new Array(n); for (let k = 0; k < n; k++) a[k] = rd(pr.it); rec[pr.name] = a; }
120
+ else rec[pr.name] = rd(pr.type);
121
+ }
122
+ if (o > buf.byteLength) throw new Error('PLY file ends early.');
123
+ store(e, i, rec);
124
+ }
125
+ }
126
+ for (const k of idx) if (k >= V.n) throw new Error('PLY face index out of range.');
127
+ if (!idx.length) throw new Error('PLY has no faces.');
128
+ return finish(pos, uv, idx);
129
+ }
130
+
131
+ // ------------------------------------------------------------ TIFF
132
+ // Baseline TIFF: 8, 16 or 32 bit (int or float), 1 to 4 samples, strips or tiles,
133
+ // no compression, LZW, Deflate or PackBits, horizontal predictor. Returns ImageData (RGBA, 8 bit).
134
+
135
+ export async function decodeTIFF(buf, maxSide = 8192) {
136
+ const dv = new DataView(buf);
137
+ const bo = dv.getUint16(0);
138
+ if (bo !== 0x4949 && bo !== 0x4d4d) throw new Error('Not a TIFF file.');
139
+ const le = bo === 0x4949;
140
+ if (dv.getUint16(2, le) === 43) throw new Error('BigTIFF is not supported; save as a standard TIFF or PNG.');
141
+ const ifd = dv.getUint32(4, le);
142
+ const n = dv.getUint16(ifd, le);
143
+ const tags = {};
144
+ const SZ = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8, 16: 8 };
145
+ for (let i = 0; i < n; i++) {
146
+ const e = ifd + 2 + i * 12;
147
+ const tag = dv.getUint16(e, le), type = dv.getUint16(e + 2, le), cnt = dv.getUint32(e + 4, le);
148
+ const size = (SZ[type] || 1) * cnt;
149
+ const off = size <= 4 ? e + 8 : dv.getUint32(e + 8, le);
150
+ const vals = [];
151
+ for (let k = 0; k < Math.min(cnt, 1 << 20); k++) {
152
+ if (type === 3) vals.push(dv.getUint16(off + k * 2, le));
153
+ else if (type === 4) vals.push(dv.getUint32(off + k * 4, le));
154
+ else if (type === 1 || type === 7) vals.push(dv.getUint8(off + k));
155
+ else if (type === 16) vals.push(Number(dv.getBigUint64(off + k * 8, le)));
156
+ else break;
157
+ }
158
+ tags[tag] = vals;
159
+ }
160
+ const W = tags[256]?.[0], H = tags[257]?.[0];
161
+ if (!W || !H) throw new Error('TIFF has no width or height.');
162
+ if (W > maxSide || H > maxSide) throw new Error(`TIFF is ${W} x ${H} px; the limit is ${maxSide} px on a side.`);
163
+ const bps = tags[258]?.[0] || 1, spp = tags[277]?.[0] || 1, comp = tags[259]?.[0] || 1;
164
+ const pred = tags[317]?.[0] || 1, fmt = tags[339]?.[0] || 1, photo = tags[262]?.[0] ?? 1;
165
+ if (![8, 16, 32].includes(bps)) throw new Error(`TIFF with ${bps} bits per sample is not supported (use 8, 16 or 32).`);
166
+ if ((tags[284]?.[0] || 1) !== 1 && spp > 1) throw new Error('Planar TIFF is not supported.');
167
+ if (photo === 3) throw new Error('Palette TIFF is not supported.');
168
+ const tiled = !!tags[322];
169
+ const tw = tiled ? tags[322][0] : W, th = tiled ? tags[323][0] : (tags[278]?.[0] || H);
170
+ const offs = tiled ? tags[324] : tags[273], cnts = tiled ? tags[325] : tags[279];
171
+ if (!offs || !cnts) throw new Error('TIFF has no image data offsets.');
172
+ const B = bps / 8, rowB = tw * spp * B;
173
+ const raw = new Uint8Array(W * H * spp * B);
174
+ const across = Math.ceil(W / tw);
175
+ for (let c = 0; c < offs.length; c++) {
176
+ let chunk = new Uint8Array(buf, offs[c], cnts[c]);
177
+ if (comp === 5) chunk = lzw(chunk, rowB * th);
178
+ else if (comp === 8 || comp === 32946) chunk = await inflate(chunk, 'deflate');
179
+ else if (comp === 32773) chunk = packbits(chunk, rowB * th);
180
+ else if (comp !== 1) throw new Error(`TIFF compression ${comp} is not supported (use none, LZW or Deflate).`);
181
+ const x0 = tiled ? (c % across) * tw : 0, y0 = tiled ? Math.floor(c / across) * th : c * th;
182
+ for (let y = 0; y < th && y0 + y < H; y++) {
183
+ const row = chunk.subarray(y * rowB, (y + 1) * rowB);
184
+ if (pred === 2) {
185
+ if (B === 1) for (let i = spp; i < row.length; i++) row[i] = (row[i] + row[i - spp]) & 255;
186
+ else if (B === 2) { const d = new DataView(row.buffer, row.byteOffset, row.length); for (let i = spp; i < tw * spp; i++) d.setUint16(i * 2, (d.getUint16(i * 2, le) + d.getUint16((i - spp) * 2, le)) & 65535, le); }
187
+ }
188
+ const w = Math.min(tw, W - x0) * spp * B;
189
+ raw.set(row.subarray(0, w), ((y0 + y) * W + x0) * spp * B);
190
+ }
191
+ }
192
+ // to 8-bit RGBA, stretching 16- and 32-bit data to the range it actually uses
193
+ const N = W * H, d = new DataView(raw.buffer);
194
+ const get = B === 1 ? (i) => raw[i] : B === 2 ? (i) => d.getUint16(i * 2, le)
195
+ : fmt === 3 ? (i) => d.getFloat32(i * 4, le) : (i) => d.getUint32(i * 4, le);
196
+ let lo = 0, hi = 255;
197
+ if (B > 1) {
198
+ lo = Infinity; hi = -Infinity;
199
+ for (let i = 0; i < N * spp; i += Math.max(1, Math.floor(N * spp / 200000))) { const v = get(i); if (Number.isFinite(v)) { if (v < lo) lo = v; if (v > hi) hi = v; } }
200
+ if (!(hi > lo)) { lo = 0; hi = 1; }
201
+ }
202
+ const k = 255 / (hi - lo);
203
+ const out = new Uint8ClampedArray(N * 4);
204
+ for (let p = 0; p < N; p++) {
205
+ const s = p * spp;
206
+ const r = (get(s) - lo) * k;
207
+ const g = spp >= 3 ? (get(s + 1) - lo) * k : r, b = spp >= 3 ? (get(s + 2) - lo) * k : r;
208
+ const a = spp === 4 ? (get(s + 3) - lo) * k : spp === 2 ? (get(s + 1) - lo) * k : 255;
209
+ const inv = photo === 0 ? 255 : 0;
210
+ out[p * 4] = Math.abs(inv - r); out[p * 4 + 1] = Math.abs(inv - g); out[p * 4 + 2] = Math.abs(inv - b); out[p * 4 + 3] = a;
211
+ }
212
+ return new ImageData(out, W, H);
213
+ }
214
+
215
+ function lzw(src, expect) {
216
+ const out = new Uint8Array(Math.max(expect, 16));
217
+ let o = 0, bit = 0, size = 9;
218
+ let dict = [];
219
+ const reset = () => { dict = []; for (let i = 0; i < 256; i++) dict.push([i]); dict.push(null, null); size = 9; };
220
+ const read = () => {
221
+ let v = 0;
222
+ for (let i = 0; i < size; i++) { const B = src[(bit + i) >> 3]; v = (v << 1) | ((B >> (7 - ((bit + i) & 7))) & 1); }
223
+ bit += size; return v;
224
+ };
225
+ reset();
226
+ let prev = null;
227
+ while ((bit + size) <= src.length * 8) {
228
+ const c = read();
229
+ if (c === 257) break;
230
+ if (c === 256) { reset(); prev = null; continue; }
231
+ let e;
232
+ if (c < dict.length && dict[c]) e = dict[c];
233
+ else if (prev) e = prev.concat(prev[0]);
234
+ else throw new Error('Damaged LZW data in TIFF.');
235
+ for (const x of e) { if (o < out.length) out[o++] = x; }
236
+ if (prev) dict.push(prev.concat(e[0]));
237
+ prev = e;
238
+ if (dict.length + 1 >= (1 << size) && size < 12) size++;
239
+ }
240
+ return out;
241
+ }
242
+
243
+ function packbits(src, expect) {
244
+ const out = new Uint8Array(expect); let o = 0, i = 0;
245
+ while (i < src.length && o < expect) {
246
+ const n = (src[i++] << 24) >> 24;
247
+ if (n >= 0) { for (let k = 0; k <= n; k++) out[o++] = src[i++]; }
248
+ else if (n !== -128) { const v = src[i++]; for (let k = 0; k < 1 - n; k++) out[o++] = v; }
249
+ }
250
+ return out;
251
+ }
252
+
253
+ async function inflate(bytes, fmt) {
254
+ const ds = new DecompressionStream(fmt);
255
+ const r = new Response(new Blob([bytes]).stream().pipeThrough(ds));
256
+ return new Uint8Array(await r.arrayBuffer());
257
+ }
258
+
259
+ // ------------------------------------------------------------ zip
260
+
261
+ export async function readZip(buf, limits) {
262
+ const u8 = new Uint8Array(buf), dv = new DataView(buf);
263
+ let eocd = -1;
264
+ for (let i = u8.length - 22; i >= Math.max(0, u8.length - 65557); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
265
+ if (eocd < 0) throw new Error('This is not a zip file, or it is damaged.');
266
+ const count = dv.getUint16(eocd + 10, true);
267
+ let p = dv.getUint32(eocd + 16, true);
268
+ const files = [];
269
+ let total = 0;
270
+ for (let n = 0; n < count; n++) {
271
+ if (dv.getUint32(p, true) !== 0x02014b50) throw new Error('Damaged zip directory.');
272
+ const method = dv.getUint16(p + 10, true), csize = dv.getUint32(p + 20, true), usize = dv.getUint32(p + 24, true);
273
+ const nl = dv.getUint16(p + 28, true), xl = dv.getUint16(p + 30, true), cl = dv.getUint16(p + 32, true);
274
+ const flags = dv.getUint16(p + 8, true);
275
+ const lho = dv.getUint32(p + 42, true);
276
+ const name = new TextDecoder().decode(u8.subarray(p + 46, p + 46 + nl));
277
+ p += 46 + nl + xl + cl;
278
+ if (name.endsWith('/')) continue;
279
+ if (flags & 1) throw new Error(`${name} in the zip is encrypted.`);
280
+ if (usize === 0xffffffff || csize === 0xffffffff) throw new Error('Zip64 archives are not supported.');
281
+ if (limits && usize > limits.maxFileBytes) throw new Error(`${name} is ${(usize / 1e6).toFixed(1)} MB unzipped; the limit per file is ${(limits.maxFileBytes / 1048576).toFixed(0)} MB.`);
282
+ total += usize;
283
+ if (limits && total > limits.maxTotalBytes) throw new Error(`The zip unpacks to more than ${(limits.maxTotalBytes / 1048576).toFixed(0)} MB.`);
284
+ const ln = dv.getUint16(lho + 26, true), lx = dv.getUint16(lho + 28, true);
285
+ const data = u8.subarray(lho + 30 + ln + lx, lho + 30 + ln + lx + csize);
286
+ let bytes;
287
+ if (method === 0) bytes = data.slice();
288
+ else if (method === 8) bytes = await inflate(data, 'deflate-raw');
289
+ else throw new Error(`${name} uses zip compression method ${method}; only stored and deflated files are supported.`);
290
+ files.push({ name, blob: new Blob([bytes]), size: bytes.length });
291
+ }
292
+ return files;
293
+ }
294
+
295
+ const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
296
+ function crc32(u8) { let c = 0xffffffff; for (let i = 0; i < u8.length; i++) c = CRC[(c ^ u8[i]) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }
297
+
298
+ // a stored (uncompressed) zip from [{ name, bytes: Uint8Array }]
299
+ export function writeZip(entries) {
300
+ const enc = new TextEncoder();
301
+ const parts = [], cen = [];
302
+ let off = 0;
303
+ for (const e of entries) {
304
+ const name = enc.encode(e.name), crc = crc32(e.bytes), n = e.bytes.length;
305
+ const h = new DataView(new ArrayBuffer(30));
306
+ h.setUint32(0, 0x04034b50, true); h.setUint16(4, 20, true); h.setUint16(6, 0x0800, true);
307
+ h.setUint32(14, crc, true); h.setUint32(18, n, true); h.setUint32(22, n, true); h.setUint16(26, name.length, true);
308
+ parts.push(new Uint8Array(h.buffer), name, e.bytes);
309
+ const c = new DataView(new ArrayBuffer(46));
310
+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x0800, true);
311
+ c.setUint32(16, crc, true); c.setUint32(20, n, true); c.setUint32(24, n, true); c.setUint16(28, name.length, true); c.setUint32(42, off, true);
312
+ cen.push(new Uint8Array(c.buffer), name);
313
+ off += 30 + name.length + n;
314
+ }
315
+ const csz = cen.reduce((a, b) => a + b.length, 0);
316
+ const z = new DataView(new ArrayBuffer(22));
317
+ z.setUint32(0, 0x06054b50, true); z.setUint16(8, entries.length, true); z.setUint16(10, entries.length, true);
318
+ z.setUint32(12, csz, true); z.setUint32(16, off, true);
319
+ return new Blob([...parts, ...cen, new Uint8Array(z.buffer)], { type: 'application/zip' });
320
+ }
lib/manifest.js ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Scroll manifest: schema helpers and the validator.
2
+ // Shared by the page (registry scrolls and "Open your own") and by tools/validate_scroll.mjs in Node.
3
+ // Pure JavaScript, no DOM, no dependencies.
4
+
5
+ export const SCHEMA = 'unroll-scroll/1';
6
+
7
+ // limits for scrolls opened in the browser ("Open your own"); registry scrolls are checked against REGISTRY_LIMITS
8
+ export const LOCAL_LIMITS = {
9
+ maxFileBytes: 64 * 1024 * 1024, // any single file
10
+ maxTotalBytes: 256 * 1024 * 1024, // everything together, after unzipping
11
+ maxZipBytes: 128 * 1024 * 1024, // a zip as dropped or downloaded
12
+ maxWindings: 64,
13
+ maxVertices: 2000000, // all windings together
14
+ maxTextureSide: 8192,
15
+ };
16
+ export const REGISTRY_LIMITS = { ...LOCAL_LIMITS, maxWindings: 400, maxFileBytes: 200 * 1024 * 1024, maxTotalBytes: 2e9 };
17
+
18
+ export const MESH_EXT = ['obj', 'ply'];
19
+ export const IMAGE_EXT = ['png', 'jpg', 'jpeg', 'webp', 'tif', 'tiff'];
20
+ export const ROLES = ['ct', 'ink', 'overlay'];
21
+ export const FORMATS = ['grid-int16', 'mesh'];
22
+
23
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
24
+ const WID_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,31}$/;
25
+
26
+ export const ext = (p) => (String(p).split(/[?#]/)[0].match(/\.([A-Za-z0-9]+)$/) || [, ''])[1].toLowerCase();
27
+ export const fill = (pattern, id) => String(pattern).split('{id}').join(id);
28
+
29
+ // "w023".."w059" -> ["w023", ..., "w059"]: same prefix, numeric tail, zero padding kept
30
+ export function expandRange(a, b) {
31
+ const ma = /^(.*?)(\d+)$/.exec(a), mb = /^(.*?)(\d+)$/.exec(b);
32
+ if (!ma || !mb || ma[1] !== mb[1]) throw new Error(`range ${a} to ${b}: both ends need the same prefix and a number at the end`);
33
+ const lo = +ma[2], hi = +mb[2], pad = ma[2].length;
34
+ if (hi < lo) throw new Error(`range ${a} to ${b}: the end comes before the start`);
35
+ if (hi - lo > 5000) throw new Error(`range ${a} to ${b} is too long`);
36
+ const out = [];
37
+ for (let i = lo; i <= hi; i++) out.push(ma[1] + String(i).padStart(pad, '0'));
38
+ return out;
39
+ }
40
+
41
+ // the manifest's windings, as a list of { id, mesh? } in the manifest's own order
42
+ export function listWindings(m) {
43
+ const W = m.windings;
44
+ if (Array.isArray(W)) return W.map((w) => (typeof w === 'string' ? { id: w } : { ...w }));
45
+ if (W && Array.isArray(W.range)) {
46
+ const skip = new Set(W.skip || []);
47
+ return expandRange(W.range[0], W.range[1]).filter((id) => !skip.has(id))
48
+ .map((id) => ({ id, ...(W.mesh ? { mesh: fill(W.mesh, id) } : {}) }));
49
+ }
50
+ return [];
51
+ }
52
+
53
+ // peel order, outermost first: what the page unrolls from left to right
54
+ export function peelOrder(m) {
55
+ const ws = listWindings(m);
56
+ const outer = (m.windings && !Array.isArray(m.windings) && m.windings.outermost) || m.outermost || 'first';
57
+ return outer === 'last' ? ws.reverse() : ws;
58
+ }
59
+
60
+ // which windings a layer covers: "all", { "range": [a, b] } or a list of ids
61
+ export function layerWindings(layer, allIds) {
62
+ const w = layer.windings ?? 'all';
63
+ if (w === 'all') return [...allIds];
64
+ if (w && Array.isArray(w.range)) return expandRange(w.range[0], w.range[1]).filter((id) => allIds.includes(id));
65
+ if (Array.isArray(w)) return w.filter((id) => allIds.includes(id));
66
+ throw new Error('"windings" must be "all", { "range": [first, last] } or a list of ids');
67
+ }
68
+
69
+ // a layer's image for one winding: an entry in "files" wins over the "texture" pattern
70
+ export const layerFile = (layer, id) => (layer.files && layer.files[id]) || fill(layer.texture, id);
71
+
72
+ export const roleOf = (m, role) => (m.layers || []).find((l) => l.role === role) || null;
73
+
74
+ function isRelPath(p, allowParent) {
75
+ if (typeof p !== 'string' || !p.length || p.length > 300) return false;
76
+ if (/^[a-z]+:/i.test(p) || p.startsWith('/') || p.includes('\\')) return false;
77
+ if (!allowParent && p.split('/').includes('..')) return false;
78
+ return true;
79
+ }
80
+
81
+ /**
82
+ * Validate a manifest.
83
+ * opts.trusted: a registry scroll (may use ".." in base and HTML in display fields)
84
+ * opts.limits: LOCAL_LIMITS or REGISTRY_LIMITS
85
+ * opts.fileSize(path) -> number | null | undefined: when given, every referenced file must exist (null means missing)
86
+ * Returns { ok, errors: [string], warnings: [string], files: [path] }
87
+ */
88
+ export function validateManifest(m, opts = {}) {
89
+ const errors = [], warnings = [], files = new Set();
90
+ const lim = opts.limits || (opts.trusted ? REGISTRY_LIMITS : LOCAL_LIMITS);
91
+ const E = (s) => errors.push(s), Wn = (s) => warnings.push(s);
92
+ if (!m || typeof m !== 'object' || Array.isArray(m)) return { ok: false, errors: ['The manifest is not a JSON object.'], warnings, files: [] };
93
+ if (m.schema !== SCHEMA) E(`"schema" must be "${SCHEMA}" (found ${JSON.stringify(m.schema)}).`);
94
+ if (!ID_RE.test(m.id || '')) E('"id" is required: 1 to 64 letters, digits, dot, dash or underscore, starting with a letter or digit.');
95
+ if (typeof m.name !== 'string' || !m.name.trim() || m.name.length > 120) E('"name" is required: a short human name, up to 120 characters.');
96
+ if (!(typeof m.voxelMM === 'number' && m.voxelMM > 0 && m.voxelMM < 10)) E('"voxelMM" is required: the scan voxel size in millimetres, for example 0.009362.');
97
+ if (m.base !== undefined && !(m.base === '' || (isRelPath(m.base.replace(/\/$/, '') || '.', !!opts.trusted)))) E('"base" must be a relative folder path.');
98
+ const g = m.geometry || {};
99
+ if (!FORMATS.includes(g.format)) E(`"geometry.format" must be one of ${FORMATS.join(', ')}.`);
100
+ const ref = (p, what, exts) => {
101
+ if (!isRelPath(p, false)) { E(`${what}: "${p}" is not a valid relative path (no URLs, no leading slash, no "..").`); return; }
102
+ if (exts && !exts.includes(ext(p))) E(`${what}: "${p}" must be a ${exts.map((x) => '.' + x).join(', ')} file.`);
103
+ files.add(p);
104
+ };
105
+ if (g.format === 'grid-int16') {
106
+ if (!opts.trusted) E('The "grid-int16" format is only for scrolls in the site registry. Use "mesh" with OBJ or PLY files.');
107
+ ref(g.index, 'geometry.index', ['json']);
108
+ ref(g.bin, 'geometry.bin', ['bin']);
109
+ }
110
+ if (g.format === 'mesh') {
111
+ if (g.units !== undefined && !['voxels', 'mm'].includes(g.units)) E('"geometry.units" must be "voxels" or "mm".');
112
+ if (g.axis !== undefined && !['z', 'y'].includes(g.axis)) E('"geometry.axis" must be "z" (scan convention: the roll axis is z) or "y".');
113
+ }
114
+ // windings
115
+ let wins = [];
116
+ try { wins = listWindings(m); } catch (e) { E(`windings: ${e.message}`); }
117
+ if (!m.windings) E('"windings" is required: a list of windings, or { "range": ["w001", "w010"] }.');
118
+ else if (!wins.length && !errors.length) E('"windings" lists no windings.');
119
+ if (wins.length > lim.maxWindings) E(`Too many windings: ${wins.length} (the limit is ${lim.maxWindings}).`);
120
+ const seen = new Set();
121
+ for (const w of wins) {
122
+ if (!WID_RE.test(w.id || '')) { E(`Winding id ${JSON.stringify(w.id)} is not valid: 1 to 32 letters, digits, dot, dash or underscore.`); continue; }
123
+ if (seen.has(w.id)) E(`Winding "${w.id}" is listed twice.`);
124
+ seen.add(w.id);
125
+ if (g.format === 'mesh') {
126
+ if (!w.mesh) E(`Winding "${w.id}" needs a "mesh" file (OBJ or PLY).`);
127
+ else ref(w.mesh, `winding ${w.id} mesh`, MESH_EXT);
128
+ }
129
+ }
130
+ const outer = m.windings && !Array.isArray(m.windings) ? m.windings.outermost : m.outermost;
131
+ if (outer !== undefined && !['first', 'last'].includes(outer)) E('"outermost" must be "first" or "last".');
132
+ // layers
133
+ const ids = wins.map((w) => w.id);
134
+ if (!Array.isArray(m.layers) || !m.layers.length) E('"layers" is required: at least one layer with role "ct" or "ink".');
135
+ const roles = new Set();
136
+ for (const [i, l] of (m.layers || []).entries()) {
137
+ const at = `layers[${i}]${l && l.id ? ` (${l.id})` : ''}`;
138
+ if (!l || typeof l !== 'object') { E(`${at} is not an object.`); continue; }
139
+ if (!ROLES.includes(l.role)) { E(`${at}: "role" must be one of ${ROLES.join(', ')}.`); continue; }
140
+ if (roles.has(l.role)) E(`${at}: only one layer per role is shown; "${l.role}" appears twice.`);
141
+ roles.add(l.role);
142
+ if (typeof l.label !== 'string' || !l.label.trim()) E(`${at}: "label" is required.`);
143
+ let cover = [];
144
+ try { cover = layerWindings(l, ids); } catch (e) { E(`${at} windings: ${e.message}`); }
145
+ if (l.windings !== undefined && l.windings !== 'all' && !cover.length) E(`${at}: its "windings" match none of the scroll's windings.`);
146
+ const perWinding = g.format === 'mesh' || l.role === 'overlay';
147
+ if (perWinding) {
148
+ if (l.files !== undefined && (typeof l.files !== 'object' || Array.isArray(l.files))) E(`${at}: "files" must map winding ids to paths.`);
149
+ const fl = l.files && typeof l.files === 'object' ? l.files : {};
150
+ for (const k of Object.keys(fl)) if (!cover.includes(k)) Wn(`${at}: "files" names ${k}, which this layer does not cover.`);
151
+ if (typeof l.texture !== 'string' && cover.some((id) => !fl[id])) E(`${at}: "texture" is required, a path pattern with {id}, for example "textures/{id}_ink.png".`);
152
+ else {
153
+ if (typeof l.texture === 'string' && !l.texture.includes('{id}') && cover.filter((id) => !fl[id]).length > 1) E(`${at}: "texture" must contain {id} when the layer covers more than one winding.`);
154
+ for (const id of cover) ref(layerFile(l, id), `${at} image for ${id}`, IMAGE_EXT);
155
+ }
156
+ } else if (g.format === 'grid-int16') {
157
+ ref(l.atlas, `${at} atlas`, IMAGE_EXT);
158
+ if (l.atlasFallback !== undefined) ref(l.atlasFallback, `${at} atlasFallback`, IMAGE_EXT);
159
+ }
160
+ if (l.hi !== undefined) for (const id of cover) ref(fill(l.hi, id), `${at} close-up for ${id}`, IMAGE_EXT);
161
+ if (l.stats !== undefined) ref(l.stats, `${at} stats`, ['json']);
162
+ if (l.resolutionUM !== undefined && !(typeof l.resolutionUM === 'number' && l.resolutionUM > 0)) E(`${at}: "resolutionUM" must be a positive number of micrometres.`);
163
+ if (!l.source) Wn(`${at}: no "source" given; say where this layer comes from.`);
164
+ }
165
+ if (!roles.has('ct') && !roles.has('ink')) E('At least one layer must have role "ct" (X-ray) or "ink".');
166
+ if (!m.credits) Wn('No "credits": say who made the data and how to cite it.');
167
+ if (!m.dataTerms) Wn('No "dataTerms": give the data licence or terms of use.');
168
+ for (const k of ['credits', 'dataTerms']) if (m[k] && m[k].url && !/^https?:\/\//.test(m[k].url)) E(`"${k}.url" must start with http:// or https://.`);
169
+ if (m.display && !opts.trusted) Wn('"display" is only used for registry scrolls; it is ignored here.');
170
+ // files on disk or in the drop
171
+ if (opts.fileSize) {
172
+ let total = 0;
173
+ for (const p of files) {
174
+ const n = opts.fileSize(p);
175
+ if (n === null || n === undefined) { E(`Missing file: ${p}`); continue; }
176
+ if (n > lim.maxFileBytes) E(`${p} is ${(n / 1e6).toFixed(1)} MB; the limit per file is ${(lim.maxFileBytes / 1048576).toFixed(0)} MB.`);
177
+ total += n;
178
+ }
179
+ if (total > lim.maxTotalBytes) E(`The files add up to ${(total / 1e6).toFixed(0)} MB; the limit is ${(lim.maxTotalBytes / 1048576).toFixed(0)} MB.`);
180
+ }
181
+ return { ok: !errors.length, errors, warnings, files: [...files] };
182
+ }
183
+
184
+ export function validateRegistry(r) {
185
+ const errors = [];
186
+ if (!r || !Array.isArray(r.scrolls) || !r.scrolls.length) errors.push('scrolls/index.json needs a non-empty "scrolls" list.');
187
+ const seen = new Set();
188
+ for (const s of (r && r.scrolls) || []) {
189
+ if (!ID_RE.test(s.id || '')) errors.push(`Registry entry ${JSON.stringify(s.id)}: bad id.`);
190
+ if (seen.has(s.id)) errors.push(`Registry entry ${s.id} is listed twice.`);
191
+ seen.add(s.id);
192
+ if (!isRelPath(s.manifest, false) || ext(s.manifest) !== 'json') errors.push(`Registry entry ${s.id}: "manifest" must be a relative path to a .json file.`);
193
+ }
194
+ if (r && r.default && !seen.has(r.default)) errors.push(`Registry "default" ${r.default} is not in the list.`);
195
+ return { ok: !errors.length, errors };
196
+ }
lib/openown.js ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // "Open your own": read a scroll from files, a zip or a URL, entirely in this browser.
2
+ // Nothing is uploaded: files are read with the File API, checked, and kept in IndexedDB on this device.
3
+ import { validateManifest, LOCAL_LIMITS, ext, MESH_EXT, IMAGE_EXT } from './manifest.js';
4
+ import { readZip } from './formats.js';
5
+ import { findManifest, fileSource, buildMeshScroll, saveLocal, deleteLocal, listLocal } from './scrolls.js';
6
+ import { exampleZip } from './example.js';
7
+
8
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
9
+ const MB = (n) => `${(n / 1048576).toFixed(n < 10485760 ? 1 : 0)} MB`;
10
+ const OK_EXT = ['json', 'zip', 'txt', 'md', ...MESH_EXT, ...IMAGE_EXT];
11
+
12
+ // files from a drop, a file picker or a zip: [{ name, blob }]
13
+ export async function gatherFiles(list, lim = LOCAL_LIMITS) {
14
+ const out = [];
15
+ for (const f of list) {
16
+ const name = f.relPath || f.webkitRelativePath || f.name;
17
+ const e = ext(name);
18
+ if (e === 'zip') {
19
+ if (f.size > lim.maxZipBytes) throw new Error(`${f.name} is ${MB(f.size)}; the limit for a zip is ${MB(lim.maxZipBytes)}.`);
20
+ out.push(...(await readZip(await f.arrayBuffer(), lim)));
21
+ } else if (OK_EXT.includes(e)) {
22
+ if (f.size > lim.maxFileBytes) throw new Error(`${name} is ${MB(f.size)}; the limit per file is ${MB(lim.maxFileBytes)}.`);
23
+ out.push({ name, blob: f });
24
+ }
25
+ }
26
+ if (!out.length) throw new Error('None of these files can be used. Open a manifest.json with its OBJ or PLY meshes and PNG, JPG or TIFF images, or a zip of them.');
27
+ const total = out.reduce((a, f) => a + f.blob.size, 0);
28
+ if (total > lim.maxTotalBytes) throw new Error(`These files add up to ${MB(total)}; the limit is ${MB(lim.maxTotalBytes)}.`);
29
+ return out.filter((f) => !/(^|\/)(__MACOSX|\.)/.test(f.name));
30
+ }
31
+
32
+ // a manifest or zip at a URL; the manifest's files are fetched from beside it. Needs CORS on that server.
33
+ export async function filesFromURL(url, lim = LOCAL_LIMITS, onStep = () => {}) {
34
+ let u;
35
+ try { u = new URL(url, location.href); } catch (e) { throw new Error('That is not a valid URL.'); }
36
+ if (!/^https?:$/.test(u.protocol)) throw new Error('Only http and https URLs can be opened.');
37
+ const get = async (href, max) => {
38
+ let r;
39
+ try { r = await fetch(href, { mode: 'cors', credentials: 'omit' }); }
40
+ catch (e) { throw new Error(`Could not fetch ${href}. The server may not allow cross-origin requests (CORS), or it is unreachable. Download the files and drop them here instead.`); }
41
+ if (!r.ok) throw new Error(`${href}: the server answered ${r.status}.`);
42
+ const len = +r.headers.get('content-length');
43
+ if (len && len > max) throw new Error(`${href} is ${MB(len)}; the limit is ${MB(max)}.`);
44
+ const b = await r.blob();
45
+ if (b.size > max) throw new Error(`${href} is ${MB(b.size)}; the limit is ${MB(max)}.`);
46
+ return b;
47
+ };
48
+ onStep(`Fetching ${u.href}`);
49
+ const first = await get(u.href, lim.maxZipBytes);
50
+ const head = new Uint8Array(await first.slice(0, 4).arrayBuffer());
51
+ if (ext(u.pathname) === 'zip' || (head[0] === 0x50 && head[1] === 0x4b)) return readZip(await first.arrayBuffer(), lim);
52
+ let m;
53
+ try { m = JSON.parse(await first.text()); } catch (e) { throw new Error('The URL is neither a zip nor a JSON manifest.'); }
54
+ const v = validateManifest(m, { limits: lim });
55
+ if (!v.ok) throw Object.assign(new Error('The manifest has problems.'), { list: v.errors });
56
+ const files = [{ name: 'manifest.json', blob: first }];
57
+ let total = first.size;
58
+ for (const p of v.files) {
59
+ onStep(`Fetching ${p}`);
60
+ const b = await get(new URL(p, u).href, lim.maxFileBytes);
61
+ total += b.size;
62
+ if (total > lim.maxTotalBytes) throw new Error(`The files add up to more than ${MB(lim.maxTotalBytes)}.`);
63
+ files.push({ name: p, blob: b });
64
+ }
65
+ return files;
66
+ }
67
+
68
+ // check everything a scroll needs, parse it all once, and keep it in this browser
69
+ export async function checkAndStore(files, onStep = () => {}) {
70
+ const { path, manifest } = await findManifest(files);
71
+ const src = fileSource(files, path);
72
+ const v = validateManifest(manifest, { limits: LOCAL_LIMITS, fileSize: (p) => src.size(p) });
73
+ if (!v.ok) throw Object.assign(new Error(`${path} has ${v.errors.length} problem${v.errors.length > 1 ? 's' : ''}.`), { list: v.errors, warnings: v.warnings });
74
+ onStep('Reading meshes and images');
75
+ await buildMeshScroll(manifest, src, { limits: LOCAL_LIMITS, atlasSide: 1024 }); // a full trial build, small atlas
76
+ const keep = v.files.concat(path).map((p) => src.find(p) || { name: p }).filter((f) => f.blob);
77
+ const key = `local-${manifest.id}-${Date.now().toString(36)}`;
78
+ const size = keep.reduce((a, f) => a + f.blob.size, 0);
79
+ // opening the same scroll again replaces the copy kept before
80
+ for (const old of await listLocal()) if (old.id === manifest.id) await deleteLocal(old.key).catch(() => {});
81
+ try { await saveLocal({ key, id: manifest.id, name: manifest.name, added: Date.now(), size, files: keep.map((f) => ({ name: f.name, blob: f.blob })) }); }
82
+ catch (e) { throw new Error(`This browser would not store the scroll (${e.message || e}). Private browsing or a full disk can cause this.`); }
83
+ return { key, warnings: v.warnings };
84
+ }
85
+
86
+ export function setupOpenOwn({ $, onOpen, currentKey }) {
87
+ const sheet = $('openSheet'), drop = $('oDrop'), status = $('oStatus');
88
+ const show = (html, cls = '') => { status.className = `o-status mono ${cls}`; status.innerHTML = html; status.hidden = !html; };
89
+ const fail = (e) => {
90
+ const list = e.list ? `<ul>${e.list.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : '';
91
+ show(`<b>Could not open it.</b> ${esc(e.message || e)}${list}`, 'err');
92
+ };
93
+ async function run(get) {
94
+ show('Reading files...', 'busy');
95
+ try {
96
+ const files = await get();
97
+ const { key, warnings } = await checkAndStore(files, (s) => show(esc(s), 'busy'));
98
+ show(`Loaded. ${warnings.length ? `${warnings.length} note${warnings.length > 1 ? 's' : ''}: ${esc(warnings.join(' '))}` : ''} Opening...`, 'ok');
99
+ setTimeout(() => onOpen(key), 300);
100
+ } catch (e) { console.warn(e); fail(e); }
101
+ }
102
+ // drag and drop, including folders
103
+ const readEntry = (entry, path = '') => new Promise((ok) => {
104
+ if (entry.isFile) entry.file((f) => { f.relPath = path + f.name; ok([f]); }, () => ok([]));
105
+ else if (entry.isDirectory) {
106
+ const r = entry.createReader(), all = [];
107
+ const more = () => r.readEntries(async (es) => {
108
+ if (!es.length) { ok((await Promise.all(all)).flat()); return; }
109
+ for (const e of es) all.push(readEntry(e, `${path}${entry.name}/`));
110
+ more();
111
+ }, () => ok([]));
112
+ more();
113
+ } else ok([]);
114
+ });
115
+ for (const t of [drop, sheet]) {
116
+ t.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over'); });
117
+ t.addEventListener('dragleave', () => drop.classList.remove('over'));
118
+ t.addEventListener('drop', (e) => {
119
+ e.preventDefault(); drop.classList.remove('over');
120
+ const items = [...(e.dataTransfer.items || [])].map((i) => i.webkitGetAsEntry && i.webkitGetAsEntry()).filter(Boolean);
121
+ run(async () => gatherFiles(items.length ? (await Promise.all(items.map((it) => readEntry(it)))).flat() : [...e.dataTransfer.files]));
122
+ });
123
+ }
124
+ // pages can be dropped on anywhere: open the sheet when files are dragged over the 3D view
125
+ addEventListener('dragenter', (e) => { if (e.dataTransfer && [...e.dataTransfer.types].includes('Files') && sheet.hidden) open(); });
126
+ $('oPick').onchange = (e) => { const fl = [...e.target.files]; e.target.value = ''; run(() => gatherFiles(fl)); };
127
+ $('oPickDir').onchange = (e) => { const fl = [...e.target.files]; e.target.value = ''; run(() => gatherFiles(fl)); };
128
+ drop.onclick = (e) => { if (e.target === drop || e.target.closest('.o-drop-text')) $('oPick').click(); };
129
+ drop.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $('oPick').click(); } };
130
+ $('oURLForm').onsubmit = (e) => {
131
+ e.preventDefault();
132
+ const u = $('oURL').value.trim();
133
+ if (!u) { show('Paste the URL of a manifest.json or a zip first.', 'err'); return; }
134
+ run(() => filesFromURL(u, LOCAL_LIMITS, (s) => show(esc(s), 'busy')));
135
+ };
136
+ $('oExample').onclick = async () => {
137
+ $('oExample').disabled = true;
138
+ try {
139
+ const b = await exampleZip();
140
+ const a = document.createElement('a');
141
+ a.href = URL.createObjectURL(b); a.download = 'unroll-synthetic-scroll.zip'; a.click();
142
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
143
+ } finally { $('oExample').disabled = false; }
144
+ };
145
+ $('oLimits').textContent = `Limits: ${MB(LOCAL_LIMITS.maxFileBytes)} per file, ${MB(LOCAL_LIMITS.maxTotalBytes)} in all, ${LOCAL_LIMITS.maxWindings} windings, ${(LOCAL_LIMITS.maxVertices / 1e6).toFixed(0)} million vertices, images up to ${LOCAL_LIMITS.maxTextureSide} px on a side.`;
146
+ async function refreshList() {
147
+ const L = await listLocal();
148
+ const box = $('oSaved');
149
+ box.hidden = !L.length;
150
+ $('oSavedList').innerHTML = L.map((s) => `<li><span>${esc(s.name)} <span class="dim">${esc(s.id)} · ${MB(s.size || 0)}${s.key === currentKey ? ' · open now' : ''}</span></span>` +
151
+ `<span><button class="chip" data-open="${esc(s.key)}">Open</button><button class="chip" data-del="${esc(s.key)}">Remove</button></span></li>`).join('');
152
+ for (const b of box.querySelectorAll('[data-open]')) b.onclick = () => onOpen(b.dataset.open);
153
+ for (const b of box.querySelectorAll('[data-del]')) b.onclick = async () => { await deleteLocal(b.dataset.del); if (b.dataset.del === currentKey) onOpen(null); else refreshList(); };
154
+ }
155
+ function open() { sheet.hidden = false; refreshList(); $('oClose').focus(); }
156
+ $('oClose').onclick = () => { sheet.hidden = true; };
157
+ return { open, refreshList, run };
158
+ }
lib/scrolls.js ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Where a scroll comes from (the site registry, or files and URLs opened in this browser),
2
+ // and how a "mesh" format scroll becomes the geometry and texture atlases the page draws.
3
+ import { validateManifest, validateRegistry, peelOrder, layerWindings, roleOf, layerFile, ext, LOCAL_LIMITS, REGISTRY_LIMITS } from './manifest.js';
4
+ import { parseOBJ, parsePLY, decodeTIFF } from './formats.js';
5
+
6
+ // ------------------------------------------------------------ registry
7
+
8
+ export async function loadRegistry() {
9
+ const res = await fetch('scrolls/index.json');
10
+ if (!res.ok) throw new Error(`scrolls/index.json: ${res.status}`);
11
+ const reg = await res.json();
12
+ const v = validateRegistry(reg);
13
+ if (!v.ok) throw new Error(v.errors.join(' '));
14
+ return reg;
15
+ }
16
+
17
+ // ------------------------------------------------------------ scrolls kept in this browser (IndexedDB, never uploaded)
18
+
19
+ const DB = 'unroll-local', STORE = 'scrolls';
20
+ function db() {
21
+ return new Promise((ok, bad) => {
22
+ const r = indexedDB.open(DB, 1);
23
+ r.onupgradeneeded = () => r.result.createObjectStore(STORE, { keyPath: 'key' });
24
+ r.onsuccess = () => ok(r.result);
25
+ r.onerror = () => bad(r.error);
26
+ });
27
+ }
28
+ async function tx(mode, fn) {
29
+ const d = await db();
30
+ return new Promise((ok, bad) => {
31
+ const t = d.transaction(STORE, mode);
32
+ const out = fn(t.objectStore(STORE));
33
+ t.oncomplete = () => ok(out && 'result' in out ? out.result : undefined);
34
+ t.onerror = () => bad(t.error);
35
+ t.onabort = () => bad(t.error || new Error('Storage was refused. Private browsing can block it.'));
36
+ });
37
+ }
38
+ export const localKey = (s) => s.startsWith('local-');
39
+ export async function listLocal() {
40
+ try { return (await tx('readonly', (s) => s.getAll())).map(({ key, name, id, added, size }) => ({ key, name, id, added, size })); }
41
+ catch (e) { return []; }
42
+ }
43
+ export const getLocal = (key) => tx('readonly', (s) => s.get(key));
44
+ export const saveLocal = (rec) => tx('readwrite', (s) => s.put(rec));
45
+ export const deleteLocal = (key) => tx('readwrite', (s) => s.delete(key));
46
+
47
+ // ------------------------------------------------------------ sources: one interface for remote files and dropped files
48
+
49
+ const dirOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/') + 1) : '');
50
+ const norm = (p) => {
51
+ const out = [];
52
+ for (const s of p.split('/')) { if (!s || s === '.') continue; if (s === '..') out.pop(); else out.push(s); }
53
+ return out.join('/');
54
+ };
55
+
56
+ // remote: paths are relative to the manifest's URL plus its "base"
57
+ export function remoteSource(manifestURL, manifest, fetchBytes) {
58
+ const root = new URL(manifest.base || '', new URL(manifestURL, location.href));
59
+ const url = (p) => new URL(p, root).href;
60
+ return {
61
+ kind: 'remote',
62
+ url,
63
+ size: () => undefined,
64
+ bytes: (p, guess) => fetchBytes(url(p), guess),
65
+ blob: async (p, guess) => new Blob([await fetchBytes(url(p), guess)]),
66
+ async imageURL(p) { return ext(p).startsWith('tif') ? toPNGURL(await this.blob(p), p) : url(p); },
67
+ };
68
+ }
69
+
70
+ // local: a list of { name, blob } (dropped, picked, unzipped or downloaded); paths are relative to the manifest
71
+ export function fileSource(files, manifestPath) {
72
+ const map = new Map(files.map((f) => [norm(f.name), f]));
73
+ const base = dirOf(norm(manifestPath));
74
+ const byBase = new Map();
75
+ for (const f of files) { const b = norm(f.name).split('/').pop(); byBase.set(b, byBase.has(b) ? null : f); }
76
+ const find = (p) => map.get(norm(base + p)) || map.get(norm(p)) || byBase.get(norm(p).split('/').pop()) || null;
77
+ const urls = new Map();
78
+ return {
79
+ kind: 'files',
80
+ find,
81
+ size: (p) => { const f = find(p); return f ? f.blob.size : null; },
82
+ async bytes(p) { const f = find(p); if (!f) throw new Error(`Missing file: ${p}`); return f.blob.arrayBuffer(); },
83
+ async blob(p) { const f = find(p); if (!f) throw new Error(`Missing file: ${p}`); return f.blob; },
84
+ async imageURL(p) {
85
+ if (urls.has(p)) return urls.get(p);
86
+ const b = await this.blob(p);
87
+ const u = ext(p).startsWith('tif') ? await toPNGURL(b, p) : URL.createObjectURL(b);
88
+ urls.set(p, u);
89
+ return u;
90
+ },
91
+ };
92
+ }
93
+
94
+ // find the manifest among dropped files
95
+ export async function findManifest(files) {
96
+ const cands = files.filter((f) => ext(f.name) === 'json');
97
+ const hits = [];
98
+ for (const f of cands) {
99
+ if (f.blob.size > 4e6) continue;
100
+ try { const j = JSON.parse(await f.blob.text()); if (j && (j.schema || j.windings)) hits.push({ f, j }); }
101
+ catch (e) { if (/manifest/i.test(f.name)) throw new Error(`${f.name} is not valid JSON: ${e.message}`); }
102
+ }
103
+ if (!hits.length) throw new Error('No manifest found. Add a manifest.json (see the example package), or drop a zip that contains one.');
104
+ if (hits.length > 1) {
105
+ const m = hits.filter((h) => /(^|\/)manifest\.json$/i.test(h.f.name));
106
+ if (m.length === 1) return { path: m[0].f.name, manifest: m[0].j };
107
+ throw new Error(`Found ${hits.length} manifests (${hits.map((h) => h.f.name).join(', ')}). Open one scroll at a time.`);
108
+ }
109
+ return { path: hits[0].f.name, manifest: hits[0].j };
110
+ }
111
+
112
+ // ------------------------------------------------------------ images
113
+
114
+ export async function decodeImage(blob, name, maxSide = LOCAL_LIMITS.maxTextureSide) {
115
+ let bmp;
116
+ try {
117
+ if (ext(name).startsWith('tif')) bmp = await createImageBitmap(await decodeTIFF(await blob.arrayBuffer(), maxSide));
118
+ else bmp = await createImageBitmap(blob);
119
+ } catch (e) {
120
+ throw new Error(`${name}: could not decode the image (${e.message || 'unsupported or damaged file'}). Use PNG, JPG or TIFF.`);
121
+ }
122
+ if (bmp.width > maxSide || bmp.height > maxSide) throw new Error(`${name} is ${bmp.width} x ${bmp.height} px; the limit is ${maxSide} px on a side.`);
123
+ return bmp;
124
+ }
125
+ async function toPNGURL(blob, name) {
126
+ const bmp = await decodeImage(blob, name);
127
+ const c = document.createElement('canvas');
128
+ c.width = bmp.width; c.height = bmp.height;
129
+ c.getContext('2d').drawImage(bmp, 0, 0);
130
+ return new Promise((ok) => c.toBlob((b) => ok(URL.createObjectURL(b)), 'image/png'));
131
+ }
132
+
133
+ // ------------------------------------------------------------ mesh scrolls
134
+
135
+ export function parseMesh(buf, name) {
136
+ const e = ext(name);
137
+ if (e === 'obj') return parseOBJ(new TextDecoder().decode(buf));
138
+ if (e === 'ply') return parsePLY(buf);
139
+ throw new Error(`${name}: meshes must be OBJ or PLY.`);
140
+ }
141
+
142
+ /**
143
+ * Turn a "mesh" manifest into what the page draws: per winding geometry in scene millimetres, roll axis on the origin,
144
+ * and CT and ink atlases (canvases) with one rectangle per winding, the same shape the registry's grid scrolls use.
145
+ */
146
+ export async function buildMeshScroll(m, src, opts = {}) {
147
+ const lim = opts.limits || LOCAL_LIMITS;
148
+ const order = peelOrder(m);
149
+ const g = m.geometry;
150
+ const k = (g.units || 'voxels') === 'mm' ? 1 : m.voxelMM;
151
+ const zAxis = (g.axis || 'z') === 'z';
152
+ const flipV = g.flipV !== false;
153
+ const W = [];
154
+ let nV = 0;
155
+ for (const w of order) {
156
+ let mesh;
157
+ try { mesh = parseMesh(await src.bytes(w.mesh, 2e5), w.mesh); } catch (e) { throw new Error(`Winding ${w.id}: ${e.message}`); }
158
+ nV += mesh.vertices;
159
+ if (nV > lim.maxVertices) throw new Error(`The meshes have more than ${lim.maxVertices.toLocaleString()} vertices together; decimate them first.`);
160
+ const P = mesh.pos, n = mesh.vertices;
161
+ const pos = new Float32Array(n * 3), loc = new Float32Array(n * 2);
162
+ for (let i = 0; i < n; i++) {
163
+ const x = P[i * 3] * k, y = P[i * 3 + 1] * k, z = P[i * 3 + 2] * k;
164
+ if (zAxis) { pos[i * 3] = x; pos[i * 3 + 1] = -z; pos[i * 3 + 2] = y; } else { pos[i * 3] = x; pos[i * 3 + 1] = y; pos[i * 3 + 2] = z; }
165
+ loc[i * 2] = mesh.uv[i * 2];
166
+ loc[i * 2 + 1] = flipV ? 1 - mesh.uv[i * 2 + 1] : mesh.uv[i * 2 + 1];
167
+ }
168
+ W.push({ id: w.id, pos, loc, index: mesh.index, n });
169
+ }
170
+ // put the roll's axis on the origin: centre of the bounding box
171
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
172
+ for (const w of W) for (let i = 0; i < w.n * 3; i++) { const a = i % 3; if (w.pos[i] < lo[a]) lo[a] = w.pos[i]; if (w.pos[i] > hi[a]) hi[a] = w.pos[i]; }
173
+ const c = [0, 1, 2].map((a) => (lo[a] + hi[a]) / 2);
174
+ if (g.centre === false) c.fill(0);
175
+ for (const w of W) for (let i = 0; i < w.n * 3; i++) w.pos[i] -= c[i % 3];
176
+
177
+ const COLS = 96;
178
+ for (const w of W) {
179
+ const { pos, loc, index } = w;
180
+ // size of the flattened sheet: the mean stretch of the UV map, weighted by triangle area
181
+ let su = 0, sv = 0, sa = 0;
182
+ for (let t = 0; t < index.length; t += 3) {
183
+ const a = index[t], b = index[t + 1], d = index[t + 2];
184
+ const e1 = [0, 1, 2].map((q) => pos[b * 3 + q] - pos[a * 3 + q]), e2 = [0, 1, 2].map((q) => pos[d * 3 + q] - pos[a * 3 + q]);
185
+ const du1 = loc[b * 2] - loc[a * 2], dv1 = loc[b * 2 + 1] - loc[a * 2 + 1], du2 = loc[d * 2] - loc[a * 2], dv2 = loc[d * 2 + 1] - loc[a * 2 + 1];
186
+ const det = du1 * dv2 - du2 * dv1;
187
+ const cx = e1[1] * e2[2] - e1[2] * e2[1], cy = e1[2] * e2[0] - e1[0] * e2[2], cz = e1[0] * e2[1] - e1[1] * e2[0];
188
+ const area = 0.5 * Math.hypot(cx, cy, cz);
189
+ sa += area;
190
+ if (Math.abs(det) < 1e-12) continue;
191
+ const pu = [0, 1, 2].map((q) => (e1[q] * dv2 - e2[q] * dv1) / det), pv = [0, 1, 2].map((q) => (e2[q] * du1 - e1[q] * du2) / det);
192
+ su += Math.hypot(...pu) * area; sv += Math.hypot(...pv) * area;
193
+ }
194
+ if (!(sa > 0) || !(su > 0) || !(sv > 0)) throw new Error(`Winding ${w.id}: the mesh has no area or its UVs are degenerate.`);
195
+ w.widthMM = su / sa; w.heightMM = sv / sa; w.areaCM2 = sa / 100;
196
+ // radius, top edge, and the angle of each slice along u for the peel
197
+ let r = 0, yt = 0;
198
+ const cx = new Float64Array(COLS), cz = new Float64Array(COLS), cn = new Float64Array(COLS);
199
+ for (let i = 0; i < w.n; i++) {
200
+ const x = pos[i * 3], y = pos[i * 3 + 1], z = pos[i * 3 + 2];
201
+ r += Math.hypot(x, z);
202
+ yt += y + loc[i * 2 + 1] * w.heightMM;
203
+ const b = Math.min(COLS - 1, Math.max(0, Math.round(loc[i * 2] * (COLS - 1))));
204
+ cx[b] += x; cz[b] += z; cn[b]++;
205
+ }
206
+ w.radiusMM = r / w.n; w.ytop = yt / w.n;
207
+ const ang = new Float64Array(COLS);
208
+ let prev = null;
209
+ for (let b = 0; b < COLS; b++) {
210
+ if (!cn[b]) { ang[b] = prev ?? 0; continue; }
211
+ let a = Math.atan2(cz[b] / cn[b], cx[b] / cn[b]);
212
+ if (prev !== null) { while (a - prev > Math.PI) a -= 2 * Math.PI; while (a - prev < -Math.PI) a += 2 * Math.PI; }
213
+ ang[b] = a; prev = a;
214
+ }
215
+ let f0 = 0; while (f0 < COLS && !cn[f0]) f0++;
216
+ for (let b = 0; b < f0 && f0 < COLS; b++) ang[b] = ang[f0];
217
+ w.colAng = ang; w.colIdx = Array.from({ length: COLS }, (_, i) => i); w.gridW = COLS - 1;
218
+ }
219
+
220
+ // atlases: shelf-pack one rectangle per winding, sized by its millimetres
221
+ const S = opts.atlasSide || 4096, pad = 4;
222
+ let ppmm = Math.min(...W.map((w) => (S - 2 * pad) / Math.max(w.widthMM, w.heightMM)));
223
+ for (let it = 0; it < 80; it++) {
224
+ let x = pad, y = pad, rowH = 0, fits = true;
225
+ for (const w of W) {
226
+ const rw = Math.ceil(w.widthMM * ppmm), rh = Math.ceil(w.heightMM * ppmm);
227
+ if (x + rw + pad > S) { x = pad; y += rowH + pad; rowH = 0; }
228
+ w.rect = [x, y, rw, rh];
229
+ x += rw + pad; rowH = Math.max(rowH, rh);
230
+ if (y + rh + pad > S) fits = false;
231
+ }
232
+ if (fits) break;
233
+ ppmm *= 0.92;
234
+ }
235
+ ppmm = Math.min(ppmm, opts.maxPPMM || 40);
236
+ const ids = W.map((w) => w.id);
237
+ const ctL = roleOf(m, 'ct'), inkL = roleOf(m, 'ink');
238
+ const mk = () => { const cv = document.createElement('canvas'); cv.width = cv.height = S; const x = cv.getContext('2d'); x.fillStyle = '#000'; x.fillRect(0, 0, S, S); return [cv, x]; };
239
+ const [ctC, ctX] = mk(), [inkC, inkX] = mk();
240
+ const ctSet = new Set(ctL ? layerWindings(ctL, ids) : []), inkSet = new Set(inkL ? layerWindings(inkL, ids) : []);
241
+ for (const w of W) {
242
+ const [x, y, rw, rh] = w.rect;
243
+ w.atlas = [x / S, y / S, (x + rw) / S, (y + rh) / S];
244
+ if (ctSet.has(w.id)) {
245
+ const p = layerFile(ctL, w.id);
246
+ ctX.drawImage(await decodeImage(await src.blob(p, 3e5), p), x, y, rw, rh);
247
+ } else {
248
+ // no X-ray for this winding: paint the mesh's UV footprint so the page knows where papyrus is
249
+ ctX.fillStyle = 'rgb(90,90,90)';
250
+ for (let t = 0; t < w.index.length; t += 3) {
251
+ ctX.beginPath();
252
+ for (let q = 0; q < 3; q++) { const v = w.index[t + q]; ctX[q ? 'lineTo' : 'moveTo'](x + w.loc[v * 2] * rw, y + w.loc[v * 2 + 1] * rh); }
253
+ ctX.closePath(); ctX.fill(); ctX.strokeStyle = ctX.fillStyle; ctX.lineWidth = 1; ctX.stroke();
254
+ }
255
+ }
256
+ if (inkSet.has(w.id)) {
257
+ const p = layerFile(inkL, w.id);
258
+ inkX.drawImage(await decodeImage(await src.blob(p, 3e5), p), x, y, rw, rh);
259
+ }
260
+ w.hasInk = inkSet.has(w.id);
261
+ if (opts.progress) opts.progress(w.id);
262
+ }
263
+ return { windings: W, ctCanvas: ctC, inkCanvas: inkC, cellMM: Math.max(...W.map((w) => w.widthMM)) / COLS };
264
+ }
265
+
266
+ export { validateManifest, LOCAL_LIMITS, REGISTRY_LIMITS };
package.json ADDED
@@ -0,0 +1 @@
 
 
1
+ { "private": true, "type": "module", "scripts": { "validate": "node tools/validate_scroll.mjs" } }
polish.js CHANGED
@@ -49,7 +49,7 @@ function toggleHelp(force) {
49
  $('hClose').onclick = () => toggleHelp(false);
50
 
51
  const click = (id) => { const el = $(id); if (el && !el.hidden) { el.click(); return true; } return false; };
52
- const sheetOpen = () => ['focus', 'about'].some((id) => $(id) && !$(id).hidden);
53
 
54
  addEventListener('keydown', (e) => {
55
  if (e.ctrlKey || e.metaKey || e.altKey) return;
 
49
  $('hClose').onclick = () => toggleHelp(false);
50
 
51
  const click = (id) => { const el = $(id); if (el && !el.hidden) { el.click(); return true; } return false; };
52
+ const sheetOpen = () => ['focus', 'about', 'openSheet'].some((id) => $(id) && !$(id).hidden);
53
 
54
  addEventListener('keydown', (e) => {
55
  if (e.ctrlKey || e.metaKey || e.altKey) return;
scrolls/PHerc0139/manifest.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "unroll-scroll/1",
3
+ "id": "PHerc0139",
4
+ "name": "PHerc. 139",
5
+ "description": "A papyrus roll carbonized by Vesuvius in 79 CE, scanned at the ESRF synchrotron. 37 traced windings.",
6
+ "voxelMM": 0.009362,
7
+ "base": "../../",
8
+ "geometry": {
9
+ "format": "grid-int16",
10
+ "index": "data/scroll.json",
11
+ "bin": "data/scroll.bin",
12
+ "sizeHint": 3500000,
13
+ "source": "Vesuvius Challenge 9.362 um tifxyz meshes, decimated by tools/build.py"
14
+ },
15
+ "windings": {
16
+ "range": [
17
+ "w023",
18
+ "w059"
19
+ ],
20
+ "outermost": "last"
21
+ },
22
+ "layers": [
23
+ {
24
+ "id": "xray",
25
+ "role": "ct",
26
+ "label": "X‑ray",
27
+ "atlas": "data/atlas_ct.webp",
28
+ "sizeHint": 3482792,
29
+ "title": "Raw X-ray CT brightness on each winding. No ink detection.",
30
+ "hint": "Raw X-ray CT brightness, no ink detection.",
31
+ "source": "Vesuvius Challenge surface volumes, 9.362 um scan",
32
+ "resolutionUM": 9.362,
33
+ "atlasFallback": "data/atlas_ct.jpg"
34
+ },
35
+ {
36
+ "id": "ink",
37
+ "role": "ink",
38
+ "label": "Published ink (2.4 µm)",
39
+ "atlas": "data/atlas_ink.webp",
40
+ "sizeHint": 1876686,
41
+ "hi": "data/hi/{id}.jpg",
42
+ "title": "Vesuvius Challenge's published ink detection on the fine 2.4 µm scan, covering all 37 windings.",
43
+ "hint": "Published ink (2.4 µm): Vesuvius Challenge detection, 2.4 µm scan, all windings.",
44
+ "closeupLabel": "Published ink (2.4 µm)",
45
+ "notes": "ink: Vesuvius Challenge public detection on the 2.399 µm scan",
46
+ "source": "Vesuvius Challenge public ink detection (ink-detection/downsampled)",
47
+ "resolutionUM": 2.399,
48
+ "atlasFallback": "data/atlas_ink.jpg"
49
+ },
50
+ {
51
+ "id": "gpu",
52
+ "role": "overlay",
53
+ "label": "Our ink model (9 µm)",
54
+ "windings": {
55
+ "range": [
56
+ "w046",
57
+ "w051"
58
+ ]
59
+ },
60
+ "texture": "data/gpu/{id}.jpg",
61
+ "hi": "data/hi/{id}_gpu.jpg",
62
+ "stats": "data/gpu.json",
63
+ "sizeHint": 150000,
64
+ "title": "Lower resolution comparison: the open ink_9um model run by us on free Hugging Face GPU, on the coarser 9.4 µm scan (about 4x coarser than 2.4 µm), for six windings. It looks blurrier and shows patch seams. It's here to show what an open model can recover from cheaper, more widely available scans, as a reproducible baseline you can check against the published result.",
65
+ "hint": "Our ink model (9 µm): open ink_9um model on the 9.4 µm scan, about 4x coarser, six windings. Blurrier, with patch seams; a reproducible baseline to check against the published layer.",
66
+ "closeupLabel": "Our ink model (9 µm)",
67
+ "readoutLabel": "OUR INK",
68
+ "bandTitle": "Windings inked by our ink model (9 µm)",
69
+ "source": "scrollprize/ink_9um (seed 42, step 75000) run on Hugging Face ZeroGPU; per-run receipts in data/gpu/receipts/",
70
+ "resolutionUM": 9.362,
71
+ "aboutHtml": "<b>Our ink model (9 µm)</b>, the cyan band, is ours. We used all 8 of a free Hugging Face account's daily ZeroGPU runs (the limit is 8; most of the daily GPU-time quota was left over) to run the public <a href=\"https://huggingface.co/scrollprize/ink_9um\" target=\"_blank\" rel=\"noopener\">scrollprize/ink_9um</a> model over windings w046 to w051: 37,141 patches in 57 s of measured GPU time on half an NVIDIA RTX PRO 6000 Blackwell. It reads the 9.362 µm scan, about four times coarser than the 2.4 µm scan behind the amber layer, so its ink map is noisier. w047 and w050 ran with patch overlap 0.5; w046, w048, w049 and w051 ran with less overlap, so their 128 px patch grid shows as faint square tiles. That grid is a stitching artifact, not ink. It is included at lower resolution on purpose: it shows what an open model can recover from cheaper, more widely available scans, as a reproducible baseline you can check against the published result. Click a cyan winding to compare the two maps."
72
+ }
73
+ ],
74
+ "credits": {
75
+ "text": "Vesuvius Challenge",
76
+ "url": "https://scrollprize.org/data_browser/PHerc0139",
77
+ "citation": "Giorgio Angelotti, Stephen Parsons, Sean Johnson, Elian Rafael Dal Prà, Johannes Rudolph, Paul Tafforeau, Alessandro Mirone, Paul Henderson, Hendrik Schilling, Forrest McDonald, David Josey, Youssef Nader, C. Seth Parker, W. Brent Seales. Vesuvius Challenge - CT Scans of Herculaneum Papyri. Vesuvius Challenge.",
78
+ "holder": "Biblioteca Nazionale di Napoli"
79
+ },
80
+ "dataTerms": {
81
+ "license": "CC BY‑NC 4.0",
82
+ "url": "https://creativecommons.org/licenses/by-nc/4.0/",
83
+ "notes": "data/ and og.jpg are derived from Vesuvius Challenge data and are CC BY-NC 4.0. The code is MIT."
84
+ },
85
+ "display": {
86
+ "pageTitle": "Unroll · PHerc. 139",
87
+ "loaderKicker": "PHERC. 0139 · ESRF · 9.362 µm",
88
+ "kicker": "PHERC. 0139 <span class=\"sep\">/</span> HERCULANEUM <span class=\"sep\">/</span> BURIED 79 CE",
89
+ "titleHtml": "Unroll a scroll nobody has opened in <em>1,947 years.</em>",
90
+ "lede": "37 of its windings have been traced through X‑ray CT by the Vesuvius Challenge, and neural networks found the ink on them. Drag to look around. Scrub to unroll.",
91
+ "layerWhy": "Published ink is the Vesuvius Challenge result on the fine 2.4 µm scan. Our ink model (9 µm) is the open ink_9um model run by us on a scan about 4x coarser, so it is blurrier. It shows what an open model can recover from cheaper scans, as a baseline you can check.",
92
+ "aboutHtml": [
93
+ "<p>PHerc. 139 is one of the papyrus rolls carbonized when Vesuvius buried Herculaneum in 79 CE. It is too fragile to open, so it was scanned with X‑rays at the ESRF synchrotron in Grenoble. It is held by the Biblioteca Nazionale di Napoli.</p>",
94
+ "<p>Each sheet in the 3D view is one winding of the roll, traced through the CT volume by the <a href=\"https://scrollprize.org\" target=\"_blank\" rel=\"noopener\">Vesuvius Challenge</a>. The shapes are the real ones, from the public 9.362 µm meshes. The <b>X‑ray</b> layer is the CT intensity on each surface. The <b>Published ink (2.4 µm)</b> layer is the Vesuvius Challenge's public ink detection on the 2.4 µm scan. In 3D it is drawn through a local‑contrast filter so letter‑sized strokes stand out; the close‑up view shows the published preview unfiltered, downscaled to 2,400 px.</p>",
95
+ "<p id=\"aboutGpu\" hidden></p>",
96
+ "<p>Unrolling lays the windings end to end, outermost first, the way a reader would open the roll. Each traced winding runs a little past one full turn, so roughly a tenth of the 2.8 m strip repeats surface from its neighbour.</p>",
97
+ "<p class=\"mono dim small\">Sources: open data bucket <code>PHerc0139/segments/*/mesh/*9.362um.tifxyz</code>, <code>surface-volumes/9.362um…zarr</code> and <code>ink-detection/downsampled</code>. Data: Giorgio Angelotti, Stephen Parsons, Sean Johnson, Elian Rafael Dal Prà, Johannes Rudolph, Paul Tafforeau, Alessandro Mirone, Paul Henderson, Hendrik Schilling, Forrest McDonald, David Josey, Youssef Nader, C. Seth Parker, W. Brent Seales. <i>Vesuvius Challenge - CT Scans of Herculaneum Papyri.</i> Vesuvius Challenge. Licensed <a href=\"https://creativecommons.org/licenses/by-nc/4.0/\" target=\"_blank\" rel=\"noopener\">CC BY‑NC 4.0</a>. The page's code (HTML, CSS, JS and <code>tools/</code>) is MIT; see the Space's README.</p>",
98
+ "<p class=\"mono dim small made-by\">Made by Chase Hendrick.</p>"
99
+ ],
100
+ "shot": {
101
+ "kicker": "PHERC. 0139 / HERCULANEUM / BURIED 79 CE",
102
+ "line1": "Unroll a scroll nobody",
103
+ "line2": "has opened in ",
104
+ "accent": "1,947 years.",
105
+ "footer": "data: Vesuvius Challenge, CC BY-NC 4.0 (creativecommons.org/licenses/by-nc/4.0)"
106
+ }
107
+ }
108
+ }
scrolls/index.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "unroll-registry/1",
3
+ "default": "PHerc0139",
4
+ "scrolls": [
5
+ {
6
+ "id": "PHerc0139",
7
+ "name": "PHerc. 139",
8
+ "manifest": "scrolls/PHerc0139/manifest.json"
9
+ }
10
+ ]
11
+ }
style.css CHANGED
@@ -218,3 +218,23 @@ kbd { display: inline-block; min-width: 20px; padding: 2px 6px; border: 1px soli
218
  }
219
  /* polish: a flex-wrap row sizes itself to all its items side by side, which pushed the layer switch over the title */
220
  @media (min-width: 721px) { .tr { max-width: 600px; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  }
219
  /* polish: a flex-wrap row sizes itself to all its items side by side, which pushed the layer switch over the title */
220
  @media (min-width: 721px) { .tr { max-width: 600px; } }
221
+ /* scroll picker and "Open your own" */
222
+ .scroll-pick { display: flex; align-items: center; gap: 8px; margin-top: 12px; pointer-events: auto; }
223
+ .scroll-pick select { background: rgba(12,10,9,0.8); color: #ece6db; border: 1px solid rgba(255,255,255,0.18); border-radius: 999px; padding: 5px 10px; font: inherit; font-size: 12px; max-width: 240px; }
224
+ .local-tag { color: #7fd8ff; }
225
+ .open-own .o-private { border-left: 2px solid #7fd8ff; padding-left: 10px; }
226
+ .o-drop { border: 1.5px dashed rgba(255,255,255,0.28); border-radius: 12px; padding: 22px 16px; text-align: center; cursor: pointer; margin: 10px 0; transition: background .2s, border-color .2s; }
227
+ .o-drop.over, .o-drop:focus-visible { background: rgba(255,179,71,0.08); border-color: #ffb347; outline: none; }
228
+ .o-drop-btns { display: flex; gap: 8px; justify-content: center; margin-top: 12px; flex-wrap: wrap; }
229
+ .o-drop-btns label { cursor: pointer; }
230
+ .o-url { display: flex; gap: 8px; margin-top: 8px; }
231
+ .o-url input { flex: 1; min-width: 0; background: rgba(0,0,0,0.4); color: inherit; border: 1px solid rgba(255,255,255,0.2); border-radius: 8px; padding: 7px 10px; font: inherit; font-size: 13px; }
232
+ .o-status { padding: 10px 12px; border-radius: 8px; font-size: 12px; margin: 8px 0; background: rgba(255,255,255,0.05); }
233
+ .o-status.err { background: rgba(255,80,60,0.12); color: #ffb4a8; }
234
+ .o-status.ok { background: rgba(80,200,255,0.1); color: #a8e6ff; }
235
+ .o-status ul { margin: 6px 0 0; padding-left: 18px; }
236
+ .o-list { list-style: none; padding: 0; margin: 6px 0 12px; }
237
+ .o-list li { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px solid rgba(255,255,255,0.08); }
238
+ .o-list li > span:last-child { display: flex; gap: 6px; }
239
+ .mu { text-transform: none; }
240
+ @media (min-width: 721px) { .hud.tr .seg[role=tablist] .chip { letter-spacing: .07em; padding: 8px 11px; } }
tools/gpu_layer.py CHANGED
@@ -78,7 +78,7 @@ def main():
78
  "calls": g["calls"],
79
  "overlap": args["overlap"],
80
  "started": receipt["calls"][0]["started"],
81
- "meta": (f"ZeroGPU run: scrollprize/ink_9um (seed 42, step 75000) on the 9.362 µm scan · "
82
  f"{p:,} patches of 128×128 px, overlap {args['overlap']}"
83
  f"{' (patch seams visible)' if args['overlap'] < 0.5 else ''} · {g['measured']:.1f} s of GPU in "
84
  f"{g['calls']} call{'s' if g['calls'] > 1 else ''} · {receipt['calls'][0]['started'][:10]} · "
@@ -92,7 +92,7 @@ def main():
92
  "windings": wins,
93
  "totals": {"windings": len(wins), "patches": tot_patches, "gpuSeconds": round(tot_measured, 1),
94
  "calls": tot_calls, "device": device},
95
- "about": (f"<b>The cyan band</b> is ours. We used all {tot_calls} of a free Hugging Face account's daily "
96
  f"ZeroGPU runs (the limit is 8; most of the daily GPU-time quota was left over) to run the public "
97
  f"<a href=\"https://huggingface.co/scrollprize/ink_9um\" target=\"_blank\" rel=\"noopener\">"
98
  f"scrollprize/ink_9um</a> model over windings {ids[0]} to {ids[-1]}: {tot_patches:,} patches in "
 
78
  "calls": g["calls"],
79
  "overlap": args["overlap"],
80
  "started": receipt["calls"][0]["started"],
81
+ "meta": (f"Our ink model (9 µm): scrollprize/ink_9um (seed 42, step 75000) on the 9.362 µm scan · "
82
  f"{p:,} patches of 128×128 px, overlap {args['overlap']}"
83
  f"{' (patch seams visible)' if args['overlap'] < 0.5 else ''} · {g['measured']:.1f} s of GPU in "
84
  f"{g['calls']} call{'s' if g['calls'] > 1 else ''} · {receipt['calls'][0]['started'][:10]} · "
 
92
  "windings": wins,
93
  "totals": {"windings": len(wins), "patches": tot_patches, "gpuSeconds": round(tot_measured, 1),
94
  "calls": tot_calls, "device": device},
95
+ "about": (f"<b>Our ink model (9 µm)</b>, the cyan band, is ours. We used all {tot_calls} of a free Hugging Face account's daily "
96
  f"ZeroGPU runs (the limit is 8; most of the daily GPU-time quota was left over) to run the public "
97
  f"<a href=\"https://huggingface.co/scrollprize/ink_9um\" target=\"_blank\" rel=\"noopener\">"
98
  f"scrollprize/ink_9um</a> model over windings {ids[0]} to {ids[-1]}: {tot_patches:,} patches in "
tools/precompute_template.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Template: turn traced windings into an Unroll "mesh" scroll package.
3
+
4
+ Copy this file, fill in the WINDINGS table (or the find_windings() function) for your scroll, and run:
5
+
6
+ python tools/precompute_template.py --out scrolls/MyScroll --id MyScroll --name "My scroll" --voxel-mm 0.007910
7
+
8
+ For every winding it writes
9
+ meshes/<id>.obj the surface, decimated, with UVs (u along the winding, v down the roll)
10
+ xray/<id>.jpg the X-ray (CT) layer laid out on those UVs, if you give one
11
+ ink/<id>.jpg the ink layer, if you give one
12
+ and then manifest.json, which tools/validate_scroll.mjs checks.
13
+
14
+ Inputs it understands out of the box:
15
+ * a tifxyz folder (x.tif, y.tif, z.tif: one 3D point per grid cell, -1 where there is no surface),
16
+ which is how the Vesuvius Challenge publishes segment meshes
17
+ * an OBJ that already has UVs (copied through, optionally rescaled)
18
+ Layers are images in the same UV frame (the flattened segment): PNG, JPG or TIFF, 8 or 16 bit.
19
+
20
+ Needs Python 3.9+, numpy and Pillow; tifffile for tifxyz and 16-bit TIFF layers.
21
+ Everything here is a starting point; check the TODO lines for your data.
22
+ """
23
+ import argparse
24
+ import json
25
+ import shutil
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+ from PIL import Image
30
+
31
+ # TODO: list your windings, outermost first. Paths are relative to --src.
32
+ WINDINGS = [
33
+ # {"id": "w001", "mesh": "segments/w001.tifxyz", "ct": "layers/w001_ct.tif", "ink": "layers/w001_ink.png"},
34
+ ]
35
+
36
+ MAX_SIDE = 2400 # longest side of a layer image, px (the page allows up to 8192)
37
+ GRID_STEP = 4 # keep every Nth tifxyz cell (decimation); the page allows 2,000,000 vertices in all
38
+
39
+
40
+ def find_windings(src: Path):
41
+ """TODO: discover windings automatically instead of filling WINDINGS by hand."""
42
+ return WINDINGS
43
+
44
+
45
+ def tifxyz_to_obj(folder: Path, out: Path, step: int):
46
+ import tifffile
47
+ x, y, z = (tifffile.imread(folder / f"{a}.tif").astype(np.float32) for a in "xyz")
48
+ x, y, z = x[::step, ::step], y[::step, ::step], z[::step, ::step]
49
+ R, C = x.shape
50
+ valid = (x > 0) & (y > 0) & (z > 0)
51
+ vid = -np.ones((R, C), np.int64)
52
+ vid[valid] = np.arange(valid.sum())
53
+ rr, cc = np.nonzero(valid)
54
+ lines = [f"# from {folder.name}, voxel units, roll axis along z"]
55
+ lines += [f"v {x[r, c]:.2f} {y[r, c]:.2f} {z[r, c]:.2f}" for r, c in zip(rr, cc)]
56
+ # u runs along the winding (columns), v runs down the roll (rows); OBJ's v points up, so flip it
57
+ lines += [f"vt {c / max(1, C - 1):.6f} {1 - r / max(1, R - 1):.6f}" for r, c in zip(rr, cc)]
58
+ for r in range(R - 1):
59
+ for c in range(C - 1):
60
+ a, b, d, e = vid[r, c], vid[r, c + 1], vid[r + 1, c], vid[r + 1, c + 1]
61
+ if min(a, d, b) >= 0:
62
+ lines.append(f"f {a+1}/{a+1} {d+1}/{d+1} {b+1}/{b+1}")
63
+ if min(b, d, e) >= 0:
64
+ lines.append(f"f {b+1}/{b+1} {d+1}/{d+1} {e+1}/{e+1}")
65
+ out.write_text("\n".join(lines) + "\n")
66
+ return int(valid.sum())
67
+
68
+
69
+ def layer_image(src: Path, out: Path):
70
+ if src.suffix.lower() in (".tif", ".tiff"):
71
+ import tifffile
72
+ a = tifffile.imread(src).astype(np.float32)
73
+ if a.ndim == 3:
74
+ a = a[..., 0]
75
+ lo, hi = np.percentile(a, [0.5, 99.5]) # TODO: fixed limits if your layers must match
76
+ a = np.clip((a - lo) / max(hi - lo, 1e-6), 0, 1) * 255
77
+ im = Image.fromarray(a.astype(np.uint8))
78
+ else:
79
+ im = Image.open(src).convert("L")
80
+ im.thumbnail((MAX_SIDE, MAX_SIDE), Image.LANCZOS)
81
+ im.save(out, quality=90)
82
+
83
+
84
+ def main():
85
+ ap = argparse.ArgumentParser()
86
+ ap.add_argument("--src", default=".", help="folder the WINDINGS paths are relative to")
87
+ ap.add_argument("--out", required=True)
88
+ ap.add_argument("--id", required=True)
89
+ ap.add_argument("--name", required=True)
90
+ ap.add_argument("--voxel-mm", type=float, required=True)
91
+ args = ap.parse_args()
92
+ src, out = Path(args.src), Path(args.out)
93
+ for d in ("meshes", "xray", "ink"):
94
+ (out / d).mkdir(parents=True, exist_ok=True)
95
+ wins = find_windings(src)
96
+ if not wins:
97
+ raise SystemExit("No windings: fill in WINDINGS or find_windings() first.")
98
+ entries, have_ct, have_ink, total = [], [], [], 0
99
+ for w in wins:
100
+ m = src / w["mesh"]
101
+ dst = out / "meshes" / f"{w['id']}.obj"
102
+ if m.is_dir():
103
+ total += tifxyz_to_obj(m, dst, GRID_STEP)
104
+ else:
105
+ shutil.copy(m, dst) # TODO: decimate large meshes first
106
+ entries.append({"id": w["id"], "mesh": f"meshes/{w['id']}.obj"})
107
+ if w.get("ct"):
108
+ layer_image(src / w["ct"], out / "xray" / f"{w['id']}.jpg"); have_ct.append(w["id"])
109
+ if w.get("ink"):
110
+ layer_image(src / w["ink"], out / "ink" / f"{w['id']}.jpg"); have_ink.append(w["id"])
111
+ print(f"{w['id']}: done")
112
+ layers = []
113
+ if have_ct:
114
+ layers.append({"id": "xray", "role": "ct", "label": "X-ray", "texture": "xray/{id}.jpg", "windings": have_ct,
115
+ "source": "TODO: which scan and surface volume", "resolutionUM": round(args.voxel_mm * 1000, 3)})
116
+ if have_ink:
117
+ layers.append({"id": "ink", "role": "ink", "label": "Ink", "texture": "ink/{id}.jpg", "windings": have_ink,
118
+ "source": "TODO: which model or detection, on which scan", "resolutionUM": None})
119
+ layers[-1].pop("resolutionUM")
120
+ manifest = {
121
+ "schema": "unroll-scroll/1", "id": args.id, "name": args.name,
122
+ "description": "TODO: one or two sentences about this scroll.",
123
+ "voxelMM": args.voxel_mm,
124
+ "geometry": {"format": "mesh", "units": "voxels", "axis": "z"},
125
+ "windings": entries, "outermost": "first",
126
+ "layers": layers,
127
+ "credits": {"text": "TODO: who made the data", "url": "https://scrollprize.org", "citation": "TODO"},
128
+ "dataTerms": {"license": "TODO: for example CC BY-NC 4.0", "url": "https://creativecommons.org/licenses/by-nc/4.0/"},
129
+ }
130
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1, ensure_ascii=False) + "\n")
131
+ print(f"wrote {out / 'manifest.json'}; now run: node tools/validate_scroll.mjs {out / 'manifest.json'}")
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
tools/validate_scroll.mjs ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ // Validate the scroll registry and manifests with the same checks the page runs.
3
+ // node tools/validate_scroll.mjs all scrolls in scrolls/index.json
4
+ // node tools/validate_scroll.mjs path/to/manifest.json [--local]
5
+ // --local applies the limits used for "Open your own" (as a visitor's browser would).
6
+ // Exit code 1 if anything is wrong. Git LFS pointer files count as present.
7
+ import { readFileSync, statSync, existsSync } from 'node:fs';
8
+ import { dirname, resolve, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { validateManifest, validateRegistry, LOCAL_LIMITS, REGISTRY_LIMITS, peelOrder } from '../lib/manifest.js';
11
+
12
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
13
+ const args = process.argv.slice(2);
14
+ const local = args.includes('--local');
15
+ const paths = args.filter((a) => !a.startsWith('--'));
16
+ let bad = 0;
17
+
18
+ function lfsSize(p) {
19
+ // an LFS pointer stands for the real file: report the size it records
20
+ const st = statSync(p);
21
+ if (st.size < 400) { const t = readFileSync(p, 'utf8'); const m = /^version https:\/\/git-lfs.*\nsize (\d+)/m.exec(t); if (m) return +m[1]; }
22
+ return st.size;
23
+ }
24
+
25
+ function check(manifestPath, trusted) {
26
+ let m;
27
+ try { m = JSON.parse(readFileSync(manifestPath, 'utf8')); }
28
+ catch (e) { console.log(`FAIL ${manifestPath}: ${e.message}`); bad++; return; }
29
+ const base = resolve(dirname(manifestPath), m.base || '');
30
+ const v = validateManifest(m, {
31
+ trusted, limits: trusted ? REGISTRY_LIMITS : LOCAL_LIMITS,
32
+ fileSize: (p) => { const f = join(base, p); return existsSync(f) ? lfsSize(f) : null; },
33
+ });
34
+ const n = v.ok ? peelOrder(m).length : 0;
35
+ console.log(`${v.ok ? 'ok ' : 'FAIL'} ${manifestPath}${v.ok ? `: ${m.id}, ${n} windings, ${m.layers.length} layers, ${v.files.length} files` : ''}`);
36
+ for (const e of v.errors) console.log(` error: ${e}`);
37
+ for (const w of v.warnings) console.log(` note: ${w}`);
38
+ if (!v.ok) bad++;
39
+ }
40
+
41
+ if (paths.length) for (const p of paths) check(resolve(p), !local);
42
+ else {
43
+ const reg = JSON.parse(readFileSync(join(root, 'scrolls/index.json'), 'utf8'));
44
+ const r = validateRegistry(reg);
45
+ console.log(`${r.ok ? 'ok ' : 'FAIL'} scrolls/index.json: ${reg.scrolls?.length ?? 0} scrolls`);
46
+ for (const e of r.errors) console.log(` error: ${e}`);
47
+ if (!r.ok) bad++;
48
+ for (const s of reg.scrolls || []) check(join(root, s.manifest), true);
49
+ }
50
+ process.exit(bad ? 1 : 0);