copper3d 3.11.4 → 3.11.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +51 -1
  2. package/ai-index/guides/4D-MRI-LV-rendering.md +1 -1
  3. package/ai-index/guides/copper3d-rendering-optimization.md +37 -0
  4. package/ai-index/guides/load-callbacks.md +35 -0
  5. package/ai-index/guides/nrrd-tools.md +110 -2
  6. package/ai-index/guides/segmentation-module.md +108 -2
  7. package/ai-index/manifest.json +8 -8
  8. package/ai-index/symbols.json +1 -1
  9. package/dist/Loader/copperNrrdLoader.d.ts +33 -0
  10. package/dist/Loader/copperNrrdLoader.js +27 -5
  11. package/dist/Loader/copperNrrdLoader.js.map +1 -1
  12. package/dist/Renderer/copperRenderer.js +2 -2
  13. package/dist/Renderer/copperRenderer.js.map +1 -1
  14. package/dist/Scene/copperScene.d.ts +1 -1
  15. package/dist/Scene/copperScene.js +4 -1
  16. package/dist/Scene/copperScene.js.map +1 -1
  17. package/dist/Utils/segmentation/DragOperator.d.ts +6 -0
  18. package/dist/Utils/segmentation/DragOperator.js +9 -0
  19. package/dist/Utils/segmentation/DragOperator.js.map +1 -1
  20. package/dist/Utils/segmentation/NrrdTools.d.ts +38 -1
  21. package/dist/Utils/segmentation/NrrdTools.js +105 -2
  22. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  23. package/dist/Utils/segmentation/RenderingUtils.d.ts +7 -10
  24. package/dist/Utils/segmentation/RenderingUtils.js +14 -117
  25. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  26. package/dist/Utils/segmentation/contourPaint.d.ts +37 -0
  27. package/dist/Utils/segmentation/contourPaint.js +128 -0
  28. package/dist/Utils/segmentation/contourPaint.js.map +1 -0
  29. package/dist/Utils/segmentation/tools/DragSliceTool.js +5 -0
  30. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  31. package/dist/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  32. package/dist/Utils/segmentation/tools/MaskMirror.js +165 -0
  33. package/dist/Utils/segmentation/tools/MaskMirror.js.map +1 -0
  34. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +8 -0
  35. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  36. package/dist/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  37. package/dist/bundle.esm.js +459 -122
  38. package/dist/bundle.umd.js +459 -121
  39. package/dist/index.d.ts +2 -2
  40. package/dist/index.js +2 -2
  41. package/dist/index.js.map +1 -1
  42. package/dist/types/Loader/copperNrrdLoader.d.ts +33 -0
  43. package/dist/types/Scene/copperScene.d.ts +1 -1
  44. package/dist/types/Utils/segmentation/DragOperator.d.ts +6 -0
  45. package/dist/types/Utils/segmentation/NrrdTools.d.ts +38 -1
  46. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +7 -10
  47. package/dist/types/Utils/segmentation/contourPaint.d.ts +37 -0
  48. package/dist/types/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  49. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  50. package/dist/types/index.d.ts +2 -2
  51. package/package.json +1 -1
package/README.md CHANGED
@@ -238,6 +238,12 @@ Skipped a plane and need it later? `ensureAxisExtracted(slices, axis, meshes?)`
238
238
  demand, mutating `slices` (and `meshes`) in place. `NrrdTools.setSliceOrientation()` already
239
239
  calls it for you, so an axial-only load can still switch to sagittal or coronal.
240
240
 
241
+ Extracting a slice yourself with `Volume.extractSlice`? Run `prepareVolumeSlices(...slices)`
242
+ on the result. It gives the slice's readback buffer a `willReadFrequently` context (three
243
+ creates it without the flag, so every repaint copies the canvas back from the GPU) and
244
+ restores the geometry three's `VolumeSlice` constructor wipes. The loader does this for
245
+ everything it extracts.
246
+
241
247
  ---
242
248
 
243
249
  ## NrrdTools Usage Guide
@@ -352,6 +358,24 @@ write — the package ships without a UI and does not reach into yours. Point it
352
358
  nrrdTools.notifyUser = (message, level) => toast[level](message); // 'error' | 'warning' | 'info'
