copper3d 3.11.3 → 3.11.5

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 (46) hide show
  1. package/README.md +50 -3
  2. package/ai-index/guides/nrrd-tools.md +127 -5
  3. package/ai-index/guides/segmentation-module.md +146 -3
  4. package/ai-index/manifest.json +5 -5
  5. package/ai-index/symbols.json +1 -1
  6. package/dist/Utils/segmentation/CanvasState.js +0 -1
  7. package/dist/Utils/segmentation/CanvasState.js.map +1 -1
  8. package/dist/Utils/segmentation/DragOperator.d.ts +6 -0
  9. package/dist/Utils/segmentation/DragOperator.js +9 -0
  10. package/dist/Utils/segmentation/DragOperator.js.map +1 -1
  11. package/dist/Utils/segmentation/DrawToolCore.js +0 -14
  12. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  13. package/dist/Utils/segmentation/NrrdTools.d.ts +38 -1
  14. package/dist/Utils/segmentation/NrrdTools.js +105 -2
  15. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  16. package/dist/Utils/segmentation/RenderingUtils.d.ts +5 -9
  17. package/dist/Utils/segmentation/RenderingUtils.js +10 -116
  18. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  19. package/dist/Utils/segmentation/contourPaint.d.ts +37 -0
  20. package/dist/Utils/segmentation/contourPaint.js +128 -0
  21. package/dist/Utils/segmentation/contourPaint.js.map +1 -0
  22. package/dist/Utils/segmentation/core/types.d.ts +0 -1
  23. package/dist/Utils/segmentation/eventRouter/EventRouter.js +0 -1
  24. package/dist/Utils/segmentation/eventRouter/EventRouter.js.map +1 -1
  25. package/dist/Utils/segmentation/eventRouter/types.d.ts +0 -1
  26. package/dist/Utils/segmentation/tools/DragSliceTool.js +5 -0
  27. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  28. package/dist/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  29. package/dist/Utils/segmentation/tools/MaskMirror.js +165 -0
  30. package/dist/Utils/segmentation/tools/MaskMirror.js.map +1 -0
  31. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +5 -0
  32. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  33. package/dist/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  34. package/dist/Utils/segmentation/tools/ZoomTool.js +32 -2
  35. package/dist/Utils/segmentation/tools/ZoomTool.js.map +1 -1
  36. package/dist/bundle.esm.js +450 -130
  37. package/dist/bundle.umd.js +450 -130
  38. package/dist/types/Utils/segmentation/DragOperator.d.ts +6 -0
  39. package/dist/types/Utils/segmentation/NrrdTools.d.ts +38 -1
  40. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +5 -9
  41. package/dist/types/Utils/segmentation/contourPaint.d.ts +37 -0
  42. package/dist/types/Utils/segmentation/core/types.d.ts +0 -1
  43. package/dist/types/Utils/segmentation/eventRouter/types.d.ts +0 -1
  44. package/dist/types/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  45. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  46. package/package.json +1 -1
@@ -109321,6 +109321,11 @@ void main() {
109321
109321
  }
109322
109322
  let newIndex = view.currentSliceIndex + sliceModifyNum;
109323
109323
  if (newIndex != view.currentSliceIndex || view.showContrast) {
109324
+ // While a preview slice is shown the displayed slice has depth 1, so moving it would
109325
+ // paint blank; the host fetches the target slice instead.
109326
+ const target = Math.min(Math.max(newIndex, view.minIndex), view.maxIndex);
109327
+ if (this.callbacks.previewSliceMove(target))
109328
+ return;
109324
109329
  if (newIndex > view.maxIndex) {
109325
109330
  newIndex = view.maxIndex;
109326
109331
  view.contrastNum = this.ctx.protectedData.displaySlices.length - 1;
@@ -109449,6 +109454,7 @@ void main() {
109449
109454
  };
109450
109455
  this.sensitiveArray = [];
109451
109456
  this.refreshSphereOverlayCb = null;
109457
+ this.previewSliceMoveCb = () => false;
109452
109458
  // EventRouter for centralized event handling
109453
109459
  this.eventRouter = null;
109454
109460
  this.configDragMode = () => {
@@ -109506,6 +109512,7 @@ void main() {
109506
109512
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, targetCtx, w, h) => this.renderSliceToCanvas(layer, axis, sliceIndex, buffer, targetCtx, w, h),
109507
109513
  compositeAllLayers: () => this.compositeAllLayers(),
109508
109514
  refreshSphereOverlay: () => { var _a; return (_a = this.refreshSphereOverlayCb) === null || _a === void 0 ? void 0 : _a.call(this); },
109515
+ previewSliceMove: (index) => this.previewSliceMoveCb(index),
109509
109516
  }, this.showDragNumberDiv, dragEffectCanvases);
109510
109517
  }
