copper3d 3.10.2 → 3.10.4

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 (41) hide show
  1. package/README.md +40 -4
  2. package/dist/Utils/segmentation/DrawToolCore.d.ts +8 -0
  3. package/dist/Utils/segmentation/DrawToolCore.js +12 -0
  4. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  5. package/dist/Utils/segmentation/NrrdTools.d.ts +21 -1
  6. package/dist/Utils/segmentation/NrrdTools.js +25 -0
  7. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  8. package/dist/Utils/segmentation/RenderingUtils.d.ts +32 -0
  9. package/dist/Utils/segmentation/RenderingUtils.js +107 -12
  10. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  11. package/dist/Utils/segmentation/core/MarchingSquares.d.ts +26 -0
  12. package/dist/Utils/segmentation/core/MarchingSquares.js +113 -0
  13. package/dist/Utils/segmentation/core/MarchingSquares.js.map +1 -1
  14. package/dist/Utils/segmentation/core/UndoManager.d.ts +12 -1
  15. package/dist/Utils/segmentation/core/UndoManager.js +33 -17
  16. package/dist/Utils/segmentation/core/UndoManager.js.map +1 -1
  17. package/dist/Utils/segmentation/core/index.d.ts +2 -2
  18. package/dist/Utils/segmentation/core/index.js +1 -1
  19. package/dist/Utils/segmentation/core/index.js.map +1 -1
  20. package/dist/Utils/segmentation/core/types.d.ts +10 -0
  21. package/dist/Utils/segmentation/core/types.js.map +1 -1
  22. package/dist/Utils/segmentation/coreTools/GuiState.js +2 -0
  23. package/dist/Utils/segmentation/coreTools/GuiState.js.map +1 -1
  24. package/dist/Utils/segmentation/tools/DrawingTool.d.ts +19 -2
  25. package/dist/Utils/segmentation/tools/DrawingTool.js +30 -6
  26. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  27. package/dist/Utils/segmentation/tools/ToolHost.d.ts +7 -1
  28. package/dist/bundle.esm.js +324 -37
  29. package/dist/bundle.umd.js +324 -37
  30. package/dist/index.d.ts +2 -2
  31. package/dist/types/Utils/segmentation/DrawToolCore.d.ts +8 -0
  32. package/dist/types/Utils/segmentation/NrrdTools.d.ts +21 -1
  33. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +32 -0
  34. package/dist/types/Utils/segmentation/core/MarchingSquares.d.ts +26 -0
  35. package/dist/types/Utils/segmentation/core/UndoManager.d.ts +12 -1
  36. package/dist/types/Utils/segmentation/core/index.d.ts +2 -2
  37. package/dist/types/Utils/segmentation/core/types.d.ts +10 -0
  38. package/dist/types/Utils/segmentation/tools/DrawingTool.d.ts +19 -2
  39. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +7 -1
  40. package/dist/types/index.d.ts +2 -2
  41. package/package.json +1 -1