353
359
  ```
354
360
 
361
+ **Previewing one slice before the volume loads**
362
+
363
+ ```typescript
364
+ // Put one plane on screen immediately, positioned as slice `index` of the full stack
365
+ nrrdTools.showPreviewSlice(header, slice, index, async (target) => {
366
+ const next = await fetchSinglePlane(caseId, target); // `target` is already clamped
367
+ nrrdTools.showPreviewSlice(header, next, target, onSliceMove);
368
+ });
369
+
370
+ // Later, when the real volume arrives — keeps the previewed index
371
+ nrrdTools.switchSlicesPreservingView(allSlices);
372
+ ```
373
+
374
+ While previewing, wheel/keys/drag do **not** move the display — the shown slice has depth 1,
375
+ so the target index is handed to your callback to fetch instead. `header` is the full volume's
376
+ geometry, not the plane's. Axial only. `isPreviewing()` reports the state; it ends on
377
+ `switchSlicesPreservingView`, `setAllSlices` or `reset`.
378
+
355
379
  **Contrast series**
356
380
 
357
381
  A case is a series of contrasts. `addSkip` / `removeSkip` index the **full** contrast list;
@@ -509,6 +533,28 @@ leave outline mode to annotate.
509
533
 
510
534
  ---
511
535
 
536
+ ### Mask mirroring — show one viewer's masks on another
537
+
538
+ ```typescript
539
+ // `reference` draws `primary`'s masks over its own image
540
+ reference.setMaskMirror(primary);
541
+
542
+ // with a row-major 4×4 mapping reference's voxel (x, y, z, 1) → primary's voxel
543
+ reference.setMaskMirror(primary, mirrorToSource);
544
+
545
+ reference.setMaskMirror(null); // detach
546
+ ```
547
+
548
+ Everything is read live from the source — volumes, channel colours, layer and channel
549
+ visibility, per-layer opacity, fill/outline mode — so changing any of them on the source
550
+ updates the mirror on the next frame. It is display only: nothing is written to either
551
+ viewer's masks, and the mirror holds no mask data of its own.
552
+
553
+ A mirroring viewer needs no layers, so `{ layers: [] }` pairs naturally with this. `dispose()`
554
+ breaks the link from both ends.
555
+
556
+ ---
557
+
512
558
  ### Zoom range — showing below 1:1
513
559
 
514
560
  The zoom factor used to bottom out at `1`. Lower the floor and a large volume can be fitted
@@ -667,8 +713,10 @@ yourself. It throws on an unknown layer, or a channel outside `[1, 255]`.
667
713
  | | `commitSeriesLoad(slices, entries, i)` | Case-load completion — one refresh |
668
714
  | | `switchAllSlicesArrayData(slices)` | Swap the series (resets view state) |
669
715
  | | `switchSlicesPreservingView(slices)` | Swap the series, keep slice index / zoom / pan |
716
+ | **Preview** | `showPreviewSlice(header, slice, i, cb)` | Show one depth-1 slice as slice `i` of the not-yet-loaded stack; slice moves go to `cb` instead of moving the display. Axial only |
717
+ | | `isPreviewing()` | Whether a preview slice is shown |
670
718
  | **Render** | `start` | Frame callback — pass to render loop |
671
- | **Lifecycle** | `dispose()` | Release the event router's listeners, a pending slice step and the drawing-flag timer. Instance unusable afterwards; safe to call twice |
719
+ | **Lifecycle** | `dispose()` | Release the event router's listeners, a pending slice step, the drawing-flag timer and any mask-mirror link (from both ends). Instance unusable afterwards; safe to call twice |
672
720
  | **Layer** | `setActiveLayer(id)` | Switch drawing target layer |
673
721
  | | `getActiveLayer()` | Read current layer |
674
722
  | | `setLayerVisible(id, bool)` | Toggle layer in composite view |
@@ -681,6 +729,8 @@ yourself. It throws on an unknown layer, or a channel outside `[1, 255]`.
681
729
  | | `setLayerOpacity(id, opacity)` | Set per-layer opacity (0.1–1.0), triggers re-render |
682
730
  | | `getLayerOpacity(id)` | Read one layer's opacity |
683
731
  | | `getLayerOpacityMap()` | All per-layer opacity values |
732
+ | **Mirror** | `setMaskMirror(src, m?)` | Draw another viewer's masks, read live. `m` = row-major 4×4 voxel→voxel; `null` detaches. Display only |
733
+ | | `getMaskMirrorSource()` | The viewer being mirrored, or `null` |
684
734
  | **Sphere** | `setActiveSphereType(type)` | Set active sphere type, updates brush color |
685
735
  | | `getActiveSphereType()` | Read current sphere type |
686
736
  | | `setCalculateDistanceSphere(x, y, slice, type)` | Programmatically place a calculator sphere |
@@ -440,7 +440,7 @@ Versus `setInterval`, rAF syncs to the display refresh and auto-pauses when the
440
440
  animate = (time?) => {
441
441
  if (!this.running) return;
442
442
  requestAnimationFrame(this.animate); // self-scheduling
443
- this.delta += this.renderClock.getDelta();
443
+ this.delta += this.renderClock.update().getDelta(); // THREE.Timer: advance, then read
444
444
  if (this.delta > this.interval) { // only draw once enough time has accumulated (frame-rate cap)
445
445
  this.render();
446
446
  }
@@ -118,6 +118,43 @@ All lighting and rendering parameters are exposed through a dat.GUI panel for re
118
118
 
119
119
  ---
120
120
 
121
+ ## 7. Frame timing — `THREE.Timer` <Badge type="tip" text="3.11.6" />
122
+
123
+ three r185 deprecates `THREE.Clock` and warns on **every construction**. copper3d built one
124
+ per renderer and one per scene, so a viewer panel produced a warning pair each time it was
125
+ created. Both are now `THREE.Timer`.
126
+
127
+ ::: warning Breaking: `copperScene.clock` is a `THREE.Timer`
128
+ It is a public field, so code that types or constructs it has to change:
129
+
130
+ ```ts
131
+ scene.clock; // THREE.Clock → THREE.Timer
132
+ scene.clock.getDelta(); // unchanged, but see below
133
+ ```
134
+
135
+ The behavioural difference is that a `Timer` **only advances when you call `update()`** —
136
+ `getDelta()` on its own returns the same value twice.
137
+ :::
138
+
139
+ Both call sites update before reading:
140
+
141
+ ```ts
142
+ // copperRenderer.animate
143
+ this.delta += this.renderClock.update().getDelta();
144
+
145
+ // copperScene.render — every frame, not only once a model is ready
146
+ this.clock.update();
147
+ if (this.modelReady) this.mixer?.update(this.clock.getDelta() * this.playRate);
148
+ ```
149
+
150
+ `copperScene` updating unconditionally is a **fix**, not bookkeeping. `Clock.getDelta()`
151
+ measured from the previous `getDelta()` — or, on the first call, from construction. A scene
152
+ whose model finished loading five seconds after the scene was built therefore handed its
153
+ mixer a five-second first step, and the animation jumped. Updating every frame makes the
154
+ first step one frame long.
155
+
156
+ ---
157
+
121
158
  ## Architecture Diagram
122
159
 
123
160
  ```