109511
109518
  setShowDragNumberDiv(sliceIndexContainer) {
@@ -109519,6 +109526,13 @@ void main() {
109519
109526
  setRefreshSphereOverlay(cb) {
109520
109527
  this.refreshSphereOverlayCb = cb;
109521
109528
  }
109529
+ /**
109530
+ * Set the callback that may consume a slice move while a preview slice is shown.
109531
+ * Called by NrrdTools; until then every move proceeds normally.
109532
+ */
109533
+ setPreviewSliceMove(cb) {
109534
+ this.previewSliceMoveCb = cb;
109535
+ }
109522
109536
  /**
109523
109537
  * Set the EventRouter reference for centralized event handling.
109524
109538
  * Called by NrrdTools/DrawToolCore after EventRouter is initialized.
@@ -109605,6 +109619,125 @@ void main() {
109605
109619
  * stay visible against bright tissue.
109606
109620
  */
109607
109621
  const OUTLINE_WIDTH_PX = 1.5;
109622
+ /**
109623
+ * Populate one cache entry's paths for one render mode.
109624
+ *
109625
+ * Split out because the two modes are built at different times: whichever is in use when
109626
+ * a slice is first drawn, and the other one only if the clinician switches while still on
109627
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
109628
+ * sessions never turn on.
109629
+ */
109630
+ function buildPaths(entry, data, stride, outline) {
109631
+ const target = outline ? entry.outlines : entry.fills;
109632
+ for (const lbl of entry.labels) {
109633
+ target.set(lbl, outline
109634
+ ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109635
+ : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109636
+ }
109637
+ }
109638
+ /**
109639
+ * The cached contours for `slot` under `key`, extracting on a miss. One entry per slot: a new
109640
+ * key overwrites it. `readSlice` is called only when extraction is needed.
109641
+ */
109642
+ function contourEntry(cache, slot, key, readSlice, outline) {
109643
+ // Cache miss → run the expensive extraction once. Hits (zoom,
109644
+ // recomposite, contrast toggle) skip straight to the draw.
109645
+ let entry = cache.get(slot);
109646
+ if (!entry || entry.key !== key) {
109647
+ const slice = readSlice();
109648
+ entry = {
109649
+ key,
109650
+ W: slice.width,
109651
+ H: slice.height,
109652
+ labels: findLabelsInSlice(slice.data, slice.width, slice.height, slice.stride, 0),
109653
+ fills: new Map(),
109654
+ outlines: new Map(),
109655
+ };
109656
+ cache.set(slot, entry);
109657
+ buildPaths(entry, slice.data, slice.stride, outline);
109658
+ }
109659
+ else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109660
+ // The mode changed since this slice was last drawn, so the other set of
109661
+ // paths is cached and this one is not. Re-read the slice and build it; from
109662
+ // here on both are present and toggling is a pure cache hit.
109663
+ const slice = readSlice();
109664
+ buildPaths(entry, slice.data, slice.stride, outline);
109665
+ }
109666
+ return entry;
109667
+ }
109668
+ /** Paint an entry's visible labels onto `targetCtx`, scaled from voxels to `scaledWidth × scaledHeight`. */
109669
+ function paintContours(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis) {
109670
+ if (entry.labels.length === 0)
109671
+ return;
109672
+ targetCtx.save();
109673
+ // A throw (a missing colour, say) must not leave the transform on the target.
109674
+ try {
109675
+ drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis);
109676
+ }
109677
+ finally {
109678
+ targetCtx.restore();
109679
+ }
109680
+ }
109681
+ function drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis) {
109682
+ const { W, H, labels } = entry;
109683
+ const paths = outline ? entry.outlines : entry.fills;
109684
+ // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109685
+ // it off to match the rest of the pipeline.
109686
+ targetCtx.imageSmoothingEnabled = false;
109687
+ if (outline) {
109688
+ // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109689
+ // in the path instead. `lineWidth` is then measured in screen pixels, which
109690
+ // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109691
+ // thickens the line with the zoom, exactly when the clinician has magnified
109692
+ // the image to look at the boundary — and because voxels are rarely isotropic
109693
+ // (sx !== sy), it also comes out thicker in one axis than the other.
109694
+ const matrix = new DOMMatrix();
109695
+ if (axis === "y") {
109696
+ matrix.scaleSelf(1, -1);
109697
+ matrix.translateSelf(0, -scaledHeight);
109698
+ }
109699
+ matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109700
+ targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109701
+ // Segments are emitted per cell and meet at shared endpoints; round caps
109702
+ // close those joins. Canvas composites a whole Path2D in one pass, so the
109703
+ // overlap costs no doubled alpha.
109704
+ targetCtx.lineJoin = "round";
109705
+ targetCtx.lineCap = "round";
109706
+ for (const lbl of labels) {
109707
+ if (channelVis && channelVis[lbl] === false)
109708
+ continue;
109709
+ const path = paths.get(lbl);
109710
+ if (!path)
109711
+ continue;
109712
+ const color = colorOf(lbl);
109713
+ targetCtx.strokeStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109714
+ const display = new Path2D();
109715
+ display.addPath(path, matrix);
109716
+ targetCtx.stroke(display);
109717
+ }
109718
+ return;
109719
+ }
109720
+ // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109721
+ // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109722
+ // so the flip operates in display coordinates.
109723
+ if (axis === "y") {
109724
+ targetCtx.scale(1, -1);
109725
+ targetCtx.translate(0, -scaledHeight);
109726
+ }
109727
+ // Voxel coord (x ∈ [0, W], y ∈ [0, H]) → display coord.
109728
+ targetCtx.scale(scaledWidth / W, scaledHeight / H);
109729
+ for (const lbl of labels) {
109730
+ if (channelVis && channelVis[lbl] === false)
109731
+ continue;
109732
+ const path = paths.get(lbl);
109733
+ if (!path)
109734
+ continue;
109735
+ const color = colorOf(lbl);
109736
+ targetCtx.fillStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109737
+ targetCtx.fill(path, "nonzero");
109738
+ }
109739
+ }
109740
+
109608
109741
  /**
109609
109742
  * RenderingUtils — Rendering / slice-buffer helper methods.
109610
109743
  *
@@ -109619,6 +109752,10 @@ void main() {
109619
109752
  constructor(state) {
109620
109753
  /** Injected callback — set by owner after construction. */
