copper3d 3.10.1 → 3.10.3

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 (42) hide show
  1. package/README.md +23 -3
  2. package/dist/Utils/segmentation/DrawToolCore.js +1 -0
  3. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  4. package/dist/Utils/segmentation/NrrdTools.d.ts +41 -1
  5. package/dist/Utils/segmentation/NrrdTools.js +76 -0
  6. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  7. package/dist/Utils/segmentation/RenderingUtils.d.ts +32 -0
  8. package/dist/Utils/segmentation/RenderingUtils.js +107 -12
  9. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  10. package/dist/Utils/segmentation/core/MarchingSquares.d.ts +26 -0
  11. package/dist/Utils/segmentation/core/MarchingSquares.js +113 -0
  12. package/dist/Utils/segmentation/core/MarchingSquares.js.map +1 -1
  13. package/dist/Utils/segmentation/core/MaskVolume.d.ts +32 -5
  14. package/dist/Utils/segmentation/core/MaskVolume.js +95 -18
  15. package/dist/Utils/segmentation/core/MaskVolume.js.map +1 -1
  16. package/dist/Utils/segmentation/core/index.d.ts +3 -3
  17. package/dist/Utils/segmentation/core/index.js +2 -2
  18. package/dist/Utils/segmentation/core/index.js.map +1 -1
  19. package/dist/Utils/segmentation/core/types.d.ts +32 -21
  20. package/dist/Utils/segmentation/core/types.js +77 -10
  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 +503 -48
  29. package/dist/bundle.umd.js +503 -47
  30. package/dist/index.d.ts +4 -3
  31. package/dist/index.js +2 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/types/Utils/segmentation/NrrdTools.d.ts +41 -1
  34. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +32 -0
  35. package/dist/types/Utils/segmentation/core/MarchingSquares.d.ts +26 -0
  36. package/dist/types/Utils/segmentation/core/MaskVolume.d.ts +32 -5
  37. package/dist/types/Utils/segmentation/core/index.d.ts +3 -3
  38. package/dist/types/Utils/segmentation/core/types.d.ts +32 -21
  39. package/dist/types/Utils/segmentation/tools/DrawingTool.d.ts +19 -2
  40. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +7 -1
  41. package/dist/types/index.d.ts +4 -3
  42. package/package.json +1 -1