@@ -182,6 +182,41 @@ Two consequences worth knowing:
182
182
  asset file to serve. A UMD bundle mounted at a base path unknown at build time still
183
183
  works.
184
184
 
185
+ ## `prepareVolumeSlices()`: the fixups every slice needs <Badge type="tip" text="3.11.6" />
186
+
187
+ `loadNrrd` and `ensureAxisExtracted` already call this on everything they extract. You only
188
+ need it if you call `Volume.extractSlice` yourself — for a preview plane, say:
189
+
190
+ ```ts
191
+ import { prepareVolumeSlices } from "copper3d";
192
+
193
+ const slice = volume.extractSlice("z", index * spacing[2]);
194
+ prepareVolumeSlices(slice); // variadic; `undefined` entries are skipped
195
+ ```
196
+
197
+ It does two things.
198
+
199
+ **1. Gives the readback buffer a `willReadFrequently` context.** Stock
200
+ `VolumeSlice.repaint` reads `ctxBuffer` back with `getImageData` on *every* repaint, and
201
+ three creates that context without the flag — so the canvas may live on the GPU and each
202
+ repaint copies it back to the CPU. Chrome warns once per such context.
203
+
204
+ A context's attributes are fixed by the first `getContext` call on its canvas, so the flag
205
+ cannot be added afterwards; the buffer canvas is replaced with one whose context is created
206
+ with it. A later `updateGeometry` re-fetches the same context, so the flag survives.
207
+
208
+ **2. Restores the geometry three's constructor wipes.** `VolumeSlice`'s constructor calls
209
+ `updateGeometry()` and `repaint()` and *then* assigns `iLength = 0`, `jLength = 0`,
210
+ `sliceAccess = null`, undoing what it just computed. `repaint()` only recomputes them after an
211
+ `index` change, so any repaint not preceded by one calls `ctx.getImageData(0, 0, 0, 0)` and
212
+ throws `IndexSizeError: The source width is 0`. Present in three r175 through at least r185;
213
+ a harmless recompute on r174 and earlier.
214
+
215
+ ::: tip Renamed from `repairSliceGeometry`
216
+ It was internal and only did (2). It is exported now because the preview-slice flow builds
217
+ slices outside the loader and needs both.
218
+ :::
219
+
185
220
  ## Detecting a stalled download
186
221
 
187
222
  A flat timeout is the wrong instrument for a large volume: a 53MB NRRD on a
@@ -126,6 +126,16 @@ Slice scrubbing, zoom, pan, window/level and the crosshair all work as usual. Th
126
126
  tools have no layer to target and skip their work rather than failing: `setCurrentLayer()`
127
127
  returns `null` and every caller checks it.
128
128
 