109621
109754
  this.setEmptyCanvasSize = () => { };
109755
+ /** Set while this viewer draws another viewer's masks; painted after this viewer's own layers. */
109756
+ this.mirror = null;
109757
+ /** Called after every composite. The owner refreshes the viewers mirroring this one. */
109758
+ this.onComposited = null;
109622
109759
  // Reusable ImageData buffer for zero-allocation slice rendering
109623
109760
  this._reusableSliceBuffer = null;
109624
109761
  this._reusableBufferWidth = 0;
@@ -109728,22 +109865,6 @@ void main() {
109728
109865
  return null; // Volume not ready
109729
109866
  }
109730
109867
  }
109731
- /**
109732
- * Populate one cache entry's paths for one render mode.
109733
- *
109734
- * Split out because the two modes are built at different times: whichever is in use when
109735
- * a slice is first drawn, and the other one only if the clinician switches while still on
109736
- * that slice. Building both eagerly would make every slice scrub pay for a mode most
109737
- * sessions never turn on.
109738
- */
109739
- buildPaths(entry, data, stride, outline) {
109740
- const target = outline ? entry.outlines : entry.fills;
109741
- for (const lbl of entry.labels) {
109742
- target.set(lbl, outline
109743
- ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109744
- : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109745
- }
109746
- }
109747
109868
  /**
109748
109869
  * Render a layer's slice onto the target canvas as vector contours.
109749
109870
  *
@@ -109781,96 +109902,8 @@ void main() {
109781
109902
  const volume = this.getVolumeForLayer(layer);
109782
109903
  if (!volume)
109783
109904
  return;
109784
- const stride = volume.getChannels();
109785
- const cacheKey = `${axis}:${sliceIndex}:${volume.getVersion()}`;
109786
- // Cache miss → run the expensive extraction once. Hits (zoom,
109787
- // recomposite, contrast toggle) skip straight to the draw below.
109788
- let entry = this._contourCache.get(layer);
109789
- if (!entry || entry.key !== cacheKey) {
109790
- const slice = volume.getSliceUint8(sliceIndex, axis);
109791
- entry = {
109792
- key: cacheKey,
109793
- W: slice.width,
109794
- H: slice.height,
109795
- labels: findLabelsInSlice(slice.data, slice.width, slice.height, stride, 0),
109796
- fills: new Map(),
109797
- outlines: new Map(),
109798
- };
109799
- this._contourCache.set(layer, entry);
109800
- this.buildPaths(entry, slice.data, stride, outline);
109801
- }
109802
- else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109803
- // The mode changed since this slice was last drawn, so the other set of
109804
- // paths is cached and this one is not. Re-read the slice and build it; from
109805
- // here on both are present and toggling is a pure cache hit.
109806
- const slice = volume.getSliceUint8(sliceIndex, axis);
109807
- this.buildPaths(entry, slice.data, stride, outline);
109808
- }
109809
- if (entry.labels.length === 0)
109810
- return;
109811
- const { W, H, labels } = entry;
109812
- const paths = outline ? entry.outlines : entry.fills;
109813
- const channelVis = this.state.gui_states.layerChannel.channelVisibility[layer];
109814
- targetCtx.save();
109815
- // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109816
- // it off to match the rest of the pipeline.
109817
- targetCtx.imageSmoothingEnabled = false;
109818
- if (outline) {
109819
- // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109820
- // in the path instead. `lineWidth` is then measured in screen pixels, which
109821
- // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109822
- // thickens the line with the zoom, exactly when the clinician has magnified
109823
- // the image to look at the boundary — and because voxels are rarely isotropic
109824
- // (sx !== sy), it also comes out thicker in one axis than the other.
109825
- const matrix = new DOMMatrix();
109826
- if (axis === 'y') {
109827
- matrix.scaleSelf(1, -1);
109828
- matrix.translateSelf(0, -scaledHeight);
109829
- }
109830
- matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109831
- targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109832
- // Segments are emitted per cell and meet at shared endpoints; round caps
109833
- // close those joins. Canvas composites a whole Path2D in one pass, so the
109834
- // overlap costs no doubled alpha.
109835
- targetCtx.lineJoin = 'round';
109836
- targetCtx.lineCap = 'round';
109837
- for (const lbl of labels) {
109838
- if (channelVis && channelVis[lbl] === false)
109839
- continue;
109840
- const path = paths.get(lbl);
109841
- if (!path)
109842
- continue;
109843
- const color = volume.getChannelColor(lbl);
109844
- targetCtx.strokeStyle =
109845
- `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109846
- const display = new Path2D();
109847
- display.addPath(path, matrix);
109848
- targetCtx.stroke(display);
109849
- }
109850
- targetCtx.restore();
109851
- return;
109852
- }
109853
- // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109854
- // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109855
- // so the flip operates in display coordinates.
109856
- if (axis === 'y') {
109857
- targetCtx.scale(1, -1);
109858
- targetCtx.translate(0, -scaledHeight);
109859
- }
109860
- // Voxel coord (x ∈ [0, W], y ∈ [0, H]) → display coord.
109861
- targetCtx.scale(scaledWidth / W, scaledHeight / H);
109862
- for (const lbl of labels) {
109863
- if (channelVis && channelVis[lbl] === false)
109864
- continue;
109865
- const path = paths.get(lbl);
109866
- if (!path)
109867
- continue;
109868
- const color = volume.getChannelColor(lbl);
109869
- targetCtx.fillStyle =
109870
- `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109871
- targetCtx.fill(path, 'nonzero');
109872
- }
109873
- targetCtx.restore();
109905
+ const entry = contourEntry(this._contourCache, layer, `${axis}:${sliceIndex}:${volume.getVersion()}`, () => (Object.assign(Object.assign({}, volume.getSliceUint8(sliceIndex, axis)), { stride: volume.getChannels() })), outline);
109906
+ paintContours(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, (lbl) => volume.getChannelColor(lbl), this.state.gui_states.layerChannel.channelVisibility[layer]);
109874
109907
  }
109875
109908
  catch (_a) {
109876
109909
  // Slice out of bounds or volume not ready — skip silently
@@ -109910,7 +109943,7 @@ void main() {
109910
109943
  * Only draws layers whose visibility is enabled.
109911
109944
  */
109912
109945
  compositeAllLayers() {
109913
- var _a, _b;
109946
+ var _a, _b, _c, _d;
109914
109947
  const masterCtx = this.state.protectedData.ctxes.drawingLayerMasterCtx;
109915
109948
  const width = this.state.nrrd_states.view.changedWidth;
109916
109949
  const height = this.state.nrrd_states.view.changedHeight;
@@ -109927,6 +109960,8 @@ void main() {
109927
109960
  masterCtx.restore();
109928
109961
  }
109929
109962
  }
109963
+ (_c = this.mirror) === null || _c === void 0 ? void 0 : _c.paint(masterCtx, width, height);
109964
+ (_d = this.onComposited) === null || _d === void 0 ? void 0 : _d.call(this);
109930
109965
  }