@@ -18,6 +18,12 @@ export interface ToolHost {
18
18
  drawImageOnEmptyImage(canvas: HTMLCanvasElement): void;
19
19
  compositeAllLayers(): void;
20
20
  renderSliceToCanvas(layer: string, axis: "x" | "y" | "z", sliceIndex: number, buffer: ImageData, targetCtx: CanvasRenderingContext2D, scaledWidth: number, scaledHeight: number): void;
21
+ /**
22
+ * Render a layer's slice filled, whatever the display mode is. For tools that follow a
23
+ * render with `syncLayerSliceData`, which rebuilds the whole slice from the canvas: an
24
+ * outline would bake back as a ring and erase every mask interior on that slice.
25
+ */
26
+ renderSliceForBake(layer: string, axis: "x" | "y" | "z", sliceIndex: number, targetCtx: CanvasRenderingContext2D, scaledWidth: number, scaledHeight: number): void;
21
27
  getOrCreateSliceBuffer(axis: "x" | "y" | "z"): ImageData | null;
22
28
  flipDisplayImageByAxis(): void;
23
29
  redrawDisplayCanvas(): void;
@@ -71,7 +77,7 @@ export type ZoomHostDeps = Pick<ToolHost, 'resetPaintAreaUIPosition' | 'resizePa
71
77
  /** SphereTool host dependencies */
72
78
  export type SphereHostDeps = Pick<ToolHost, 'setEmptyCanvasSize' | 'drawImageOnEmptyImage' | 'enableCrosshair' | 'setUpSphereOrigins'>;
73
79
  /** DrawingTool host dependencies */
74
- export type DrawingHostDeps = Pick<ToolHost, 'setCurrentLayer' | 'compositeAllLayers' | 'syncLayerSliceData' | 'filterDrawedImage' | 'getVolumeForLayer' | 'pushUndoDelta' | 'renderSliceToCanvas' | 'getOrCreateSliceBuffer'>;
80
+ export type DrawingHostDeps = Pick<ToolHost, 'setCurrentLayer' | 'compositeAllLayers' | 'syncLayerSliceData' | 'filterDrawedImage' | 'getVolumeForLayer' | 'pushUndoDelta' | 'renderSliceToCanvas' | 'renderSliceForBake' | 'getOrCreateSliceBuffer'>;
75
81
  /** DragSliceTool host dependencies */
76
82
  export type DragSliceHostDeps = Pick<ToolHost, 'setSyncsliceNum' | 'setIsDrawFalse' | 'flipDisplayImageByAxis' | 'setEmptyCanvasSize' | 'getOrCreateSliceBuffer' | 'renderSliceToCanvas' | 'refreshSphereOverlay' | 'compositeAllLayers'>;
77
83
  /** LayerChannelManager host dependencies */
@@ -107741,12 +107741,30 @@ class MaskVolume {
107741
107741
  * - Undo/redo operations also trigger backend sync via getMask callback.
107742
107742
  */
107743
107743
  const MAX_STACK_SIZE = 50;
107744
- const LAYER_IDS = ["layer1", "layer2", "layer3"];
107745
107744
  class UndoManager {
107746
107745
  constructor() {
107746
+ this.undoStacks = new Map();
107747
+ this.redoStacks = new Map();
107747
107748
  this.activeLayer = "layer1";
107748
- this.undoStacks = new Map(LAYER_IDS.map((id) => [id, []]));
107749
- this.redoStacks = new Map(LAYER_IDS.map((id) => [id, []]));
107749
+ }
107750
+ /**
107751
+ * The stack for a layer, created on first use.
107752
+ *
107753
+ * Stacks used to be pre-created for exactly layer1/2/3, which broke in two ways at once for
107754
+ * any other id -- and `NrrdTools`'s constructor has always accepted `options.layers`, so any
107755
+ * other id is reachable. `push*` resolved with `?? get("layer1")` and silently appended to a
107756
+ * different layer's history, so an undo later popped a stroke the user never made there;
107757
+ * `undo`/`redo` asserted non-null on the same lookup and threw instead.
107758
+ *
107759
+ * Creating on demand removes both. Nothing else needs to know which layers exist.
107760
+ */
107761
+ stackFor(stacks, layerId) {
107762
+ let stack = stacks.get(layerId);
107763
+ if (!stack) {
107764
+ stack = [];
107765
+ stacks.set(layerId, stack);
107766
+ }
107767
+ return stack;
107750
107768
  }
107751
107769
  /** Set the currently active layer (determines which stack undo/redo operates on). */
107752
107770
  setActiveLayer(layer) {
@@ -107758,17 +107776,16 @@ class UndoManager {
107758
107776
  }
107759
107777
  /** Push a group of deltas as a single undo unit (e.g. 3D sphere spanning multiple slices). */
107760
107778
  pushGroup(deltas) {
107761
- var _a, _b;
107762
107779
  if (deltas.length === 0)
107763
107780
  return;
107764
107781
  const layerId = deltas[0].layerId;
107765
- const stack = (_a = this.undoStacks.get(layerId)) !== null && _a !== void 0 ? _a : this.undoStacks.get("layer1");
107782
+ const stack = this.stackFor(this.undoStacks, layerId);
107766
107783
  stack.push(deltas);
107767
107784
  if (stack.length > MAX_STACK_SIZE) {
107768
107785
  stack.shift();
107769
107786
  }
107770
107787
  // Any new operation invalidates the redo history for that layer
107771
- const redoStack = (_b = this.redoStacks.get(layerId)) !== null && _b !== void 0 ? _b : this.redoStacks.get("layer1");
107788
+ const redoStack = this.stackFor(this.redoStacks, layerId);
107772
107789
  redoStack.length = 0;
107773
107790
  }
107774
107791
  /**
@@ -107778,8 +107795,7 @@ class UndoManager {
107778
107795
  * an unbounded stack would be hundreds of megabytes. Slice deltas below it survive.
107779
107796
  */
107780
107797
  pushVolumeSnapshot(layerId, oldVolume, newVolume) {
107781
- var _a, _b;
107782
- const stack = (_a = this.undoStacks.get(layerId)) !== null && _a !== void 0 ? _a : this.undoStacks.get("layer1");
107798
+ const stack = this.stackFor(this.undoStacks, layerId);
107783
107799
  for (let i = stack.length - 1; i >= 0; i--) {
107784
107800
  if (!Array.isArray(stack[i]))
107785
107801
  stack.splice(i, 1);
@@ -107788,7 +107804,7 @@ class UndoManager {
107788
107804
  if (stack.length > MAX_STACK_SIZE) {
107789
107805
  stack.shift();
107790
107806
  }
107791
- const redoStack = (_b = this.redoStacks.get(layerId)) !== null && _b !== void 0 ? _b : this.redoStacks.get("layer1");
107807
+ const redoStack = this.stackFor(this.redoStacks, layerId);
107792
107808
  redoStack.length = 0;
107793
107809
  }
107794
107810
  /**
@@ -107796,10 +107812,10 @@ class UndoManager {
107796
107812
  * @returns The delta(s) that were undone, or undefined if nothing to undo.
107797
107813
  */
107798
107814
  undo() {
107799
- const stack = this.undoStacks.get(this.activeLayer);
107815
+ const stack = this.stackFor(this.undoStacks, this.activeLayer);
107800
107816
  const entry = stack.pop();
107801
107817
  if (entry) {
107802
- this.redoStacks.get(this.activeLayer).push(entry);
107818
+ this.stackFor(this.redoStacks, this.activeLayer).push(entry);
107803
107819
  }
107804
107820
  return entry;
107805
107821
  }
@@ -107808,10 +107824,10 @@ class UndoManager {
107808
107824
  * @returns The delta(s) that were redone, or undefined if nothing to redo.
107809
107825
  */
107810
107826
  redo() {
107811
- const stack = this.redoStacks.get(this.activeLayer);
107827
+ const stack = this.stackFor(this.redoStacks, this.activeLayer);
107812
107828
  const entry = stack.pop();
107813
107829
  if (entry) {
107814
- this.undoStacks.get(this.activeLayer).push(entry);
107830
+ this.stackFor(this.undoStacks, this.activeLayer).push(entry);
107815
107831
  }
107816
107832
  return entry;
107817
107833
  }
@@ -107834,10 +107850,10 @@ class UndoManager {
107834
107850
  }
107835
107851
  /** Clear all stacks for all layers (called on full dataset reload). */
107836
107852
  clearAll() {
107837
- for (const id of LAYER_IDS) {
107838
- this.undoStacks.get(id).length = 0;
107839
- this.redoStacks.get(id).length = 0;
107840
- }
107853
+ for (const stack of this.undoStacks.values())
107854
+ stack.length = 0;
107855
+ for (const stack of this.redoStacks.values())
107856
+ stack.length = 0;
107841
107857
  }
107842
107858
  }
107843
107859
 
@@ -107902,6 +107918,50 @@ const CELL_POLYGONS = [
107902
107918
  /* 14 (TL+TR+BR, !BL) */ [[[0, 0], [1, 0], [1, 1], [0.5, 1], [0, 0.5]]],
107903
107919
  /* 15 (full) */ [[[0, 0], [1, 0], [1, 1], [0, 1]]],
107904
107920
  ];
107921
+ /**
107922
+ * Per-cell boundary segments for the same 16 cases — the region's edge, without the region.
107923
+ *
107924
+ * Each entry is the cut line of the corresponding `CELL_POLYGONS` entry: the one edge of that
107925
+ * polygon which does not lie on the cell's border. Filling the polygons and stroking these
107926
+ * therefore describe the same silhouette, which is what lets the renderer swap fill for
107927
+ * outline without the mask's edge appearing to move.
107928
+ *
107929
+ * Endpoints are the midpoints of the cell's sides —
107930
+ * T = (0.5, 0) R = (1, 0.5) B = (0.5, 1) L = (0, 0.5)
107931
+ * — in the same cell-local 0..1 space as `CELL_POLYGONS`, so the caller adds (i, j) + SHIFT
107932
+ * identically for both.
107933
+ *
107934
+ * Cases 0 and 15 emit nothing. 15 is the whole reason an outline is cheap: solid interior has
107935
+ * no boundary, so the segment count follows the perimeter rather than the area.
107936
+ *
107937
+ * Saddles (5 and 10) follow `CELL_POLYGONS`' convention — the two in-corners are disconnected
107938
+ * (4-connectivity) — because the other reading would run a boundary straight through mask the
107939
+ * fill considers solid.
107940
+ */
107941
+ const CELL_SEGMENTS = [
107942
+ /* 0 (empty) */ [],
107943
+ /* 1 (BL) */ [[[0, 0.5], [0.5, 1]]],
107944
+ /* 2 (BR) */ [[[0.5, 1], [1, 0.5]]],
107945
+ /* 3 (BR+BL) */ [[[0, 0.5], [1, 0.5]]],
107946
+ /* 4 (TR) */ [[[0.5, 0], [1, 0.5]]],
107947
+ /* 5 (TR+BL saddle) */ [
107948
+ [[0.5, 0], [1, 0.5]],
107949
+ [[0, 0.5], [0.5, 1]],
107950
+ ],
107951
+ /* 6 (TR+BR) */ [[[0.5, 0], [0.5, 1]]],
107952
+ /* 7 (TR+BR+BL, !TL) */ [[[0.5, 0], [0, 0.5]]],
107953
+ /* 8 (TL) */ [[[0.5, 0], [0, 0.5]]],
107954
+ /* 9 (TL+BL) */ [[[0.5, 0], [0.5, 1]]],
107955
+ /* 10 (TL+BR saddle) */ [
107956
+ [[0.5, 0], [0, 0.5]],
107957
+ [[0.5, 1], [1, 0.5]],
107958
+ ],
107959
+ /* 11 (TL+BR+BL, !TR) */ [[[0.5, 0], [1, 0.5]]],
107960
+ /* 12 (TL+TR) */ [[[1, 0.5], [0, 0.5]]],
107961
+ /* 13 (TL+TR+BL, !BR) */ [[[1, 0.5], [0.5, 1]]],
107962
+ /* 14 (TL+TR+BR, !BL) */ [[[0.5, 1], [0, 0.5]]],
107963
+ /* 15 (full) */ [],
107964
+ ];
107905
107965
  /**
107906
107966
  * Emit polygons covering the voxels where `labels === targetLabel`.
107907
107967
  * Pure geometry function — no Canvas dependency. Consumers can build a Path2D
@@ -108023,6 +108083,75 @@ function extractLabelContours(labels, width, height, targetLabel, stride = 1, ch
108023
108083
  }
108024
108084
  return path;
108025
108085
  }
108086
+ /**
108087
+ * Emit the boundary of the region where `labels === targetLabel`, as open two-point segments.
108088
+ *
108089
+ * The counterpart to {@link extractLabelPolygons}: that one covers the region, this one traces
108090
+ * its edge. Both walk the same cells with the same sampling, the same out-of-bounds rule and
108091
+ * the same `+0.5` shift, so a renderer can fill one and stroke the other and have the mask end
108092
+ * in exactly the same place either way.
108093
+ *
108094
+ * Segments are emitted per cell and left unjoined. Canvas rasterises a whole `Path2D` in one
108095
+ * compositing pass, so segments meeting at a shared endpoint produce no seam and no doubled
108096
+ * alpha where their round caps overlap — joining them into polylines would buy nothing and
108097
+ * cost a chaining pass.
108098
+ *
108099
+ * Cost follows the perimeter, not the area: solid interior is case 15, which has no boundary.
108100
+ *
108101
+ * Parameters match {@link extractLabelContours}.
108102
+ */
108103
+ function extractLabelBoundarySegments(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox) {
108104
+ var _a, _b, _c, _d;
108105
+ const out = [];
108106
+ const i0 = Math.max(-1, ((_a = bbox === null || bbox === void 0 ? void 0 : bbox.x0) !== null && _a !== void 0 ? _a : 0) - 1);
108107
+ const j0 = Math.max(-1, ((_b = bbox === null || bbox === void 0 ? void 0 : bbox.y0) !== null && _b !== void 0 ? _b : 0) - 1);
108108
+ const i1 = Math.min(width, (_c = bbox === null || bbox === void 0 ? void 0 : bbox.x1) !== null && _c !== void 0 ? _c : width);
108109
+ const j1 = Math.min(height, (_d = bbox === null || bbox === void 0 ? void 0 : bbox.y1) !== null && _d !== void 0 ? _d : height);
108110
+ const sample = (x, y) => {
108111
+ if (x < 0 || x >= width || y < 0 || y >= height)
108112
+ return false;
108113
+ return labels[(y * width + x) * stride + channelOffset] === targetLabel;
108114
+ };
108115
+ // Same convention as extractLabelPolygons: samples sit at voxel centres.
108116
+ const SHIFT = 0.5;
108117
+ for (let j = j0; j < j1; j++) {
108118
+ for (let i = i0; i < i1; i++) {
108119
+ const code = (sample(i, j) ? 8 : 0) |
108120
+ (sample(i + 1, j) ? 4 : 0) |
108121
+ (sample(i + 1, j + 1) ? 2 : 0) |
108122
+ (sample(i, j + 1) ? 1 : 0);
108123
+ // Nothing here, or nothing but mask: neither has an edge in this cell.
108124
+ if (code === 0 || code === 15)
108125
+ continue;
108126
+ const segments = CELL_SEGMENTS[code];
108127
+ for (let s = 0; s < segments.length; s++) {
108128
+ const [a, b] = segments[s];
108129
+ out.push([
108130
+ [i + a[0] + SHIFT, j + a[1] + SHIFT],
108131
+ [i + b[0] + SHIFT, j + b[1] + SHIFT],
108132
+ ]);
108133
+ }
108134
+ }
108135
+ }
108136
+ return out;
108137
+ }
108138
+ /**
108139
+ * {@link extractLabelBoundarySegments} as a `Path2D`, ready to stroke.
108140
+ *
108141
+ * The outline counterpart to {@link extractLabelContours}. Stroke this; do not stroke the
108142
+ * contour path — that one is per-cell polygons whose union is the silhouette, and stroking it
108143
+ * draws every internal cell edge as well, covering the mask in a grid.
108144
+ */
108145
+ function extractLabelOutline(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox) {
108146
+ const segments = extractLabelBoundarySegments(labels, width, height, targetLabel, stride, channelOffset, bbox);
108147
+ const path = new Path2D();
108148
+ for (let s = 0; s < segments.length; s++) {
108149
+ const [a, b] = segments[s];
108150
+ path.moveTo(a[0], a[1]);
108151
+ path.lineTo(b[0], b[1]);
108152
+ }
108153
+ return path;
108154
+ }
108026
108155
  /**
108027
108156
  * Detect the distinct non-zero labels present in a slice region.
108028
108157
  *
@@ -109460,6 +109589,14 @@ class DragOperator {
109460
109589
  }
109461
109590
  }
109462
109591
 
109592
+ /**
109593
+ * Outline stroke width, in screen pixels.
109594
+ *
109595
+ * Screen pixels rather than voxels so magnifying the image does not thicken the line over the
109596
+ * boundary the clinician magnified it to see. Thin enough to sit on an edge, thick enough to
109597
+ * stay visible against bright tissue.
109598
+ */
109599
+ const OUTLINE_WIDTH_PX = 1.5;
109463
109600
  /**
109464
109601
  * RenderingUtils — Rendering / slice-buffer helper methods.
109465
109602
  *
@@ -109491,6 +109628,12 @@ class RenderingUtils {
109491
109628
  * applied at fill time and intentionally *not* cached, so toggling them
109492
109629
  * needs no recompute.
109493
109630
  *
109631
+ * The render mode is not in the key either. Fill paths and outline paths
109632
+ * are built lazily and side by side under the same entry, so switching
109633
+ * mode costs one extraction per visible label the first time and is a
109634
+ * cache hit every time after — and a session that never leaves fill mode
109635
+ * never builds an outline.
109636
+ *
109494
109637
  * One entry per layer (the current slice). Switching slice/axis or
109495
109638
  * editing overwrites it.
109496
109639
  */
@@ -109577,6 +109720,22 @@ class RenderingUtils {
109577
109720
  return null; // Volume not ready
109578
109721
  }
109579
109722
  }
109723
+ /**
109724
+ * Populate one cache entry's paths for one render mode.
109725
+ *
109726
+ * Split out because the two modes are built at different times: whichever is in use when
109727
+ * a slice is first drawn, and the other one only if the clinician switches while still on
109728
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
109729
+ * sessions never turn on.
109730
+ */
109731
+ buildPaths(entry, data, stride, outline) {
109732
+ const target = outline ? entry.outlines : entry.fills;
109733
+ for (const lbl of entry.labels) {
109734
+ target.set(lbl, outline
109735
+ ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109736
+ : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109737
+ }
109738
+ }
109580
109739
  /**
109581
109740
  * Render a layer's slice onto the target canvas as vector contours.
109582
109741
  *
@@ -109589,6 +109748,27 @@ class RenderingUtils {
109589
109748
  * is no longer used on this path — callers may pass any valid ImageData.
109590
109749
  */
109591
109750
  renderSliceToCanvas(layer, axis, sliceIndex, _buffer, targetCtx, scaledWidth, scaledHeight) {
109751
+ this.drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, this.state.gui_states.drawing.maskRenderMode === "outline");
109752
+ }
109753
+ /**
109754
+ * Render a layer's slice FILLED, whatever the clinician is currently looking at.
109755
+ *
109756
+ * For the tools that bake (`syncLayerSliceData` — pencil and eraser) the layer canvas is
109757
+ * not a picture of the mask, it is the input the mask is rebuilt from: the bake replaces
109758
+ * the whole slice in `MaskVolume` with whatever pixels it finds there.
109759
+ *
109760
+ * An outline is a lossy picture — it says where a mask ends, not what it contains — so
109761
+ * baking one back writes rings and erases every interior on that slice, taking every other
109762
+ * finding on the layer with it. One pencil stroke was enough.
109763
+ *
109764
+ * Hence a separate entry point rather than a flag threaded through the display path: a
109765
+ * render that is about to be read back has a different requirement from one that is about
109766
+ * to be looked at, and the two only coincided while there was one way to draw a mask.
109767
+ */
109768
+ renderSliceForBake(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight) {
109769
+ this.drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, false);
109770
+ }
109771
+ drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, outline) {
109592
109772
  try {
109593
109773
  const volume = this.getVolumeForLayer(layer);
109594
109774
  if (!volume)
@@ -109596,28 +109776,72 @@ class RenderingUtils {
109596
109776
  const stride = volume.getChannels();
109597
109777
  const cacheKey = `${axis}:${sliceIndex}:${volume.getVersion()}`;
109598
109778
  // Cache miss → run the expensive extraction once. Hits (zoom,
109599
- // recomposite, contrast toggle) skip straight to the fill below.
109779
+ // recomposite, contrast toggle) skip straight to the draw below.
109600
109780
  let entry = this._contourCache.get(layer);
109601
109781
  if (!entry || entry.key !== cacheKey) {
109602
109782
  const slice = volume.getSliceUint8(sliceIndex, axis);
109603
- const W = slice.width;
109604
- const H = slice.height;
109605
- const labels = findLabelsInSlice(slice.data, W, H, stride, 0);
109606
- const paths = new Map();
109607
- for (const lbl of labels) {
109608
- paths.set(lbl, extractLabelContours(slice.data, W, H, lbl, stride, 0));
109609
- }
109610
- entry = { key: cacheKey, W, H, labels, paths };
109783
+ entry = {
109784
+ key: cacheKey,
109785
+ W: slice.width,
109786
+ H: slice.height,
109787
+ labels: findLabelsInSlice(slice.data, slice.width, slice.height, stride, 0),
109788
+ fills: new Map(),
109789
+ outlines: new Map(),
109790
+ };
109611
109791
  this._contourCache.set(layer, entry);
109792
+ this.buildPaths(entry, slice.data, stride, outline);
109793
+ }
109794
+ else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109795
+ // The mode changed since this slice was last drawn, so the other set of
109796
+ // paths is cached and this one is not. Re-read the slice and build it; from
109797
+ // here on both are present and toggling is a pure cache hit.
109798
+ const slice = volume.getSliceUint8(sliceIndex, axis);
109799
+ this.buildPaths(entry, slice.data, stride, outline);
109612
109800
  }
109613
109801
  if (entry.labels.length === 0)
109614
109802
  return;
109615
- const { W, H, labels, paths } = entry;
109803
+ const { W, H, labels } = entry;
109804
+ const paths = outline ? entry.outlines : entry.fills;
109616
109805
  const channelVis = this.state.gui_states.layerChannel.channelVisibility[layer];
109617
109806
  targetCtx.save();
109618
- // Vector fill — imageSmoothingEnabled is irrelevant here, but keep
109807
+ // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109619
109808
  // it off to match the rest of the pipeline.
109620
109809
  targetCtx.imageSmoothingEnabled = false;
109810
+ if (outline) {
109811
+ // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109812
+ // in the path instead. `lineWidth` is then measured in screen pixels, which
109813
+ // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109814
+ // thickens the line with the zoom, exactly when the clinician has magnified
109815
+ // the image to look at the boundary — and because voxels are rarely isotropic
109816
+ // (sx !== sy), it also comes out thicker in one axis than the other.
109817
+ const matrix = new DOMMatrix();
109818
+ if (axis === 'y') {
109819
+ matrix.scaleSelf(1, -1);
109820
+ matrix.translateSelf(0, -scaledHeight);
109821
+ }
109822
+ matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109823
+ targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109824
+ // Segments are emitted per cell and meet at shared endpoints; round caps
109825
+ // close those joins. Canvas composites a whole Path2D in one pass, so the
109826
+ // overlap costs no doubled alpha.
109827
+ targetCtx.lineJoin = 'round';
109828
+ targetCtx.lineCap = 'round';
109829
+ for (const lbl of labels) {
109830
+ if (channelVis && channelVis[lbl] === false)
109831
+ continue;
109832
+ const path = paths.get(lbl);
109833
+ if (!path)
109834
+ continue;
109835
+ const color = volume.getChannelColor(lbl);
109836
+ targetCtx.strokeStyle =
109837
+ `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109838
+ const display = new Path2D();
109839
+ display.addPath(path, matrix);
109840
+ targetCtx.stroke(display);
109841
+ }
109842
+ targetCtx.restore();
109843
+ return;
109844
+ }
109621
109845
  // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109622
109846
  // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109623
109847
  // so the flip operates in display coordinates.
@@ -110835,6 +111059,11 @@ class DrawingTool extends BaseTool {
110835
111059
  this.ctx.nrrd_states.interaction.drawStartPos.y = e.offsetY;
110836
111060
  // Capture pre-draw slice snapshot for undo
110837
111061
  this.capturePreDrawSnapshot();
111062
+ // The eraser works on canvas pixels and then bakes the canvas back into the volume, so
111063
+ // it needs the layer solid rather than outlined for the length of the stroke. The display
111064
+ // mode comes back at pointerup, via refreshLayerFromVolume.
111065
+ if (this.ctx.gui_states.mode.eraser)
111066
+ this.solidifyLayerForErase();
110838
111067
  // Brush mode: initialize voxel tracking and write first dot
110839
111068
  if (!this.ctx.gui_states.mode.pencil && !this.ctx.gui_states.mode.eraser) {
110840
111069
  const voxel = this.canvasToVoxel3D(e.offsetX, e.offsetY);
@@ -111247,17 +111476,36 @@ class DrawingTool extends BaseTool {
111247
111476
  this.preDrawSlice = null;
111248
111477
  }
111249
111478
  /**
111250
- * Redraws persisted layer data onto ctx before new pencil fill.
111251
- * Delegates to the host's vector renderSliceToCanvas for consistency.
111479
+ * Redraws persisted layer data onto ctx before the new pencil fill.
111480
+ *
111481
+ * Uses the BAKE renderer, not the display one. What lands on this canvas is about to be
111482
+ * read straight back into the MaskVolume by `syncLayerSliceData`, which replaces the whole
111483
+ * slice -- so this render is the data, not a picture of it. Drawing outlines here would
111484
+ * bake rings and erase the interior of every mask on the layer.
111252
111485
  */
111253
111486
  redrawPreviousImageToLayerCtx(ctx) {
111254
111487
  const axis = this.ctx.protectedData.axis;
111255
111488
  const W = this.ctx.nrrd_states.view.changedWidth;
111256
111489
  const H = this.ctx.nrrd_states.view.changedHeight;
111257
- const buffer = this.callbacks.getOrCreateSliceBuffer(axis);
111258
- if (!buffer)
111259
- return;
111260
- this.callbacks.renderSliceToCanvas(this.ctx.gui_states.layerChannel.layer, axis, this.ctx.nrrd_states.view.currentSliceIndex, buffer, ctx, W, H);
111490
+ this.callbacks.renderSliceForBake(this.ctx.gui_states.layerChannel.layer, axis, this.ctx.nrrd_states.view.currentSliceIndex, ctx, W, H);
111491
+ }
111492
+ /**
111493
+ * Put the active layer's canvas into the solid state the eraser and the bake both need.
111494
+ *
111495
+ * The eraser removes pixels matching the active channel's colour, and `syncLayerSliceData`
111496
+ * then rebuilds the whole slice from what is left on the canvas. Against an outline there
111497
+ * is nothing to match inside a mask, so a drag over a lesion erases nothing -- and the bake
111498
+ * that follows writes the ring back and loses every interior on the layer.
111499
+ *
111500
+ * Unconditional rather than checked against the display mode: in fill mode this redraws
111501
+ * what is already on screen, and a mode-dependent branch here is one more thing that can
111502
+ * fall out of step with the renderer.
111503
+ */
111504
+ solidifyLayerForErase() {
111505
+ const target = this.callbacks.setCurrentLayer();
111506
+ target.canvas.width = target.canvas.width; // clear
111507
+ this.callbacks.renderSliceForBake(this.ctx.gui_states.layerChannel.layer, this.ctx.protectedData.axis, this.ctx.nrrd_states.view.currentSliceIndex, target.ctx, this.ctx.nrrd_states.view.changedWidth, this.ctx.nrrd_states.view.changedHeight);
111508
+ this.callbacks.compositeAllLayers();
111261
111509
  }
111262
111510
  /** Draw a line segment on a layer canvas (pencil mode only) */
111263
111511
  drawLinesOnLayer(ctx, x, y) {
@@ -113139,6 +113387,7 @@ class DrawToolCore {
113139
113387
  getVolumeForLayer: (layer) => this.renderer.getVolumeForLayer(layer),
113140
113388
  pushUndoDelta: (delta) => this.undoManager.push(delta),
113141
113389
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, ctx, w, h) => this.renderer.renderSliceToCanvas(layer, axis, sliceIndex, buffer, ctx, w, h),
113390
+ renderSliceForBake: (layer, axis, sliceIndex, ctx, w, h) => this.renderer.renderSliceForBake(layer, axis, sliceIndex, ctx, w, h),
113142
113391
  getOrCreateSliceBuffer: (axis) => this.renderer.getOrCreateSliceBuffer(axis),
113143
113392
  });
113144
113393
  this.sphereBrushTool = new SphereBrushTool(toolCtx, {
@@ -113831,6 +114080,17 @@ class DrawToolCore {
113831
114080
  this.state.annotationCallbacks.onLayerVolumeReplaced(layerId);
113832
114081
  }
113833
114082
  }
114083
+ /**
114084
+ * A copy of one layer's voxel buffer, or null if the layer has no volume.
114085
+ *
114086
+ * The read-only counterpart to replaceLayerVolume, and a copy rather than the live buffer:
114087
+ * handing out the renderer's own array would let a caller mutate the volume behind it, with
114088
+ * nothing invalidating the slice cache.
114089
+ */
114090
+ getLayerVolume(layerId) {
114091
+ const vol = this.renderer.getVolumeForLayer(layerId);
114092
+ return vol ? new Uint8Array(vol.getRawData()) : null;
114093
+ }
113834
114094
  /**
113835
114095
  * Replace a layer's entire volume, optionally recording it as one undo step.
113836
114096
  *
@@ -114039,6 +114299,8 @@ class GuiState {
114039
114299
  fillColor: (_b = opts.defaultFillColor) !== null && _b !== void 0 ? _b : "#f50a33",
114040
114300
  brushColor: (_c = opts.defaultBrushColor) !== null && _c !== void 0 ? _c : "#f50a33",
114041
114301
  brushAndEraserSize: 10,
114302
+ // Filled is what every existing caller already gets; outline is opt-in.
114303
+ maskRenderMode: "fill",
114042
114304
  };
114043
114305
  this.viewConfig = {
114044
114306
  mainAreaSize: 3,
@@ -116229,6 +116491,21 @@ class NrrdTools {
116229
116491
  setLayerOpacity(layerId, opacity) { this.layerChannelManager.setLayerOpacity(layerId, opacity); }
116230
116492
  getLayerOpacity(layerId) { return this.layerChannelManager.getLayerOpacity(layerId); }
116231
116493
  getLayerOpacityMap() { return this.layerChannelManager.getLayerOpacityMap(); }
116494
+ /**
116495
+ * Fill every mask, or stroke only its boundary — for every layer and channel at once.
116496
+ *
116497
+ * A display decision, and nothing but: `MaskVolume` is not read differently and not written
116498
+ * at all, so what is stored, uploaded, exported and undone is the complete mask either way.
116499
+ *
116500
+ * Repaints immediately, the same way `setChannelVisible` does, because there is no other
116501
+ * event that would bring the change to the screen — a clinician who switched the mode and
116502
+ * then had to scrub a slice to see it would reasonably call that broken.
116503
+ */
116504
+ setMaskRenderMode(mode) {
116505
+ this.state.gui_states.drawing.maskRenderMode = mode;
116506
+ this.reloadMasksFromVolume();
116507
+ }
116508
+ getMaskRenderMode() { return this.state.gui_states.drawing.maskRenderMode; }
116232
116509
  // ═══════════════════════════════════════════════════════════════════════════
116233
116510
  // 8. Delegated — SliceRenderPipeline
116234
116511
  // ═══════════════════════════════════════════════════════════════════════════
@@ -116650,6 +116927,16 @@ class NrrdTools {
116650
116927
  // Refresh the display so all three axes reflect the new data
116651
116928
  this.reloadMasksFromVolume();
116652
116929
  }
116930
+ /**
116931
+ * A copy of one layer's voxel buffer, or null if the layer has no volume.
116932
+ *
116933
+ * Pairs with `replaceLayerVolume`, so a caller can move a mask from one layer to another
116934
+ * through the undoable path rather than through `copyLayerData`, which writes the target
116935
+ * buffer directly and leaves nothing for Ctrl+Z.
116936
+ */
116937
+ getLayerVolume(layerId) {
116938
+ return this.drawCore.getLayerVolume(layerId);
116939
+ }
116653
116940
  /**
116654
116941
  * Replace a layer's entire voxel buffer.
116655
116942
  *
@@ -117835,15 +118122,15 @@ function installFastSliceRepaint(rawSlice_1) {
117835
118122
  }
117836
118123
 
117837
118124
  // import * as kiwrious from "copper3d_plugin_heart_k";
117838
- // "v3.10.2" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118125
+ // "v3.10.4" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
117839
118126
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
117840
118127
  // referencing it throws a ReferenceError — guard it so local loading still works.
117841
118128
  let _revision = "unknown";
117842
118129
  try {
117843
- _revision = "v3.10.2";
118130
+ _revision = "v3.10.4";
117844
118131
  }
117845
118132
  catch (_a) {
117846
- /* "v3.10.2" not injected (local source build) */
118133
+ /* "v3.10.4" not injected (local source build) */
117847
118134
  }
117848
118135
  const REVISION = _revision;
117849
118136
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__