129
+ The rest of the pipeline follows the same rule <Badge type="tip" text="3.11.6" />:
130
+ `getVolumeForLayer()` returns `undefined` **without** the "unknown layer, falling back to…"
131
+ warning — there is no first layer to fall back to, and the warning was noise on a viewer that
132
+ is working as designed — and `reloadMasksFromVolume()` returns early, since there is nothing
133
+ to reload. An unknown layer id on a viewer that *does* have layers still warns and falls back,
134
+ as before.
135
+
136
+ Pairs naturally with `setMaskMirror` (§6.7): a layerless viewer still composites, so it can
137
+ show another viewer's masks over its own image.
138
+
129
139
  ::: tip Which one to reach for
130
140
  `layers: []` is a **structural** choice — this instance will never annotate.
131
141
  `setAnnotationSuspended(true)` (§5.6) is a **temporary** one on an instance that will, such as
@@ -344,6 +354,51 @@ nrrdTools.switchAllSlicesArrayData(allSlices);
344
354
  nrrdTools.switchSlicesPreservingView(allSlices);
345
355
  ```
346
356
 
357
+ #### 3.4 Previewing one slice before the volume loads <Badge type="tip" text="3.11.6" />
358
+
359
+ A large volume takes seconds to arrive. `showPreviewSlice` puts **one** slice on screen
360
+ immediately, positioned as slice `index` of the full stack, and lets the reader scrub while
361
+ the rest is still downloading:
362
+
363
+ ```typescript
364
+ nrrdTools.showPreviewSlice(header, slice, index, async (target) => {
365
+ // `target` is the clamped slice the reader asked for — fetch and show it
366
+ const next = await fetchSinglePlane(caseId, target);
367
+ nrrdTools.showPreviewSlice(header, next, target, onSliceMove);
368
+ });
369
+
370
+ nrrdTools.isPreviewing(); // → true until a full volume takes over
371
+ ```
372
+
373
+ | Parameter | What it is |
374
+ |-----------|------------|
375
+ | `header` | The **full** volume's geometry (`NrrdHeaderLike`: dimensions, spacing, space_origin) — not the single plane's |
376
+ | `slice` | A depth-1 slice triple built from one plane's voxels |
377
+ | `index` | Which slice of the full stack this plane is |
378
+ | `onSliceMove` | Receives the clamped target index for every slice move while previewing |
379
+
380
+ **While previewing, slice moves do not move the display.** Wheel, keys, drag and
381
+ `setSliceMoving` are all intercepted and handed to `onSliceMove` with the clamped target
382
+ instead — the displayed slice has depth 1, so moving it would paint blank. Fetching that
383
+ plane and calling `showPreviewSlice` again is what advances the view.
384
+
385
+ Geometry is re-initialised only when `header` differs from the current one, so calling it
386
+ repeatedly while scrubbing is cheap. It writes no mask data.
387
+
388
+ **Handing over to the real volume:**
389
+
390
+ ```typescript
391
+ const allSlices = await loadFullVolume(caseId);
392
+ nrrdTools.switchSlicesPreservingView(allSlices); // keeps the previewed index, ends previewing
393
+ ```
394
+
395
+ Previewing also ends on `setAllSlices()` and `reset()`.
396
+
397
+ ::: warning Axial only
398
+ `showPreviewSlice` does not switch orientation — it shows a `z` plane. Sagittal and coronal
399
+ need the full volume.
400
+ :::
401
+
347
402
  ---
348
403
 
349
404
  ### 4. Render Loop Integration
@@ -387,6 +442,7 @@ is torn down can actually be garbage-collected:
387
442
  | The event router's listeners | Its window `blur` listener closes over the router, which reaches the whole engine graph — one live listener pins the entire instance |
388
443
  | A pending slice step | The `requestAnimationFrame` `setSliceMoving` coalesces into |
389
444
  | The drawing-flag timer | The pending `setIsDrawFalse` timeout |
445
+ | Any mask-mirror link | Broken from **both** ends, so neither viewer keeps the other alive. Disposing a source detaches its mirrors and repaints them empty (see §6.7) |
390
446
 
391
447
  The instance must not be used afterwards. It is safe to call more than once, so an unmount
392
448
  hook that may run twice needs no guard.
@@ -920,7 +976,55 @@ upload flow, say) is expected to persist the new volume. The callback fires only
920
976
  clinician undoes or redoes the replacement, because at that point the backend holds the newer
921
977
  volume and has to be told to fall back.
922
978
 
923
- #### 6.7 Erasing one channel — `clearChannel()` <Badge type="tip" text="3.10.2" />
979
+ #### 6.7 Mirroring another viewer's masks — `setMaskMirror()` <Badge type="tip" text="3.11.5" />
980
+
981
+ Draw a **different** viewer's masks on this one. The classic use is a side-by-side: annotate
982
+ on the left, and have the right-hand study show the same findings over its own image.
983
+
984
+ ```typescript
985
+ // `reference` draws `primary`'s masks
986
+ reference.setMaskMirror(primary);
987
+
988
+ // with a voxel→voxel transform between the two grids
989
+ reference.setMaskMirror(primary, mirrorToSource); // row-major 4×4
990
+
991
+ reference.setMaskMirror(null); // detach
992
+ const src = reference.getMaskMirrorSource(); // → primary | null
993
+ ```
994
+
995
+ **Everything is read live from the source** — its volumes, channel colours, layer and channel
996
+ visibility, per-layer opacity, and its fill/outline render mode. Change any of them on the
997
+ source and the mirror follows on the next frame. A mirroring viewer needs no layers of its
998
+ own; `layers: []` pairs naturally with this.
999
+
1000
+ ::: warning Display only
1001
+ Nothing is written to either viewer's masks. The mirror holds no mask data at all — it is a
1002
+ view onto the source, so there is no copy to keep in sync and nothing to save.
1003
+ :::
1004
+
1005
+ **The transform.** `mirrorToSource` is a row-major 4×4 mapping *this* viewer's voxel
1006
+ `(x, y, z, 1)` to the source's voxel. Omit it for the identity, which is right when both
1007
+ viewers share a grid.
1008
+
1009
+ | Case | Sampling |
1010
+ |------|----------|
1011
+ | Identity **and** identical dimensions | The source's own slice, unchanged |
1012
+ | Diagonal transform (axes agree; only scale and offset differ) | A mirror voxel coarser than the source shows the first label among every source voxel it spans — so a finding thinner than the mirror's slice still appears on the slice containing it |
1013
+ | Any other transform | Nearest source voxel |
1014
+
1015
+ A cell mapping outside the source reads as empty.
1016
+
1017
+ **Refresh and teardown.** Every visible mask change on the source ends in a composite, and
1018
+ each one schedules a repaint of its mirrors on the next animation frame; repeated changes
1019
+ coalesce into one. `dispose()` breaks the link from both ends, so neither viewer keeps the
1020
+ other alive — disposing the source detaches its mirrors and repaints them empty.
1021
+
1022
+ ::: tip Sphere mode hides it
1023
+ The source hides its own layers in sphere mode, so a mirror of it shows nothing while that
1024
+ mode is active — matching what the source itself displays.
1025
+ :::
1026
+
1027
+ #### 6.8 Erasing one channel — `clearChannel()` <Badge type="tip" text="3.10.2" />
924
1028
 
925
1029
  ```typescript