109931
109966
  }
109932
109967
 
@@ -109951,7 +109986,6 @@ void main() {
109951
109986
  redo: 'y',
109952
109987
  contrast: ['Control', 'Meta'],
109953
109988
  crosshair: 'c',
109954
- sphere: 'q',
109955
109989
  mouseWheel: 'Scroll:Zoom'
109956
109990
  };
109957
109991
  /**
@@ -110737,6 +110771,37 @@ void main() {
110737
110771
  * Extracted from DrawToolCore.ts:
110738
110772
  * - configMouseZoomWheel
110739
110773
  */
110774
+ /** Pixels one wheel notch scrolls in Chrome; one notch zooms by 10%. */
110775
+ const PIXELS_PER_NOTCH = 100;
110776
+ const LOG_STEP_PER_PIXEL = Math.log(1.1) / PIXELS_PER_NOTCH;
110777
+ /** deltaMode 1 (lines, Firefox) and 2 (pages) in pixels, so a notch is ~100px everywhere. */
110778
+ const PIXELS_PER_LINE = 33;
110779
+ const PIXELS_PER_PAGE = 800;
110780
+ /** A single event zooms by at most this ratio, so one runaway delta cannot jump the view. */
110781
+ const MAX_RATIO_PER_EVENT = 2;
110782
+ /**
110783
+ * The zoom ratio for one wheel event, proportional to how far it scrolled. A busy page makes
110784
+ * the browser coalesce wheel events and sum their deltas, so counting events would zoom a
110785
+ * heavy view slower than a light one; following the distance zooms both alike, and lets a
110786
+ * trackpad's small deltas zoom smoothly. Scrolling down (positive deltaY) zooms out.
110787
+ */
110788
+ function wheelZoomRatio(e) {
110789
+ let px = e.deltaY;
110790
+ if (!Number.isFinite(px) || px === 0) {
110791
+ // No deltaY (legacy events): one notch in the direction detail/wheelDelta gives.
110792
+ const out = e.detail ? e.detail > 0 : e.wheelDelta < 0;
110793
+ px = out ? PIXELS_PER_NOTCH : -PIXELS_PER_NOTCH;
110794
+ }
110795
+ else if (e.deltaMode === 1) {
110796
+ px *= PIXELS_PER_LINE;
110797
+ }
110798
+ else if (e.deltaMode === 2) {
110799
+ px *= PIXELS_PER_PAGE;
110800
+ }
110801
+ const maxLog = Math.log(MAX_RATIO_PER_EVENT);
110802
+ const log = Math.max(-maxLog, Math.min(maxLog, -px * LOG_STEP_PER_PIXEL));
110803
+ return Math.exp(log);
110804
+ }
110740
110805
  class ZoomTool extends BaseTool {
110741
110806
  constructor(ctx, container, mainAreaContainer, callbacks) {
110742
110807
  super(ctx);
@@ -110783,7 +110848,6 @@ void main() {
110783
110848
  return;
110784
110849
  }
110785
110850
  e.preventDefault();
110786
- const delta = e.detail ? e.detail > 0 : e.wheelDelta < 0;
110787
110851
  this.ctx.protectedData.isDrawing = true;
110788
110852
  const rect = this.container.getBoundingClientRect();
110789
110853
  const drawingCanvas = this.ctx.protectedData.canvases.drawingCanvas;
@@ -110791,7 +110855,7 @@ void main() {
110791
110855
  drawingCanvas.offsetWidth;
110792
110856
  const ratioT = (e.clientY - rect.top - this.mainAreaContainer.offsetTop - drawingCanvas.offsetTop) /
110793
110857
  drawingCanvas.offsetHeight;
110794
- const ratioDelta = !delta ? 1 + 0.1 : 1 - 0.1;
110858
+ const ratioDelta = wheelZoomRatio(e);
110795
110859
  // Compound from the latest pending target (this frame) or the current
110796
110860
  // committed sizeFactor.
110797
110861
  const base = pending ? pending.moveDistance : this.ctx.nrrd_states.view.sizeFactor;
@@ -113550,20 +113614,6 @@ void main() {
113550
113614
  return; // Ctrl takes priority
113551
113615
  }
113552
113616
  }
113553
- // Handle sphere mode toggle
113554
- if (ev.key === this.state.keyboardSettings.sphere) {
113555
- // Block during draw mode or contrast mode
113556
- if (this.eventRouter.isShiftHeld() || this.eventRouter.isCtrlHeld()) {
113557
- return;
113558
- }
113559
- this.state.gui_states.mode.sphere = !this.state.gui_states.mode.sphere;
113560
- if (this.state.gui_states.mode.sphere) {
113561
- this.enterSphereMode();
113562
- }
113563
- else {
113564
- this.exitSphereMode();
113565
- }
113566
- }
113567
113617
  });