@@ -106326,7 +106326,65 @@ void main() {
106326
106326
  * | 7 | Auxiliary annotation | Orange |
106327
106327
  * | 8 | Extended annotation | Purple |
106328
106328
  */
106329
- const MASK_CHANNEL_COLORS = {
106329
+ /**
106330
+ * The largest label a mask voxel can carry. `MaskVolume` stores one byte per voxel and the
106331
+ * value IS the label, so 0 is empty and 1-255 are annotation channels.
106332
+ */
106333
+ const MAX_ENGINE_CHANNEL = 255;
106334
+ /** Highest channel whose colour is delivered rather than generated. */
106335
+ const SEEDED_CHANNELS = 8;
106336
+ /**
106337
+ * Successive hues this far apart never revisit an earlier one, which is the whole reason to
106338
+ * use it: any prefix of the sequence is about as spread out as that many hues can be.
106339
+ */
106340
+ const GOLDEN_ANGLE_DEGREES = 137.508;
106341
+ /**
106342
+ * The colour for a channel past the delivered eight.
106343
+ *
106344
+ * Saturation and lightness are fixed so the only thing that varies is hue: these sit on
106345
+ * greyscale MRI, where a mask that changes brightness between channels reads as a difference
106346
+ * in the image rather than in the annotation.
106347
+ *
106348
+ * Distinct is not the same as distinguishable. Past roughly twenty, neighbouring hues stop
106349
+ * being tellable apart by eye on a greyscale background; that is a limit on how many findings
106350
+ * a product should offer at once, not on what this function will return.
106351
+ */
106352
+ function generatedChannelColor(channel) {
106353
+ const hue = ((channel - SEEDED_CHANNELS - 1) * GOLDEN_ANGLE_DEGREES) % 360;
106354
+ return hslToRgba(hue, 0.68, 0.55);
106355
+ }
106356
+ /** HSL (h in degrees, s and l in 0-1) to the 0-255 RGBA this module stores. */
106357
+ function hslToRgba(h, s, l) {
106358
+ const c = (1 - Math.abs(2 * l - 1)) * s;
106359
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
106360
+ const m = l - c / 2;
106361
+ const [r, g, b] = h < 60 ? [c, x, 0] :
106362
+ h < 120 ? [x, c, 0] :
106363
+ h < 180 ? [0, c, x] :
106364
+ h < 240 ? [0, x, c] :
106365
+ h < 300 ? [x, 0, c] :
106366
+ [c, 0, x];
106367
+ const to255 = (v) => Math.round((v + m) * 255);
106368
+ return { r: to255(r), g: to255(g), b: to255(b), a: 255 };
106369
+ }
106370
+ /**
106371
+ * A delivered 0-8 table, continued to 255 with generated colours.
106372
+ *
106373
+ * The seeds are kept verbatim rather than regenerated: every delivered case's chips, 3D
106374
+ * overlay tints and printed report outlines are keyed on them, so a formula that happened to
106375
+ * produce different values would silently recolour work already read and signed off.
106376
+ *
106377
+ * Built eagerly rather than behind a Proxy. `applyLayerChannelColors` walks these with
106378
+ * `Object.entries`, which a Proxy's `get` trap would not serve.
106379
+ */
106380
+ function extendPalette(seed, from) {
106381
+ const table = Object.assign({}, seed);
106382
+ for (let channel = SEEDED_CHANNELS + 1; channel <= MAX_ENGINE_CHANNEL; channel++) {
106383
+ table[channel] = from(generatedChannelColor(channel));
106384
+ }
106385
+ return table;
106386
+ }
106387
+ const MASK_CHANNEL_COLORS_SEED = {
106330
106388
  0: { r: 0, g: 0, b: 0, a: 0 }, // Background (transparent)
106331
106389
  1: { r: 16, g: 185, b: 129, a: 255 }, // Emerald / Soft Green — Primary / Tumor
106332
106390
  2: { r: 244, g: 63, b: 94, a: 255 }, // Rose / Soft Red — Secondary / Edema
@@ -106340,7 +106398,7 @@ void main() {
106340
106398
  /**
106341
106399
  * CSS color strings for the default channel palette (for reference / UI).
106342
106400
  */
106343
- const MASK_CHANNEL_CSS_COLORS = {
106401
+ const MASK_CHANNEL_CSS_COLORS_SEED = {
106344
106402
  0: 'rgba(0,0,0,0)',
106345
106403
  1: 'rgba(16,185,129,1)', // Emerald
106346
106404
  2: 'rgba(244,63,94,1)', // Rose
@@ -106351,15 +106409,10 @@ void main() {
106351
106409
  7: 'rgba(249,115,22,1)', // Orange
106352
106410
  8: 'rgba(139,92,246,1)', // Violet
106353
106411
  };
106354
- /**
106355
- * Convenience alias for MASK_CHANNEL_CSS_COLORS.
106356
- * Used by Vue components via `Copper.CHANNEL_COLORS[channel]`.
106357
- */
106358
- const CHANNEL_COLORS = MASK_CHANNEL_CSS_COLORS;
106359
106412
  /**
106360
106413
  * Hex color strings for each channel (no alpha), used for fillColor/brushColor.
106361
106414
  */
106362
- const CHANNEL_HEX_COLORS = {
106415
+ const CHANNEL_HEX_COLORS_SEED = {
106363
106416
  0: '#000000',
106364
106417
  1: '#10b981', // Emerald
106365
106418
  2: '#f43f5e', // Rose
@@ -106378,7 +106431,7 @@ void main() {
106378
106431
  * Applied ONLY to the AI scratch layer (set per-volume in AiAssistTool.enter) —
106379
106432
  * the global palette above is untouched, so the clinician mask stays emerald.
106380
106433
  */
106381
- const AI_MASK_CHANNEL_COLORS = {
106434
+ const AI_MASK_CHANNEL_COLORS_SEED = {
106382
106435
  0: { r: 0, g: 0, b: 0, a: 0 },
106383
106436
  1: { r: 94, g: 200, b: 255, a: 255 }, // Cyan (#5ec8ff) — AI accent (was emerald)
106384
106437
  2: { r: 244, g: 63, b: 94, a: 255 }, // Rose
@@ -106389,7 +106442,7 @@ void main() {
106389
106442
  7: { r: 249, g: 115, b: 22, a: 255 }, // Orange
106390
106443
  8: { r: 139, g: 92, b: 246, a: 255 }, // Violet
106391
106444
  };
106392
- const AI_CHANNEL_HEX_COLORS = {
106445
+ const AI_CHANNEL_HEX_COLORS_SEED = {
106393
106446
  0: '#000000',
106394
106447
  1: '#5ec8ff', // Cyan — AI accent
106395
106448
  2: '#f43f5e', // Rose
@@ -106400,6 +106453,20 @@ void main() {
106400
106453
  7: '#f97316', // Orange
106401
106454
  8: '#8b5cf6', // Violet
106402
106455
  };
106456
+ // ── The four palettes, delivered through channel 8 and generated past it ──────
106457
+ const MASK_CHANNEL_COLORS = extendPalette(MASK_CHANNEL_COLORS_SEED, (c) => c);
106458
+ const MASK_CHANNEL_CSS_COLORS = extendPalette(MASK_CHANNEL_CSS_COLORS_SEED, rgbaToCss);
106459
+ const CHANNEL_HEX_COLORS = extendPalette(CHANNEL_HEX_COLORS_SEED, rgbaToHex);
106460
+ const AI_MASK_CHANNEL_COLORS = extendPalette(AI_MASK_CHANNEL_COLORS_SEED, (c) => c);
106461
+ const AI_CHANNEL_HEX_COLORS = extendPalette(AI_CHANNEL_HEX_COLORS_SEED, rgbaToHex);
106462
+ /**
106463
+ * Convenience alias for MASK_CHANNEL_CSS_COLORS.
106464
+ * Used by Vue components via `Copper.CHANNEL_COLORS[channel]`.
106465
+ *
106466
+ * Declared here, with the tables it aliases. It used to sit further up, which was fine while
106467
+ * those were object literals and is a temporal-dead-zone error now that they are built.
106468
+ */
106469
+ const CHANNEL_COLORS = MASK_CHANNEL_CSS_COLORS;
106403
106470
  // ── Color Conversion Utilities ──────────────────────────────────────────
106404
106471
  /**
106405
106472
  * Convert an RGBAColor to a hex string (no alpha), e.g. '#ff0000'.
@@ -106581,16 +106648,16 @@ void main() {
106581
106648
  * Update the color for a specific label/channel in the color map.
106582
106649
  *
106583
106650
  * For label-based volumes (1-channel), the channel parameter refers to
106584
- * the label value (0-8), not the storage channel index.
106651
+ * the label value, not the storage channel index.
106585
106652
  *
106586
- * @param channel Label/channel index to update (0-8).
106653
+ * @param channel Label/channel index to update (0-`MAX_ENGINE_CHANNEL`).
106587
106654
  * @param color New RGBA color.
106588
106655
  *
106589
- * @throws {RangeError} If channel is outside valid label range [0, 8].
106656
+ * @throws {RangeError} If channel is outside the storable label range.
106590
106657
  */
106591
106658
  setChannelColor(channel, color) {
106592
- if (channel < 0 || channel > 8) {
106593
- throw new RangeError(`Invalid channel/label: ${channel} (valid range: 0-8)`);
106659
+ if (channel < 0 || channel > MAX_ENGINE_CHANNEL) {
106660
+ throw new RangeError(`Invalid channel/label: ${channel} (valid range: 0-${MAX_ENGINE_CHANNEL})`);
106594
106661
  }
106595
106662
  this.colorMap[channel] = { r: color.r, g: color.g, b: color.b, a: color.a };
106596
106663
  }
@@ -106820,7 +106887,8 @@ void main() {
106820
106887
  * @param sliceIndex Index along the specified axis.
106821
106888
  * @param imageData Canvas ImageData (RGBA) to convert.
106822
106889
  * @param axis `'x'`, `'y'`, or `'z'`.
106823
- * @param activeChannel Fallback label for pixels whose RGB doesn't match any channel (1-8).
106890
+ * @param activeChannel Fallback label for pixels whose RGB matches no channel exactly,
106891
+ * and one of the candidates the nearest-colour search considers.
106824
106892
  * @param channelVisible Optional map of visible channels (true=visible, false=hidden).
106825
106893
  * If provided, data for hidden channels will be preserved
106826
106894
  * when the canvas pixel is transparent.
@@ -106867,6 +106935,29 @@ void main() {
106867
106935
  iStride = this.bytesPerSlice; // i → z
106868
106936
  break;
106869
106937
  }
106938
+ // Candidates for the nearest-colour fallback below: the labels already on this slice,
106939
+ // plus the one being committed. One cheap pass to collect them, in place of running the
106940
+ // fallback over the whole palette.
106941
+ //
106942
+ // Widening it to all 255 would not just be 255 distance computations per anti-aliased
106943
+ // edge pixel. It would be wrong: the more colours the guess can choose from, the more
106944
+ // readily a fringe resolves to a label that is nowhere on the slice, which puts voxels
106945
+ // into another finding's mask with nothing to show for it.
106946
+ const candidates = [activeChannel];
106947
+ {
106948
+ const seen = new Set([activeChannel]);
106949
+ for (let j = 0; j < expectedH; j++) {
106950
+ let idx = baseIndex + j * jStride;
106951
+ for (let i = 0; i < expectedW; i++) {
106952
+ const label = volData[idx];
106953
+ if (label !== 0 && !seen.has(label)) {
106954
+ seen.add(label);
106955
+ candidates.push(label);
106956
+ }
106957
+ idx += iStride;
106958
+ }
106959
+ }
106960
+ }
106870
106961
  let px = 0;
106871
106962
  for (let j = 0; j < expectedH; j++) {
106872
106963
  let idx = baseIndex + j * jStride;
@@ -106895,8 +106986,10 @@ void main() {
106895
106986
  if (matchedChannel === undefined) {
106896
106987
  let minDist = Infinity;
106897
106988
  let bestChannel = activeChannel;
106898
- // Find the nearest channel color (1-8) to handle Canvas anti-aliased edge pixels
106899
- for (let ch = 1; ch <= 8; ch++) {
106989
+ // Nearest among the labels that can legitimately be here (see `candidates`),
106990
+ // to handle Canvas anti-aliased edge pixels.
106991
+ for (let ci = 0; ci < candidates.length; ci++) {
106992
+ const ch = candidates[ci];
106900
106993
  const c = (_a = this.colorMap[ch]) !== null && _a !== void 0 ? _a : MASK_CHANNEL_COLORS[ch];
106901
106994
  if (!c)
106902
106995
  continue;
@@ -106920,19 +107013,25 @@ void main() {
106920
107013
  }
106921
107014
  /**
106922
107015
  * Build a Map from RGB packed integer to channel label for reverse lookup.
106923
- * Uses this instance's colorMap (channels 1-8, skips 0 = transparent).
107016
+ * Covers every label this instance has a colour for, skipping 0 (transparent).
106924
107017
  *
106925
107018
  * Instance method ensures custom per-layer colors are correctly reverse-mapped.
106926
107019
  */
106927
107020
  buildRgbToChannelMap() {
106928
- var _a;
106929
107021
  const map = new Map();
106930
- for (let ch = 1; ch <= 8; ch++) {
106931
- const color = (_a = this.colorMap[ch]) !== null && _a !== void 0 ? _a : MASK_CHANNEL_COLORS[ch];
106932
- if (color) {
106933
- const key = (color.r << 16) | (color.g << 8) | color.b;
106934
- map.set(key, ch);
106935
- }
107022
+ // Every label this volume has a colour for, not a fixed 1-8. A pixel painted in
107023
+ // channel 12's colour used to miss this table entirely and fall through to the
107024
+ // nearest-colour guess, which could only ever answer 1-8 -- so the channel could be
107025
+ // drawn and could never be read back. Size is not a cost here: it is built once per
107026
+ // readback and every lookup against it is O(1).
107027
+ for (const key of Object.keys(this.colorMap)) {
107028
+ const ch = Number(key);
107029
+ if (ch < 1)
107030
+ continue; // 0 is "empty", and it is transparent rather than a colour
107031
+ const color = this.colorMap[ch];
107032
+ if (!color)
107033
+ continue;
107034
+ map.set((color.r << 16) | (color.g << 8) | color.b, ch);
106936
107035
  }
106937
107036
  return map;
106938
107037
  }
@@ -106997,8 +107096,11 @@ void main() {
106997
107096
  pixels[px + 1] = 0;
106998
107097
  pixels[px + 2] = 0;
106999
107098
  pixels[px + 3] = 0;
107099
+ // `=== false`, not falsy: the map records what has been HIDDEN and never covers
107100
+ // every label. `setSliceLabelsFromImageData` already reads it this way; reading it
107101
+ // as falsy here made any label the map did not mention render as invisible.
107000
107102
  }
107001
- else if (channelVisible && !channelVisible[label]) {
107103
+ else if ((channelVisible === null || channelVisible === void 0 ? void 0 : channelVisible[label]) === false) {
107002
107104
  pixels[px] = 0;
107003
107105
  pixels[px + 1] = 0;
107004
107106
  pixels[px + 2] = 0;
@@ -107140,6 +107242,48 @@ void main() {
107140
107242
  this.data.fill(0);
107141
107243
  this.version++;
107142
107244
  }
107245
+ /**
107246
+ * Zero every voxel carrying one label, leaving every other label in place.
107247
+ *
107248
+ * The third member of the clear family: `clear()` takes the whole volume and
107249
+ * `clearSlice()` takes one slice, both regardless of label. Deleting a single
107250
+ * annotation needs neither — its mask is one label inside a volume it shares with
107251
+ * every other annotation on that layer, so anything coarser takes the neighbours
107252
+ * with it.
107253
+ *
107254
+ * Label-based volumes only, which is what `numChannels === 1` means here: the voxel
107255
+ * value IS the label. A multi-plane volume stores channels as separate planes and
107256
+ * would need a different sweep.
107257
+ *
107258
+ * The version is bumped only when a voxel actually changed. Every derived cache keyed
107259
+ * on it — the contour cache above all — is invalidated by a bump, so bumping for a
107260
+ * clear that found nothing would redraw the layer for no reason.
107261
+ *
107262
+ * @param channel Label to erase, 1-255. Zero is "empty", not a channel.
107263
+ * @throws {RangeError} If `channel` is outside [1, 255].
107264
+ *
107265
+ * @example
107266
+ * ```ts
107267
+ * vol.clearChannel(3); // finding 3's voxels go; 1, 2 and 4 stay
107268
+ * ```
107269
+ */
107270
+ clearChannel(channel) {
107271
+ // Upper bound is what a Uint8 label can hold. Task 5 of the channel-cap work
107272
+ // replaces both this and setChannelColor's guard with one MAX_ENGINE_CHANNEL.
107273
+ if (!Number.isInteger(channel) || channel < 1 || channel > 255) {
107274
+ throw new RangeError(`Invalid channel to clear: ${channel} (valid range: 1-255; 0 is empty)`);
107275
+ }
107276
+ const data = this.data;
107277
+ let changed = false;
107278
+ for (let i = 0; i < data.length; i++) {
107279
+ if (data[i] === channel) {
107280
+ data[i] = 0;
107281
+ changed = true;
107282
+ }
107283
+ }
107284
+ if (changed)
107285
+ this.version++;
107286
+ }
107143
107287
  /**
107144
107288
  * Check if the volume contains any non-zero voxel data.
107145
107289
  *
@@ -107766,6 +107910,50 @@ void main() {
107766
107910
  /* 14 (TL+TR+BR, !BL) */ [[[0, 0], [1, 0], [1, 1], [0.5, 1], [0, 0.5]]],
107767
107911
  /* 15 (full) */ [[[0, 0], [1, 0], [1, 1], [0, 1]]],
107768
107912
  ];
107913
+ /**
107914
+ * Per-cell boundary segments for the same 16 cases — the region's edge, without the region.
107915
+ *
107916
+ * Each entry is the cut line of the corresponding `CELL_POLYGONS` entry: the one edge of that
107917
+ * polygon which does not lie on the cell's border. Filling the polygons and stroking these
107918
+ * therefore describe the same silhouette, which is what lets the renderer swap fill for
107919
+ * outline without the mask's edge appearing to move.
107920
+ *
107921
+ * Endpoints are the midpoints of the cell's sides —
107922
+ * T = (0.5, 0) R = (1, 0.5) B = (0.5, 1) L = (0, 0.5)
107923
+ * — in the same cell-local 0..1 space as `CELL_POLYGONS`, so the caller adds (i, j) + SHIFT
107924
+ * identically for both.
107925
+ *
107926
+ * Cases 0 and 15 emit nothing. 15 is the whole reason an outline is cheap: solid interior has
107927
+ * no boundary, so the segment count follows the perimeter rather than the area.
107928
+ *
107929
+ * Saddles (5 and 10) follow `CELL_POLYGONS`' convention — the two in-corners are disconnected
107930
+ * (4-connectivity) — because the other reading would run a boundary straight through mask the
107931
+ * fill considers solid.
107932
+ */
107933
+ const CELL_SEGMENTS = [
107934
+ /* 0 (empty) */ [],
107935
+ /* 1 (BL) */ [[[0, 0.5], [0.5, 1]]],
107936
+ /* 2 (BR) */ [[[0.5, 1], [1, 0.5]]],
107937
+ /* 3 (BR+BL) */ [[[0, 0.5], [1, 0.5]]],
107938
+ /* 4 (TR) */ [[[0.5, 0], [1, 0.5]]],
107939
+ /* 5 (TR+BL saddle) */ [
107940
+ [[0.5, 0], [1, 0.5]],
107941
+ [[0, 0.5], [0.5, 1]],
107942
+ ],
107943
+ /* 6 (TR+BR) */ [[[0.5, 0], [0.5, 1]]],
107944
+ /* 7 (TR+BR+BL, !TL) */ [[[0.5, 0], [0, 0.5]]],
107945
+ /* 8 (TL) */ [[[0.5, 0], [0, 0.5]]],
107946
+ /* 9 (TL+BL) */ [[[0.5, 0], [0.5, 1]]],
107947
+ /* 10 (TL+BR saddle) */ [
107948
+ [[0.5, 0], [0, 0.5]],
107949
+ [[0.5, 1], [1, 0.5]],
107950
+ ],
107951
+ /* 11 (TL+BR+BL, !TR) */ [[[0.5, 0], [1, 0.5]]],
107952
+ /* 12 (TL+TR) */ [[[1, 0.5], [0, 0.5]]],
107953
+ /* 13 (TL+TR+BL, !BR) */ [[[1, 0.5], [0.5, 1]]],
107954
+ /* 14 (TL+TR+BR, !BL) */ [[[0.5, 1], [0, 0.5]]],
107955
+ /* 15 (full) */ [],
107956
+ ];
107769
107957
  /**
107770
107958
  * Emit polygons covering the voxels where `labels === targetLabel`.
107771
107959
  * Pure geometry function — no Canvas dependency. Consumers can build a Path2D
@@ -107887,6 +108075,75 @@ void main() {
107887
108075
  }
107888
108076
  return path;
107889
108077
  }
108078
+ /**
108079
+ * Emit the boundary of the region where `labels === targetLabel`, as open two-point segments.
108080
+ *
108081
+ * The counterpart to {@link extractLabelPolygons}: that one covers the region, this one traces
108082
+ * its edge. Both walk the same cells with the same sampling, the same out-of-bounds rule and
108083
+ * the same `+0.5` shift, so a renderer can fill one and stroke the other and have the mask end
108084
+ * in exactly the same place either way.
108085
+ *
108086
+ * Segments are emitted per cell and left unjoined. Canvas rasterises a whole `Path2D` in one
108087
+ * compositing pass, so segments meeting at a shared endpoint produce no seam and no doubled
108088
+ * alpha where their round caps overlap — joining them into polylines would buy nothing and
108089
+ * cost a chaining pass.
108090
+ *
108091
+ * Cost follows the perimeter, not the area: solid interior is case 15, which has no boundary.
108092
+ *
108093
+ * Parameters match {@link extractLabelContours}.
108094
+ */
108095
+ function extractLabelBoundarySegments(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox) {
108096
+ var _a, _b, _c, _d;
108097
+ const out = [];
108098
+ const i0 = Math.max(-1, ((_a = bbox === null || bbox === void 0 ? void 0 : bbox.x0) !== null && _a !== void 0 ? _a : 0) - 1);
108099
+ const j0 = Math.max(-1, ((_b = bbox === null || bbox === void 0 ? void 0 : bbox.y0) !== null && _b !== void 0 ? _b : 0) - 1);
108100
+ const i1 = Math.min(width, (_c = bbox === null || bbox === void 0 ? void 0 : bbox.x1) !== null && _c !== void 0 ? _c : width);
108101
+ const j1 = Math.min(height, (_d = bbox === null || bbox === void 0 ? void 0 : bbox.y1) !== null && _d !== void 0 ? _d : height);
108102
+ const sample = (x, y) => {
108103
+ if (x < 0 || x >= width || y < 0 || y >= height)
108104
+ return false;
108105
+ return labels[(y * width + x) * stride + channelOffset] === targetLabel;
108106
+ };
108107
+ // Same convention as extractLabelPolygons: samples sit at voxel centres.
108108
+ const SHIFT = 0.5;
108109
+ for (let j = j0; j < j1; j++) {
108110
+ for (let i = i0; i < i1; i++) {
108111
+ const code = (sample(i, j) ? 8 : 0) |
108112
+ (sample(i + 1, j) ? 4 : 0) |
108113
+ (sample(i + 1, j + 1) ? 2 : 0) |
108114
+ (sample(i, j + 1) ? 1 : 0);
108115
+ // Nothing here, or nothing but mask: neither has an edge in this cell.
108116
+ if (code === 0 || code === 15)
108117
+ continue;
108118
+ const segments = CELL_SEGMENTS[code];
108119
+ for (let s = 0; s < segments.length; s++) {
108120
+ const [a, b] = segments[s];
108121
+ out.push([
108122
+ [i + a[0] + SHIFT, j + a[1] + SHIFT],
108123
+ [i + b[0] + SHIFT, j + b[1] + SHIFT],
108124
+ ]);
108125
+ }
108126
+ }
108127
+ }
108128
+ return out;
108129
+ }
108130
+ /**
108131
+ * {@link extractLabelBoundarySegments} as a `Path2D`, ready to stroke.
108132
+ *
108133
+ * The outline counterpart to {@link extractLabelContours}. Stroke this; do not stroke the
108134
+ * contour path — that one is per-cell polygons whose union is the silhouette, and stroking it
108135
+ * draws every internal cell edge as well, covering the mask in a grid.
108136
+ */
108137
+ function extractLabelOutline(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox) {
108138
+ const segments = extractLabelBoundarySegments(labels, width, height, targetLabel, stride, channelOffset, bbox);
108139
+ const path = new Path2D();
108140
+ for (let s = 0; s < segments.length; s++) {
108141
+ const [a, b] = segments[s];
108142
+ path.moveTo(a[0], a[1]);
108143
+ path.lineTo(b[0], b[1]);
108144
+ }
108145
+ return path;
108146
+ }
107890
108147
  /**
107891
108148
  * Detect the distinct non-zero labels present in a slice region.
107892
108149
  *
@@ -109324,6 +109581,14 @@ void main() {
109324
109581
  }
109325
109582
  }
109326
109583
 
109584
+ /**
109585
+ * Outline stroke width, in screen pixels.
109586
+ *
109587
+ * Screen pixels rather than voxels so magnifying the image does not thicken the line over the
109588
+ * boundary the clinician magnified it to see. Thin enough to sit on an edge, thick enough to
109589
+ * stay visible against bright tissue.
109590
+ */
109591
+ const OUTLINE_WIDTH_PX = 1.5;
109327
109592
  /**
109328
109593
  * RenderingUtils — Rendering / slice-buffer helper methods.
109329
109594
  *
@@ -109355,6 +109620,12 @@ void main() {
109355
109620
  * applied at fill time and intentionally *not* cached, so toggling them
109356
109621
  * needs no recompute.
109357
109622
  *
109623
+ * The render mode is not in the key either. Fill paths and outline paths
109624
+ * are built lazily and side by side under the same entry, so switching
109625
+ * mode costs one extraction per visible label the first time and is a
109626
+ * cache hit every time after — and a session that never leaves fill mode
109627
+ * never builds an outline.
109628
+ *
109358
109629
  * One entry per layer (the current slice). Switching slice/axis or
109359
109630
  * editing overwrites it.
109360
109631
  */
@@ -109441,6 +109712,22 @@ void main() {
109441
109712
  return null; // Volume not ready
109442
109713
  }
109443
109714
  }
109715
+ /**
109716
+ * Populate one cache entry's paths for one render mode.
109717
+ *
109718
+ * Split out because the two modes are built at different times: whichever is in use when
109719
+ * a slice is first drawn, and the other one only if the clinician switches while still on
109720
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
109721
+ * sessions never turn on.
109722
+ */
109723
+ buildPaths(entry, data, stride, outline) {
109724
+ const target = outline ? entry.outlines : entry.fills;
109725
+ for (const lbl of entry.labels) {
109726
+ target.set(lbl, outline
109727
+ ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109728
+ : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109729
+ }
109730
+ }
109444
109731
  /**
109445
109732
  * Render a layer's slice onto the target canvas as vector contours.
109446
109733
  *
@@ -109453,6 +109740,27 @@ void main() {
109453
109740
  * is no longer used on this path — callers may pass any valid ImageData.
109454
109741
  */
109455
109742
  renderSliceToCanvas(layer, axis, sliceIndex, _buffer, targetCtx, scaledWidth, scaledHeight) {
109743
+ this.drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, this.state.gui_states.drawing.maskRenderMode === "outline");
109744
+ }
109745
+ /**
109746
+ * Render a layer's slice FILLED, whatever the clinician is currently looking at.
109747
+ *
109748
+ * For the tools that bake (`syncLayerSliceData` — pencil and eraser) the layer canvas is
109749
+ * not a picture of the mask, it is the input the mask is rebuilt from: the bake replaces
109750
+ * the whole slice in `MaskVolume` with whatever pixels it finds there.
109751
+ *
109752
+ * An outline is a lossy picture — it says where a mask ends, not what it contains — so
109753
+ * baking one back writes rings and erases every interior on that slice, taking every other
109754
+ * finding on the layer with it. One pencil stroke was enough.
109755
+ *
109756
+ * Hence a separate entry point rather than a flag threaded through the display path: a
109757
+ * render that is about to be read back has a different requirement from one that is about
109758
+ * to be looked at, and the two only coincided while there was one way to draw a mask.
109759
+ */
109760
+ renderSliceForBake(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight) {
109761
+ this.drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, false);
109762
+ }
109763
+ drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, outline) {
109456
109764
  try {
109457
109765
  const volume = this.getVolumeForLayer(layer);
109458
109766
  if (!volume)
@@ -109460,28 +109768,72 @@ void main() {
109460
109768
  const stride = volume.getChannels();
109461
109769
  const cacheKey = `${axis}:${sliceIndex}:${volume.getVersion()}`;
109462
109770
  // Cache miss → run the expensive extraction once. Hits (zoom,
109463
- // recomposite, contrast toggle) skip straight to the fill below.
109771
+ // recomposite, contrast toggle) skip straight to the draw below.
109464
109772
  let entry = this._contourCache.get(layer);
109465
109773
  if (!entry || entry.key !== cacheKey) {
109466
109774
  const slice = volume.getSliceUint8(sliceIndex, axis);
109467
- const W = slice.width;
109468
- const H = slice.height;
109469
- const labels = findLabelsInSlice(slice.data, W, H, stride, 0);
109470
- const paths = new Map();
109471
- for (const lbl of labels) {
109472
- paths.set(lbl, extractLabelContours(slice.data, W, H, lbl, stride, 0));
109473
- }
109474
- entry = { key: cacheKey, W, H, labels, paths };
109775
+ entry = {
109776
+ key: cacheKey,
109777
+ W: slice.width,
109778
+ H: slice.height,
109779
+ labels: findLabelsInSlice(slice.data, slice.width, slice.height, stride, 0),
109780
+ fills: new Map(),
109781
+ outlines: new Map(),
109782
+ };
109475
109783
  this._contourCache.set(layer, entry);
109784
+ this.buildPaths(entry, slice.data, stride, outline);
109785
+ }
109786
+ else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109787
+ // The mode changed since this slice was last drawn, so the other set of
109788
+ // paths is cached and this one is not. Re-read the slice and build it; from
109789
+ // here on both are present and toggling is a pure cache hit.
109790
+ const slice = volume.getSliceUint8(sliceIndex, axis);
109791
+ this.buildPaths(entry, slice.data, stride, outline);
109476
109792
  }
109477
109793
  if (entry.labels.length === 0)
109478
109794
  return;
109479
- const { W, H, labels, paths } = entry;
109795
+ const { W, H, labels } = entry;
109796
+ const paths = outline ? entry.outlines : entry.fills;
109480
109797
  const channelVis = this.state.gui_states.layerChannel.channelVisibility[layer];
109481
109798
  targetCtx.save();
109482
- // Vector fill — imageSmoothingEnabled is irrelevant here, but keep
109799
+ // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109483
109800
  // it off to match the rest of the pipeline.
109484
109801
  targetCtx.imageSmoothingEnabled = false;
109802
+ if (outline) {
109803
+ // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109804
+ // in the path instead. `lineWidth` is then measured in screen pixels, which
109805
+ // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109806
+ // thickens the line with the zoom, exactly when the clinician has magnified
109807
+ // the image to look at the boundary — and because voxels are rarely isotropic
109808
+ // (sx !== sy), it also comes out thicker in one axis than the other.
109809
+ const matrix = new DOMMatrix();
109810
+ if (axis === 'y') {
109811
+ matrix.scaleSelf(1, -1);
109812
+ matrix.translateSelf(0, -scaledHeight);
109813
+ }
109814
+ matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109815
+ targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109816
+ // Segments are emitted per cell and meet at shared endpoints; round caps
109817
+ // close those joins. Canvas composites a whole Path2D in one pass, so the
109818
+ // overlap costs no doubled alpha.
109819
+ targetCtx.lineJoin = 'round';
109820
+ targetCtx.lineCap = 'round';
109821
+ for (const lbl of labels) {
109822
+ if (channelVis && channelVis[lbl] === false)
109823
+ continue;
109824
+ const path = paths.get(lbl);
109825
+ if (!path)
109826
+ continue;
109827
+ const color = volume.getChannelColor(lbl);
109828
+ targetCtx.strokeStyle =
109829
+ `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109830
+ const display = new Path2D();
109831
+ display.addPath(path, matrix);
109832
+ targetCtx.stroke(display);
109833
+ }
109834
+ targetCtx.restore();
109835
+ return;
109836
+ }
109485
109837
  // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109486
109838
  // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109487
109839
  // so the flip operates in display coordinates.
@@ -110699,6 +111051,11 @@ void main() {
110699
111051
  this.ctx.nrrd_states.interaction.drawStartPos.y = e.offsetY;
110700
111052
  // Capture pre-draw slice snapshot for undo
110701
111053
  this.capturePreDrawSnapshot();
111054
+ // The eraser works on canvas pixels and then bakes the canvas back into the volume, so
111055
+ // it needs the layer solid rather than outlined for the length of the stroke. The display
111056
+ // mode comes back at pointerup, via refreshLayerFromVolume.
111057
+ if (this.ctx.gui_states.mode.eraser)
111058
+ this.solidifyLayerForErase();
110702
111059
  // Brush mode: initialize voxel tracking and write first dot
110703
111060
  if (!this.ctx.gui_states.mode.pencil && !this.ctx.gui_states.mode.eraser) {
110704
111061
  const voxel = this.canvasToVoxel3D(e.offsetX, e.offsetY);
@@ -111111,17 +111468,36 @@ void main() {
111111
111468
  this.preDrawSlice = null;
111112
111469
  }
111113
111470
  /**
111114
- * Redraws persisted layer data onto ctx before new pencil fill.
111115
- * Delegates to the host's vector renderSliceToCanvas for consistency.
111471
+ * Redraws persisted layer data onto ctx before the new pencil fill.
111472
+ *
111473
+ * Uses the BAKE renderer, not the display one. What lands on this canvas is about to be
111474
+ * read straight back into the MaskVolume by `syncLayerSliceData`, which replaces the whole
111475
+ * slice -- so this render is the data, not a picture of it. Drawing outlines here would
111476
+ * bake rings and erase the interior of every mask on the layer.
111116
111477
  */
111117
111478
  redrawPreviousImageToLayerCtx(ctx) {
111118
111479
  const axis = this.ctx.protectedData.axis;
111119
111480
  const W = this.ctx.nrrd_states.view.changedWidth;
111120
111481
  const H = this.ctx.nrrd_states.view.changedHeight;
111121
- const buffer = this.callbacks.getOrCreateSliceBuffer(axis);
111122
- if (!buffer)
111123
- return;
111124
- this.callbacks.renderSliceToCanvas(this.ctx.gui_states.layerChannel.layer, axis, this.ctx.nrrd_states.view.currentSliceIndex, buffer, ctx, W, H);
111482
+ this.callbacks.renderSliceForBake(this.ctx.gui_states.layerChannel.layer, axis, this.ctx.nrrd_states.view.currentSliceIndex, ctx, W, H);
111483
+ }
111484
+ /**
111485
+ * Put the active layer's canvas into the solid state the eraser and the bake both need.
111486
+ *
111487
+ * The eraser removes pixels matching the active channel's colour, and `syncLayerSliceData`
111488
+ * then rebuilds the whole slice from what is left on the canvas. Against an outline there
111489
+ * is nothing to match inside a mask, so a drag over a lesion erases nothing -- and the bake
111490
+ * that follows writes the ring back and loses every interior on the layer.
111491
+ *
111492
+ * Unconditional rather than checked against the display mode: in fill mode this redraws
111493
+ * what is already on screen, and a mode-dependent branch here is one more thing that can
111494
+ * fall out of step with the renderer.
111495
+ */
111496
+ solidifyLayerForErase() {
111497
+ const target = this.callbacks.setCurrentLayer();
111498
+ target.canvas.width = target.canvas.width; // clear
111499
+ 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);
111500
+ this.callbacks.compositeAllLayers();
111125
111501
  }
111126
111502
  /** Draw a line segment on a layer canvas (pencil mode only) */
111127
111503
  drawLinesOnLayer(ctx, x, y) {
@@ -113003,6 +113379,7 @@ void main() {
113003
113379
  getVolumeForLayer: (layer) => this.renderer.getVolumeForLayer(layer),
113004
113380
  pushUndoDelta: (delta) => this.undoManager.push(delta),
113005
113381
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, ctx, w, h) => this.renderer.renderSliceToCanvas(layer, axis, sliceIndex, buffer, ctx, w, h),
113382
+ renderSliceForBake: (layer, axis, sliceIndex, ctx, w, h) => this.renderer.renderSliceForBake(layer, axis, sliceIndex, ctx, w, h),
113006
113383
  getOrCreateSliceBuffer: (axis) => this.renderer.getOrCreateSliceBuffer(axis),
113007
113384
  });
113008
113385
  this.sphereBrushTool = new SphereBrushTool(toolCtx, {
@@ -113903,6 +114280,8 @@ void main() {
113903
114280
  fillColor: (_b = opts.defaultFillColor) !== null && _b !== void 0 ? _b : "#f50a33",
113904
114281
  brushColor: (_c = opts.defaultBrushColor) !== null && _c !== void 0 ? _c : "#f50a33",
113905
114282
  brushAndEraserSize: 10,
114283
+ // Filled is what every existing caller already gets; outline is opt-in.
114284
+ maskRenderMode: "fill",
113906
114285
  };
113907
114286
  this.viewConfig = {
113908
114287
  mainAreaSize: 3,
@@ -115631,6 +116010,67 @@ void main() {
115631
116010
  }
115632
116011
  }
115633
116012
  }
116013
+ /**
116014
+ * Erase one channel's mask on one layer, undoably.
116015
+ *
116016
+ * The missing third of the clear family that `executeAction` exposes:
116017
+ * `clearActiveSliceMask` takes one slice, `clearActiveLayerMask` takes a whole layer,
116018
+ * and neither can take a single label. Deleting one annotation needs exactly that —
116019
+ * its mask is one label inside a volume shared with every other annotation on the
116020
+ * layer.
116021
+ *
116022
+ * Not folded into `executeAction`: that signature is an action name plus an options
116023
+ * bag, and this needs two required arguments.
116024
+ *
116025
+ * Deltas go onto the engine's own undo stack, so a mistaken clear is recoverable for
116026
+ * as long as the case stays open. That is the whole reason this lives here rather
116027
+ * than in the app: writing zeros from outside and forcing a repaint by stepping the
116028
+ * slice would bypass the stack, and an accidental clear would be permanent.
116029
+ *
116030
+ * Only slices that actually carry the label are touched, so a small annotation in a
116031
+ * deep volume costs a scan and a handful of callbacks rather than one per slice.
116032
+ *
116033
+ * @param layerId Layer whose mask to edit.
116034
+ * @param channel Label to erase, 1-255.
116035
+ * @throws {Error} If `layerId` names no layer. Deliberately NOT routed through
116036
+ * `getVolumeForLayer`, which warns and falls back to the first layer — for a
116037
+ * destructive call that would quietly erase a different layer's annotation.
116038
+ * @throws {RangeError} If `channel` is outside [1, 255] (from `MaskVolume`).
116039
+ */
116040
+ clearChannel(layerId, channel) {
116041
+ const volume = this.state.protectedData.maskData.volumes[layerId];
116042
+ if (!volume) {
116043
+ const known = this.state.nrrd_states.image.layers.join(", ");
116044
+ throw new Error(`clearChannel: unknown layer "${layerId}" (known layers: ${known})`);
116045
+ }
116046
+ const { depth } = volume.getDimensions();
116047
+ // Snapshot before mutating: `oldSlice` is what undo restores.
116048
+ const deltas = [];
116049
+ for (let z = 0; z < depth; z++) {
116050
+ const slice = volume.getSliceUint8(z, "z").data;
116051
+ if (!slice.some((v) => v === channel))
116052
+ continue;
116053
+ deltas.push({
116054
+ layerId,
116055
+ axis: "z",
116056
+ sliceIndex: z,
116057
+ oldSlice: slice.slice(),
116058
+ newSlice: new Uint8Array(0), // filled below, once the clear has run
116059
+ });
116060
+ }
116061
+ if (deltas.length === 0)
116062
+ return; // nothing drawn on this channel
116063
+ volume.clearChannel(channel);
116064
+ for (const delta of deltas) {
116065
+ delta.newSlice = volume.getSliceUint8(delta.sliceIndex, "z").data.slice();
116066
+ }
116067
+ this.drawCore.undoManager.pushGroup(deltas);
116068
+ for (const delta of deltas) {
116069
+ const { data, width, height } = volume.getSliceUint8(delta.sliceIndex, "z");
116070
+ this.state.annotationCallbacks.onMaskChanged(data, layerId, channel, delta.sliceIndex, "z", width, height, false);
116071
+ }
116072
+ this.reloadMasksFromVolume();
116073
+ }
115634
116074
  // ═══════════════════════════════════════════════════════════════════════════
115635
116075
  // 4. Public API — Keyboard & History
115636
116076
  // ═══════════════════════════════════════════════════════════════════════════
@@ -116032,6 +116472,21 @@ void main() {
116032
116472
  setLayerOpacity(layerId, opacity) { this.layerChannelManager.setLayerOpacity(layerId, opacity); }
116033
116473
  getLayerOpacity(layerId) { return this.layerChannelManager.getLayerOpacity(layerId); }
116034
116474
  getLayerOpacityMap() { return this.layerChannelManager.getLayerOpacityMap(); }
116475
+ /**
116476
+ * Fill every mask, or stroke only its boundary — for every layer and channel at once.
116477
+ *
116478
+ * A display decision, and nothing but: `MaskVolume` is not read differently and not written
116479
+ * at all, so what is stored, uploaded, exported and undone is the complete mask either way.
116480
+ *
116481
+ * Repaints immediately, the same way `setChannelVisible` does, because there is no other
116482
+ * event that would bring the change to the screen — a clinician who switched the mode and
116483
+ * then had to scrub a slice to see it would reasonably call that broken.
116484
+ */
116485
+ setMaskRenderMode(mode) {
116486
+ this.state.gui_states.drawing.maskRenderMode = mode;
116487
+ this.reloadMasksFromVolume();
116488
+ }
116489
+ getMaskRenderMode() { return this.state.gui_states.drawing.maskRenderMode; }
116035
116490
  // ═══════════════════════════════════════════════════════════════════════════
116036
116491
  // 8. Delegated — SliceRenderPipeline
116037
116492
  // ═══════════════════════════════════════════════════════════════════════════
@@ -117638,15 +118093,15 @@ void main() {
117638
118093
  }
117639
118094
 
117640
118095
  // import * as kiwrious from "copper3d_plugin_heart_k";
117641
- // "v3.10.1" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118096
+ // "v3.10.3" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
117642
118097
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
117643
118098
  // referencing it throws a ReferenceError — guard it so local loading still works.
117644
118099
  let _revision = "unknown";
117645
118100
  try {
117646
- _revision = "v3.10.1";
118101
+ _revision = "v3.10.3";
117647
118102
  }
117648
118103
  catch (_a) {
117649
- /* "v3.10.1" not injected (local source build) */
118104
+ /* "v3.10.3" not injected (local source build) */
117650
118105
  }
117651
118106
  const REVISION = _revision;
117652
118107
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__
@@ -117667,6 +118122,7 @@ void main() {
117667
118122
  exports.DEFAULT_AXES = DEFAULT_AXES;
117668
118123
  exports.DEFAULT_TARGET_GREY = DEFAULT_TARGET_GREY;
117669
118124
  exports.GaussianSmoother = GaussianSmoother;
118125
+ exports.MAX_ENGINE_CHANNEL = MAX_ENGINE_CHANNEL;
117670
118126
  exports.MeshNodeTool = MeshNodeTool;
117671
118127
  exports.NrrdTools = NrrdTools;
117672
118128
  exports.REVISION = REVISION;