926
1030
  nrrdTools.clearChannel('layer1', 3); // finding 3 goes; 1, 2 and 4 stay
@@ -1838,8 +1942,10 @@ cap it below what the byte allows. Capping it lower is your product's call, not
1838
1942
  | | `commitSeriesLoad(slices, entries, i)` | Case-load completion: swap series + reconcile skips + land on contrast, one refresh |
1839
1943
  | | `switchAllSlicesArrayData(slices)` | Swap the loaded series (resets slice index / zoom / pan) |
1840
1944
  | | `switchSlicesPreservingView(slices)` | Swap the loaded series, keeping slice index, zoom and pan |
1945
+ | **Preview** | `showPreviewSlice(header, slice, i, cb)` | Show one depth-1 slice as slice `i` of the not-yet-loaded stack. While previewing, every slice move is handed to `cb` with the clamped target instead of moving the display. Axial only; ends on `switchSlicesPreservingView` / `setAllSlices` / `reset` |
1946
+ | | `isPreviewing()` | Whether a preview slice is shown in place of a loaded volume |
1841
1947
  | **Render** | `start` | Frame callback — pass to render loop |
1842
- | **Lifecycle** | `dispose()` | Release the event router's listeners, a pending slice step and the drawing-flag timer. Instance unusable afterwards; safe to call twice |
1948
+ | **Lifecycle** | `dispose()` | Release the event router's listeners, a pending slice step, the drawing-flag timer and any mask-mirror link (from both ends). Instance unusable afterwards; safe to call twice |
1843
1949
  | **Layer** | `setActiveLayer(id)` | Switch drawing target layer |
1844
1950
  | | `getActiveLayer()` | Read current layer |
1845
1951
  | | `setLayerVisible(id, bool)` | Toggle layer in composite view |
@@ -1852,6 +1958,8 @@ cap it below what the byte allows. Capping it lower is your product's call, not
1852
1958
  | | `setLayerOpacity(id, opacity)` | Set per-layer opacity (0.1–1.0), triggers re-render |
1853
1959
  | | `getLayerOpacity(id)` | Get opacity for a specific layer |
1854
1960
  | | `getLayerOpacityMap()` | Get all per-layer opacity values |