113568
113618
  this.eventRouter.setKeyupHandler((ev) => {
113569
113619
  if (this.state.configKeyBoard)
@@ -114405,7 +114455,6 @@ void main() {
114405
114455
  redo: "y",
114406
114456
  contrast: ["Control", "Meta"],
114407
114457
  crosshair: "s",
114408
- sphere: "q",
114409
114458
  mouseWheel: "Scroll:Zoom",
114410
114459
  };
114411
114460
  this.cursorPage = {
@@ -115113,6 +115162,11 @@ void main() {
115113
115162
  if (this.ctx.gui_states.mode.sphere) {
115114
115163
  return;
115115
115164
  }
115165
+ // A mirroring viewer has no layers of its own; its mirror paints in the composite.
115166
+ if (this.callbacks.hasMaskMirror()) {
115167
+ this.callbacks.compositeAllLayers();
115168
+ return;
115169
+ }
115116
115170
  const axis = this.ctx.protectedData.axis;
115117
115171
  let sliceIndex = this.ctx.nrrd_states.view.currentSliceIndex;
115118
115172
  // Clamp sliceIndex to valid range for current axis
@@ -115346,6 +115400,170 @@ void main() {
115346
115400
  }
115347
115401
  }
115348
115402
 
115403
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
115404
+ /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
115405
+ function sliceDims(dims, axis) {
115406
+ const [w, h, d] = [dims[0], dims[1], dims[2]];
115407
+ return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [d, h];
115408
+ }
115409
+ /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
115410
+ function isIdentity(m, tol = 1e-9) {
115411
+ if (!m)
115412
+ return true;
115413
+ for (let i = 0; i < 16; i++) {
115414
+ if (Math.abs(m[i] - IDENTITY[i]) > tol)
115415
+ return false;
115416
+ }
115417
+ return true;
115418
+ }
115419
+ /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
115420
+ function isDiagonal(m, tol = 1e-9) {
115421
+ for (const i of [1, 2, 4, 6, 8, 9]) {
115422
+ if (Math.abs(m[i]) > tol)
115423
+ return false;
115424
+ }
115425
+ return true;
115426
+ }
115427
+ /**
115428
+ * For each mirror index along one axis, the inclusive source index range it covers, clamped
115429
+ * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
115430
+ * source voxel covers the one nearest its centre; a larger one covers every source voxel
115431
+ * whose centre lies within it.
115432
+ */
115433
+ function coveredRanges(s, t, count, extent) {
115434
+ const lo = new Int32Array(count);
115435
+ const hi = new Int32Array(count);
115436
+ const half = Math.abs(s) / 2;
115437
+ for (let i = 0; i < count; i++) {
115438
+ const c = s * i + t;
115439
+ let a, b;
115440
+ if (Math.abs(s) <= 1) {
115441
+ a = b = Math.round(c);
115442
+ }
115443
+ else {
115444
+ a = Math.ceil(c - half - 1e-9);
115445
+ b = Math.floor(c + half - 1e-9);
115446
+ }
115447
+ lo[i] = Math.max(a, 0);
115448
+ hi[i] = Math.min(b, extent - 1);
115449
+ }
115450
+ return { lo, hi };
115451
+ }
115452
+ /**
115453
+ * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
115454
+ * the source is 0. On the same grid with the identity, it is the source's own slice.
115455
+ *
115456
+ * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
115457
+ * coarser than the source shows the first label found among every source voxel it spans, so
115458
+ * a finding thinner than the mirror's slice still appears on the slice that contains it.
115459
+ * Any other transform samples the nearest source voxel.
115460
+ */
115461
+ function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
115462
+ const sd = source.getDimensions();
115463
+ if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
115464
+ const s = source.getSliceUint8(index, axis);
115465
+ return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
115466
+ }
115467
+ const mat = m !== null && m !== void 0 ? m : IDENTITY;
115468
+ const [W, H] = sliceDims(mirrorDims, axis);
115469
+ const raw = source.getRawData();
115470
+ const nch = source.getChannels();
115471
+ const out = new Uint8Array(W * H);
115472
+ if (isDiagonal(mat)) {
115473
+ const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
115474
+ const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
115475
+ const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
115476
+ for (let v = 0; v < H; v++) {
115477
+ for (let u = 0; u < W; u++) {
115478
+ const x = axis === "x" ? index : u;
115479
+ const y = axis === "y" ? index : v;
115480
+ const z = axis === "z" ? index : axis === "y" ? v : u;
115481
+ let label = 0;
115482
+ for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
115483
+ for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
115484
+ for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
115485
+ label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
115486
+ }
115487
+ }
115488
+ }
115489
+ out[v * W + u] = label;
115490
+ }
115491
+ }
115492
+ return { data: out, width: W, height: H, stride: 1 };
115493
+ }
115494
+ for (let v = 0; v < H; v++) {
115495
+ for (let u = 0; u < W; u++) {
115496
+ // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
115497
+ const x = axis === "x" ? index : u;
115498
+ const y = axis === "y" ? index : v;
115499
+ const z = axis === "z" ? index : axis === "y" ? v : u;
115500
+ const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
115501
+ const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
115502
+ const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
115503
+ if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
115504
+ continue;
115505
+ out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
115506
+ }
115507
+ }
115508
+ return { data: out, width: W, height: H, stride: 1 };
115509
+ }
115510
+ /**
115511
+ * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
115512
+ * volumes and display state. A new transform means a new instance, so the cache never holds
115513
+ * contours from another transform.
115514
+ */
115515
+ class MaskMirror {
115516
+ constructor(self, source, matrix) {
115517
+ this.self = self;
115518
+ this.source = source;
115519
+ this.matrix = matrix;
115520
+ /** One contour entry per source layer, for the slice last painted. */
115521
+ this.cache = new Map();
115522
+ /** The source volume each cache entry was built from; a case load replaces the object. */
115523
+ this.cachedVolumes = new Map();
115524
+ }
115525
+ /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
115526
+ paint(ctx, width, height) {
115527
+ var _a, _b;
115528
+ // The source hides its own layers in sphere mode, so the mirror shows none either.
115529
+ if (this.source.gui_states.mode.sphere)
115530
+ return;
115531
+ const dims = this.self.nrrd_states.image.dimensions;
115532
+ if (!dims || dims.length !== 3)
115533
+ return;
115534
+ const axis = this.self.protectedData.axis;
115535
+ const index = this.self.nrrd_states.view.currentSliceIndex;
115536
+ const lc = this.source.gui_states.layerChannel;
115537
+ const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
115538
+ for (const layerId of this.source.nrrd_states.image.layers) {
115539
+ if (!lc.layerVisibility[layerId])
115540
+ continue;
115541
+ const volume = this.source.protectedData.maskData.volumes[layerId];
115542
+ if (!volume)
115543
+ continue;
115544
+ if (this.cachedVolumes.get(layerId) !== volume) {
115545
+ this.cache.delete(layerId);
115546
+ this.cachedVolumes.set(layerId, volume);
115547
+ }
115548
+ try {
115549
+ const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
115550
+ ctx.save();
115551
+ try {
115552
+ ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
115553
+ paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
115554
+ }
115555
+ finally {
115556
+ // A throw must not leave this layer's alpha or transform on the master canvas.
115557
+ ctx.restore();
115558
+ }
115559
+ }
115560
+ catch (_c) {
115561
+ // The source is not ready for this slice: nothing to draw for this layer.
115562
+ }
115563
+ }
115564
+ }
115565
+ }
115566
+
115349
115567
  /**
115350
115568
  * NrrdTools.setMasksFromNIfTI forwards its `Map<string, Uint8Array>` argument
115351
115569
  * straight through to here with no second channel for metadata, so a caller that
@@ -115627,7 +115845,15 @@ void main() {
115627
115845
  // ═══════════════════════════════════════════════════════════════════════════
115628
115846
  constructor(container, options) {
115629
115847
  this._sliceRAFId = null;
115848
+ /** Viewers drawing this one's masks (see setMaskMirror). */
115849
+ this._mirrors = new Set();
115850
+ /** The viewer whose masks this one draws, if any. */
115851
+ this._mirrorSource = null;
115852
+ /** The pending frame that refreshes this viewer's mirrors. */
115853
+ this._mirrorFrame = null;
115630
115854
  this._pendingSliceStep = 0;
115855
+ /** Receives slice moves while a preview slice is shown; null when none is. */
115856
+ this._previewSliceMove = null;
115631
115857
  /** Whether calculator mode is active (not part of gui_states interface) */
115632
115858
  this._calculatorActive = false;
115633
115859
  /**
@@ -115660,6 +115886,8 @@ void main() {
115660
115886
  this.drawCore = new DrawToolCore(container, this.state);
115661
115887
  // Wire DrawToolCore's overridable methods to NrrdTools implementations
115662
115888
  this.wireDrawCoreMethods();
115889
+ // Every visible mask change ends in a composite; the viewers mirroring this one follow it.
115890
+ this.drawCore.renderer.onComposited = () => this.scheduleMirrorRefresh();
115663
115891
  // Wire RenderingUtils' setEmptyCanvasSize callback
115664
115892
  this.drawCore.renderer.setEmptyCanvasSize = (axis) => this.setEmptyCanvasSize(axis);
115665
115893
  this.init();
@@ -115670,6 +115898,7 @@ void main() {
115670
115898
  }
115671
115899
  // Wire sphere overlay refresh callback into DragOperator → DragSliceTool
115672
115900
  this.dragOperator.setRefreshSphereOverlay(() => this.refreshSphereOverlay());
115901
+ this.dragOperator.setPreviewSliceMove((index) => this.previewSliceMove(index));
115673
115902
  // Initialize extracted modules
115674
115903
  this.initNrrdToolsModules();
115675
115904
  }
@@ -115717,6 +115946,7 @@ void main() {
115717
115946
  });
115718
115947
  this.sliceRenderPipeline = new SliceRenderPipeline(toolCtx, {
115719
115948
  compositeAllLayers: () => this.drawCore.renderer.compositeAllLayers(),
115949
+ hasMaskMirror: () => this._mirrorSource !== null,
115720
115950
  getOrCreateSliceBuffer: (axis) => this.drawCore.renderer.getOrCreateSliceBuffer(axis),
115721
115951
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, targetCtx, w, h) => this.drawCore.renderer.renderSliceToCanvas(layer, axis, sliceIndex, buffer, targetCtx, w, h),
115722
115952
  getVolumeForLayer: (layer) => this.drawCore.renderer.getVolumeForLayer(layer),
@@ -116485,10 +116715,49 @@ void main() {
116485
116715
  * Used for register/origin image switching where the view state should persist.
116486
116716
  */