1961
+ | **Mirror** | `setMaskMirror(src, m?)` | Draw another viewer's masks, read live from it. `m` = row-major 4×4 mapping this viewer's voxel to the source's; `null` detaches. Display only — nothing is written to either viewer |
1962
+ | | `getMaskMirrorSource()` | The viewer being mirrored, or `null` |
1855
1963
  | **Sphere** | `setActiveSphereType(type)` | Set active sphere type (`'tumour'`/`'skin'`/`'nipple'`/`'ribcage'`), updates brush color |
1856
1964
  | | `getActiveSphereType()` | Read current sphere type |
1857
1965
  | **Channel** | `setActiveChannel(ch)` | Switch drawing target channel |
@@ -328,6 +328,8 @@ The `a` (alpha) field determines the base mask opacity. Usually set to `255`; ac
328
328
  | `setAllSlices` | `(allSlices: Array<nrrdSliceType>): void` | **Entry point**: Load NRRD slices and initialize all MaskVolumes to the correct dimensions |
329
329
  | `initFromHeader` | `(header: NrrdHeaderLike): void` | Size image metadata and MaskVolumes from volume geometry alone, before any pixel data exists. `allSlicesArray` is untouched |
330
330
  | `appendSlice` | `(slice: nrrdSliceType, order: number): void` | Append one already-loaded slice to the contrast series and refresh display slices / undo state |
331
+ | `showPreviewSlice` | `(header, slice, index, onSliceMove): void` *(NrrdTools)* | Show one depth-1 slice as slice `index` of the not-yet-loaded stack, and route slice moves to `onSliceMove` until a real volume takes over |
332
+ | `isPreviewing` | `(): boolean` *(NrrdTools)* | Whether a preview slice is shown |
331
333
  | `setMasksData` | `(masksData, loadingBar?): void` | Legacy loading method (deprecated, pending removal) |
332
334
  | `setMasksFromNIfTI` | `(layerVoxels: Map<string, Uint8Array>, loadingBar?): void` | Load mask data from NIfTI files into MaskVolume, validating each buffer's grid |
333
335
  | `registerNiftiMaskGrid` | `(data: Uint8Array, dims: number[]): void` *(module export)* | Record a mask buffer's NIfTI voxel grid, keyed by buffer identity, for `setMasksFromNIfTI` to check |
@@ -351,6 +353,41 @@ The split exists so a progressive loader can size everything from a backend head
351
353
  (`{ dimensions, spacing, space_origin }` as JSON — the same `NrrdHeaderLike` shape) and then
352
354
  feed slices in one at a time with `appendSlice` as they arrive.
353
355
 
356
+ #### Preview slices <Badge type="tip" text="3.11.6" />
357
+
358
+ `NrrdTools.showPreviewSlice(header, slice, index, onSliceMove)` is the progressive path's
359
+ front end, and it is built from the two pieces above:
360
+
361
+ ```
362
+ showPreviewSlice(header, slice, index, onSliceMove)
363
+ │
364
+ ├─ geometry differs from the current one? → dataLoader.initFromHeader(header)
365
+ │ (compared field-by-field on dimensions / spacing / space_origin, so repeated
366
+ │ calls while scrubbing re-initialise nothing)
367
+ │
368
+ ├─ slice.z.initIndex = index ◀ the full-stack index lives here, NOT in the
369
+ │ depth-1 slice's own `index`, where it would
370
+ │ be out of range
371
+ ├─ allSlicesArray.length = 0
372
+ ├─ sliceRenderPipeline.resetInitState()
373
+ ├─ dataLoader.appendSlice(slice, 0) ◀ one slice, so appendSlice is the right call here
374
+ └─ _previewSliceMove = onSliceMove
375
+ ```
376
+
377
+ **The slice-move interception.** While `_previewSliceMove` is set, `DragSliceTool` clamps the
378
+ requested index to `[minIndex, maxIndex]` and offers it to `previewSliceMove(target)`; a
379
+ `true` return means the move was consumed and the tool returns without touching the display.
380
+ The displayed slice has depth 1, so moving it would paint blank — the host is expected to
381
+ fetch that plane and call `showPreviewSlice` again.
382
+
383
+ The hook reaches `DragSliceTool` as a `ToolHost` dependency
384
+ (`DragSliceHostDeps` gained `previewSliceMove`), wired through
385
+ `DragOperator.setPreviewSliceMove`. Before `NrrdTools` sets it, the default returns `false`,
386
+ so every move proceeds normally.
387
+
388
+ `_previewSliceMove` is cleared by `setAllSlices`, `switchSlicesPreservingView` and `reset` —
389
+ the three ways a real volume takes over. `isPreviewing()` reports whether it is set.
390
+
354
391
  ::: warning `appendSlice` is not a loop-friendly substitute for `setAllSlices`
355
392
  It calls `setDisplaySlicesBaseOnAxis()` per slice, which rebuilds the display-slice list from
356
393
  a still-growing `allSlicesArray`, and whose `skipSlicesDic` bookkeeping assumes it is seeing