116487
116717
  switchSlicesPreservingView(allSlices) {
116718
+ this._previewSliceMove = null;
116488
116719
  this.state.protectedData.allSlicesArray.length = 0;
116489
116720
  this.state.protectedData.allSlicesArray = [...allSlices];
116490
116721
  this.sliceRenderPipeline.switchPreservingView();
116491
116722
  }
116723
+ /**
116724
+ * Show one slice of a volume before the volume itself has loaded: `header` is the full
116725
+ * volume's geometry, `slice` a depth-1 slice triple of plane `index` (built from one plane's
116726
+ * voxels), shown as slice `index` of the full stack. Geometry is re-initialised only when it
116727
+ * differs from the current one. Replaces whatever slice data is displayed; writes no mask.
116728
+ * The full volume later replaces it with `switchSlicesPreservingView`, keeping `index`.
116729
+ *
116730
+ * Until then every slice move (wheel, keys, drag, `setSliceMoving`) goes to `onSliceMove`
116731
+ * with its clamped target index instead of moving the displayed slice. Axial only; it does
116732
+ * not switch orientation.
116733
+ */
116734
+ showPreviewSlice(header, slice, index, onSliceMove) {
116735
+ const image = this.state.nrrd_states.image;
116736
+ const same = (a, b) => !!a && a.length === b.length && Array.from(b).every((v, i) => a[i] === v);
116737
+ if (!same(image.dimensions, header.dimensions) ||
116738
+ !same(image.voxelSpacing, header.spacing) ||
116739
+ !same(image.spaceOrigin, header.space_origin)) {
116740
+ this.dataLoader.initFromHeader(header);
116741
+ }
116742
+ slice.z.initIndex = index;
116743
+ this.state.protectedData.allSlicesArray.length = 0;
116744
+ // Take the index from `initIndex` rather than writing the full-stack index into the
116745
+ // depth-1 slice's own `index`, which would be out of range for it.
116746
+ this.sliceRenderPipeline.resetInitState();
116747
+ this.dataLoader.appendSlice(slice, 0);
116748
+ this._previewSliceMove = onSliceMove;
116749
+ }
116750
+ /** Whether a preview slice from `showPreviewSlice` is shown in place of a loaded volume. */
116751
+ isPreviewing() {
116752
+ return this._previewSliceMove !== null;
116753
+ }
116754
+ /** Hands a slice move to the preview's host; false when no preview is shown. */
116755
+ previewSliceMove(index) {
116756
+ if (!this._previewSliceMove)
116757
+ return false;
116758
+ this._previewSliceMove(index);
116759
+ return true;
116760
+ }
116492
116761
  appendLoadingbar(loadingbar) {
116493
116762
  this.state.protectedData.mainAreaContainer.appendChild(loadingbar);
116494
116763
  }
@@ -116600,7 +116869,10 @@ void main() {
116600
116869
  // ═══════════════════════════════════════════════════════════════════════════
116601
116870
  // 9. Delegated — DataLoader
116602
116871
  // ═══════════════════════════════════════════════════════════════════════════
116603
- setAllSlices(allSlices) { this.dataLoader.setAllSlices(allSlices); }
116872
+ setAllSlices(allSlices) {
116873
+ this._previewSliceMove = null;
116874
+ this.dataLoader.setAllSlices(allSlices);
116875
+ }
116604
116876
  setMasksData(masksData, loadingBar) { this.dataLoader.setMasksData(masksData, loadingBar); }
116605
116877
  setMasksFromNIfTI(layerVoxels, loadingBar) { this.dataLoader.setMasksFromNIfTI(layerVoxels, loadingBar); }
116606
116878
  // ═══════════════════════════════════════════════════════════════════════════
@@ -116866,6 +117138,7 @@ void main() {
116866
117138
  this.reloadMasksFromVolume();
116867
117139
  }
116868
117140
  reset() {
117141
+ this._previewSliceMove = null;
116869
117142
  this.state.protectedData.allSlicesArray.length = 0;
116870
117143
  this.state.protectedData.displaySlices.length = 0;
116871
117144
  this.drawCore.undoManager.clearAll();
@@ -116897,10 +117170,41 @@ void main() {
116897
117170
  this.state.nrrd_states.sphere.skinSphereOrigin = null;
116898
117171
  this.state.nrrd_states.sphere.nippleSphereOrigin = null;
116899
117172
  }
117173
+ /**
117174
+ * Draw `source`'s masks on this viewer, read live from it: its volumes, colours, channel and
117175
+ * layer visibility, opacity and render mode. `mirrorToSource` is a row-major 4×4 from this
117176
+ * viewer's voxel (x, y, z, 1) to the source's voxel; omitted means the identity. `null`
117177
+ * detaches. Display only — nothing is written to either viewer's masks.
117178
+ */
117179
+ setMaskMirror(source, mirrorToSource) {
117180
+ var _a, _b;
117181
+ (_a = this._mirrorSource) === null || _a === void 0 ? void 0 : _a._mirrors.delete(this);
117182
+ this._mirrorSource = source && source !== this ? source : null;
117183
+ this.drawCore.renderer.mirror = this._mirrorSource
117184
+ ? new MaskMirror(this.state, this._mirrorSource.state, mirrorToSource !== null && mirrorToSource !== void 0 ? mirrorToSource : null)
117185
+ : null;
117186
+ (_b = this._mirrorSource) === null || _b === void 0 ? void 0 : _b._mirrors.add(this);
117187
+ this.drawCore.renderer.compositeAllLayers();
117188
+ }
117189
+ /** The viewer whose masks this one draws, or null. */
117190
+ getMaskMirrorSource() {
117191
+ return this._mirrorSource;
117192
+ }
117193
+ /** Repaint every mirror of this viewer on the next frame; repeated calls coalesce. */
117194
+ scheduleMirrorRefresh() {
117195
+ if (this._mirrors.size === 0 || this._mirrorFrame !== null)
117196
+ return;
117197
+ this._mirrorFrame = requestAnimationFrame(() => {
117198
+ this._mirrorFrame = null;
117199
+ for (const m of this._mirrors)
117200
+ m.drawCore.renderer.compositeAllLayers();
117201
+ });
117202
+ }
116900
117203
  /**
116901
117204
  * Releases what this instance holds outside its own DOM subtree, so a viewer that is torn
116902
117205
  * down can be garbage-collected: the event router's listeners (its window `blur` listener
116903
- * reaches the whole engine graph), a pending slice step and the drawing-flag timer.
117206
+ * reaches the whole engine graph), a pending slice step, the drawing-flag timer and any
117207
+ * mask-mirror link.
116904
117208
  *
116905
117209
  * The instance must not be used afterwards. Safe to call more than once.
116906
117210
  */
@@ -116916,6 +117220,22 @@ void main() {
116916
117220
  window.clearTimeout(this.preTimer);
116917
117221
  this.preTimer = undefined;
116918
117222
  }
117223
+ // Release the mirror link from both ends, so neither viewer keeps the other alive.
117224
+ if (this._mirrorSource) {
117225
+ this._mirrorSource._mirrors.delete(this);
117226
+ this._mirrorSource = null;
117227
+ this.drawCore.renderer.mirror = null;
117228
+ }
117229
+ for (const m of this._mirrors) {
117230
+ m._mirrorSource = null;
117231
+ m.drawCore.renderer.mirror = null;
117232
+ m.drawCore.renderer.compositeAllLayers();
117233
+ }
117234
+ this._mirrors.clear();
117235
+ if (this._mirrorFrame !== null) {
117236
+ cancelAnimationFrame(this._mirrorFrame);
117237
+ this._mirrorFrame = null;
117238
+ }
116919
117239
  }
116920
117240
  // ═══════════════════════════════════════════════════════════════════════════
116921
117241
  // 12. Internal — Input Events
@@ -118220,15 +118540,15 @@ void main() {
118220
118540
  }
118221
118541
 
118222
118542
  // import * as kiwrious from "copper3d_plugin_heart_k";
118223
- // "v3.11.3" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118543
+ // "v3.11.5" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118224
118544
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
118225
118545
  // referencing it throws a ReferenceError — guard it so local loading still works.
118226
118546
  let _revision = "unknown";
118227
118547
  try {
118228
- _revision = "v3.11.3";
118548
+ _revision = "v3.11.5";
118229
118549
  }
118230
118550
  catch (_a) {
118231
- /* "v3.11.3" not injected (local source build) */
118551
+ /* "v3.11.5" not injected (local source build) */
118232
118552
  }
118233
118553
  const REVISION = _revision;
118234
118554
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__