@@ -447,6 +484,15 @@ mode it redraws what is already on screen, and a mode-dependent branch there is
447
484
  that can fall out of step with the renderer. The display mode returns at pointer-up, via
448
485
  `refreshLayerFromVolume`.
449
486
 
487
+ ::: tip Both live in `contourPaint.ts` <Badge type="tip" text="3.11.5" />
488
+ The cache entry, the path building and the painting were extracted out of `RenderingUtils`
489
+ into `contourPaint.ts` so `MaskMirror` (§2.7) can paint a source viewer's masks with exactly
490
+ the same code — same cache shape, same fill/outline choice, same stroke geometry. Its exports
491
+ are `ContourEntry`, `LabelSlice`, `contourEntry(...)`, `paintContours(...)` and
492
+ `OUTLINE_WIDTH_PX`. `RenderingUtils` keeps the slice buffer, the compositing and the
493
+ per-layer cache map.
494
+ :::
495
+
450
496
  ##### Path cache
451
497
 
452
498
  The render mode is **not** part of the cache key. Each entry holds two lazily-built maps:
@@ -527,14 +573,74 @@ nrrdTools.setCalculateDistanceSphere(120, 95, 42, 'tumour');
527
573
  nrrdTools.setCalculateDistanceSphere(200, 150, 42, 'skin');
528
574
  ```
529
575
 
530
- ### 2.7 Other APIs
576
+ ### 2.7 Mask Mirroring <Badge type="tip" text="3.11.5" />
577
+
578
+ > **Implementation**: `tools/MaskMirror.ts`, painting through `contourPaint.ts`.
579
+
580
+ | Method | Signature | Description |
581
+ |--------|-----------|-------------|
582
+ | `setMaskMirror` | `(source: NrrdTools \| null, mirrorToSource?: ArrayLike<number>): void` | Draw `source`'s masks on this viewer. `null` — or passing this viewer itself — detaches |
583
+ | `getMaskMirrorSource` | `(): NrrdTools \| null` | The viewer being mirrored |
584
+
585
+ **`MaskMirror` holds no mask data.** Every paint reads the source's `CanvasState` live:
586
+ volumes, channel colours, layer/channel visibility, per-layer opacity and `maskRenderMode`.
587
+ There is no copy, so there is nothing to keep in sync and nothing to invalidate on an edit.
588
+
589
+ ```
590
+ NrrdTools A (source) NrrdTools B (mirror)
591
+ renderer.onComposited ──┐ renderer.mirror = MaskMirror(B.state, A.state, m)
592
+ │ │
593
+ A.scheduleMirrorRefresh() │
594
+ └─ rAF, coalesced ─────┴──► B.compositeAllLayers() ─┘
595
+ └─ …B's own layers, then mirror.paint(masterCtx, w, h)
596
+ ```
597
+
598
+ `compositeAllLayers` calls `this.mirror?.paint(...)` after the viewer's own layers, then fires
599
+ `onComposited`. So a mirror is painted **on top of** whatever the mirroring viewer has of its
600
+ own — usually nothing, since such a viewer is typically constructed with `layers: []`.
601
+
602
+ `SliceRenderPipeline` short-circuits to a plain `compositeAllLayers()` when
603
+ `hasMaskMirror()` is true: a mirroring viewer has no layers of its own to render.
604
+
605
+ #### Sampling — `mirrorSliceLabels`
606
+
607
+ The transform is a row-major 4×4 from **this** viewer's voxel `(x, y, z, 1)` to the source's.
608
+ Slices are built in `MaskVolume.getSliceUint8`'s layout for this viewer's own grid, so the
609
+ shared paint code draws them unchanged, flips included.
610
+
611
+ | Case | Path |
612
+ |------|------|
613
+ | `isIdentity(m)` **and** matching dimensions | Returns the source's own slice directly — no resampling |
614
+ | `isDiagonal(m)` (each axis maps onto its own) | `coveredRanges` gives, per mirror index, the inclusive source range it spans. A mirror voxel **coarser** than the source takes the first label among every source voxel it covers |
615
+ | Otherwise | Nearest source voxel |
616
+
617
+ The coarse-voxel rule is the one worth knowing: it means a finding thinner than the mirror's
618
+ slice still appears on the slice that contains it, instead of falling between samples. A cell
619
+ mapping outside the source reads as `0`.
620
+
621
+ #### Cache and failure handling
622
+
623
+ One `ContourEntry` per source layer, keyed `axis:index:volume.getVersion()`. The mirror also
624
+ tracks which `MaskVolume` object each entry came from and drops the entry when it changes — a
625
+ case load replaces the object, and the version counter alone would not notice.
626
+
627
+ A new transform means a **new `MaskMirror` instance**, so a cache can never hold contours
628
+ built under a different transform.
629
+
630
+ `paint` is defensive at two levels: the per-layer `try` swallows a source that is not ready
631
+ for this slice (nothing drawn for that layer), and a `finally` restores the canvas so a throw
632
+ cannot leave a layer's `globalAlpha` or transform on the master canvas. It also returns early
633
+ when the source is in sphere mode, which hides the source's own layers — so the mirror shows
634
+ what the source shows.
635
+
636
+ ### 2.8 Other APIs
531
637
 
532
638
  > **Implementation**: Directly in the NrrdTools Facade (section 5 View Control, section 6 Data Getters).
533
639
 
534
640
  | Method | Description |
535
641
  |--------|-------------|
536
642
  | `drag(opts?)` | Enable drag-to-scroll slice navigation |
537
- | `dispose()` | Teardown: `eventRouter.unbindAll()`, cancel the pending slice-step `requestAnimationFrame`, clear the `setIsDrawFalse` timer. Releases only what the instance attached outside its own DOM subtree — the window `blur` listener is the one that pins the whole engine graph. Instance unusable afterwards; idempotent |
643
+ | `dispose()` | Teardown: `eventRouter.unbindAll()`, cancel the pending slice-step `requestAnimationFrame`, clear the `setIsDrawFalse` timer, and break any mask-mirror link from both ends (disposing a source detaches its mirrors and repaints them empty). Releases only what the instance attached outside its own DOM subtree — the window `blur` listener is the one that pins the whole engine graph. Instance unusable afterwards; idempotent |
538
644
  | `setAnnotationSuspended(bool)` | Block every input that can write into a mask, at `DrawToolCore.onCanvasPointerDown`. Slice scrubbing, zoom, pan and the crosshair stay live (see 7.1) |
539
645
  | `isAnnotationSuspended()` | Query the suspension state |
540
646
  | `setSliceOrientation(axis)` | Switch viewing axis. Calls `ensureAxisExtracted` for every loaded contrast first, so a narrowed-axes load can still switch planes |
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "copper3dVersion": "3.11.4",
4
- "generatedAt": "2026-09-30T02:19:02.822Z",
5
- "symbolCount": 1198,
3
+ "copper3dVersion": "3.11.6",
4
+ "generatedAt": "2026-10-07T11:14:00.570Z",
5
+ "symbolCount": 1203,
6
6
  "guides": [
7
7
  {
8
8
  "id": "4D-MRI-LV-rendering",
@@ -10,7 +10,7 @@
10
10
  "title": "4D Heart (MRI + LV Surfaces) Aligned Rendering — Deep Dive",
11
11
  "summary": "Using `src/pages/example15_mri_lv_4d.vue` as the worked example, this explains how \"32 MRI images + 64 VTK models\" are loaded, aligned, and played back together on a single cardiac clock.",
12
12
  "lang": "en",
13
- "bytes": 27260
13
+ "bytes": 27306
14
14
  },
15
15
  {
16
16
  "id": "ai-assist-api",
@@ -50,7 +50,7 @@
50
50
  "title": "Copper3D GLB Rendering Optimization",
51
51
  "summary": "This document describes the rendering optimizations applied to the Copper3D library's Three.js pipeline to improve GLB model visual quality in the medical image annotator. The original rendering produced dull, dark, and detail-less models.…",
52
52
  "lang": "en",
53
- "bytes": 6770
53
+ "bytes": 8193
54
54
  },
55
55
  {
56
56
  "id": "gltf-decoders",
@@ -74,7 +74,7 @@
74
74
  "title": "Load Progress & Errors",
75
75
  "summary": "Every loader in copper3d gained `onProgress` and `onError` in **3.9.0**. Before that there was no way to find out that a load had failed — a broken URL, a 404, a corrupt file and a very slow download all looked identical from outside: the …",
76
76
  "lang": "en",
77
- "bytes": 9327
77
+ "bytes": 11087
78
78
  },
79
79
  {
80
80
  "id": "mcp-server",
@@ -90,7 +90,7 @@
90
90
  "title": "NrrdTools Usage Guide",
91
91
  "summary": "Copper3D `NrrdTools` — Medical Image Segmentation Annotation Engine",
92
92
  "lang": "en",
93
- "bytes": 75810
93
+ "bytes": 81653
94
94
  },
95
95
  {
96
96
  "id": "on-demand-controls",
@@ -122,7 +122,7 @@
122
122
  "title": "Segmentation Module Documentation",
123
123
  "summary": "⚠️ **Note**: All line number references in this document are from historical versions. After multiple rounds of refactoring (State Management Refactor, NrrdTools God Class Split, inheritance → composition refactor), these references are ou…",
124
124
  "lang": "en",
125
- "bytes": 76560
125
+ "bytes": 82753
126
126
  },
127
127
  {
128
128
  "id": "surface-annotation-api",