copper3d 4.1.3 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +15 -1
  2. package/ai-index/guides/nrrd-tools.md +105 -1
  3. package/ai-index/guides/segmentation-module.md +75 -1
  4. package/ai-index/manifest.json +5 -5
  5. package/ai-index/symbols.json +1 -1
  6. package/dist/Utils/segmentation/DrawToolCore.d.ts +18 -0
  7. package/dist/Utils/segmentation/DrawToolCore.js +63 -11
  8. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  9. package/dist/Utils/segmentation/NrrdTools.d.ts +29 -1
  10. package/dist/Utils/segmentation/NrrdTools.js +82 -1
  11. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  12. package/dist/Utils/segmentation/RenderingUtils.d.ts +3 -0
  13. package/dist/Utils/segmentation/RenderingUtils.js +20 -4
  14. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  15. package/dist/Utils/segmentation/core/UndoManager.d.ts +18 -0
  16. package/dist/Utils/segmentation/core/UndoManager.js +19 -3
  17. package/dist/Utils/segmentation/core/UndoManager.js.map +1 -1
  18. package/dist/Utils/segmentation/core/index.d.ts +2 -2
  19. package/dist/Utils/segmentation/core/index.js +1 -1
  20. package/dist/Utils/segmentation/core/index.js.map +1 -1
  21. package/dist/Utils/segmentation/core/types.d.ts +9 -0
  22. package/dist/Utils/segmentation/core/types.js.map +1 -1
  23. package/dist/Utils/segmentation/coreTools/GuiState.d.ts +4 -2
  24. package/dist/Utils/segmentation/coreTools/GuiState.js +3 -1
  25. package/dist/Utils/segmentation/coreTools/GuiState.js.map +1 -1
  26. package/dist/Utils/segmentation/tools/DragSliceTool.js +6 -1
  27. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  28. package/dist/Utils/segmentation/tools/DrawingTool.js +9 -1
  29. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  30. package/dist/Utils/segmentation/tools/HeatmapOverlay.d.ts +37 -0
  31. package/dist/Utils/segmentation/tools/HeatmapOverlay.js +185 -0
  32. package/dist/Utils/segmentation/tools/HeatmapOverlay.js.map +1 -0
  33. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +6 -0
  34. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  35. package/dist/Utils/segmentation/tools/SphereTool.js +6 -0
  36. package/dist/Utils/segmentation/tools/SphereTool.js.map +1 -1
  37. package/dist/bundle.esm.mjs +574 -206
  38. package/dist/bundle.umd.js +574 -205
  39. package/dist/index.d.ts +4 -3
  40. package/dist/index.js +2 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/types/Utils/segmentation/DrawToolCore.d.ts +18 -0
  43. package/dist/types/Utils/segmentation/NrrdTools.d.ts +29 -1
  44. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +3 -0
  45. package/dist/types/Utils/segmentation/core/UndoManager.d.ts +18 -0
  46. package/dist/types/Utils/segmentation/core/index.d.ts +2 -2
  47. package/dist/types/Utils/segmentation/core/types.d.ts +9 -0
  48. package/dist/types/Utils/segmentation/coreTools/GuiState.d.ts +4 -2
  49. package/dist/types/Utils/segmentation/tools/HeatmapOverlay.d.ts +37 -0
  50. package/dist/types/index.d.ts +4 -3
  51. package/package.json +1 -1
@@ -11240,6 +11240,11 @@
11240
11240
  * - maxStackSize: 50 entries per layer.
11241
11241
  * - Undo/redo operations also trigger backend sync via getMask callback.
11242
11242
  */
11243
+ /** The layer an entry belongs to. */
11244
+ function entryLayer(entry) {
11245
+ var _a;
11246
+ return Array.isArray(entry) ? (_a = entry[0]) === null || _a === void 0 ? void 0 : _a.layerId : entry.layerId;
11247
+ }
11243
11248
  const MAX_STACK_SIZE = 50;
11244
11249
  class UndoManager {
11245
11250
  constructor() {
@@ -11312,13 +11317,24 @@
11312
11317
  * @returns The delta(s) that were undone, or undefined if nothing to undo.
11313
11318
  */
11314
11319
  undo() {
11315
- const stack = this.stackFor(this.undoStacks, this.activeLayer);
11316
- const entry = stack.pop();
11320
+ return this.undoOn(this.activeLayer);
11321
+ }
11322
+ /**
11323
+ * Undo the last operation on `layerId`, whichever layer is active. The entry moves to that
11324
+ * layer's redo stack, exactly as `undo` does for the active one.
11325
+ */
11326
+ undoOn(layerId) {
11327
+ const entry = this.stackFor(this.undoStacks, layerId).pop();
11317
11328
  if (entry) {
11318
- this.stackFor(this.redoStacks, this.activeLayer).push(entry);
11329
+ this.stackFor(this.redoStacks, layerId).push(entry);
11319
11330
  }
11320
11331
  return entry;
11321
11332
  }
11333
+ /** The entry an undo on `layerId` would take next, left in place. */
11334
+ peek(layerId) {
11335
+ const stack = this.undoStacks.get(layerId);
11336
+ return stack === null || stack === void 0 ? void 0 : stack[stack.length - 1];
11337
+ }
11322
11338
  /**
11323
11339
  * Redo the last undone operation on the active layer.
11324
11340
  * @returns The delta(s) that were redone, or undefined if nothing to redo.
@@ -11680,23 +11696,6 @@
11680
11696
  return Array.from(seen).sort((a, b) => a - b);
11681
11697
  }
11682
11698
 
11683
- /**
11684
- * BaseTool - Abstract base for extracted DrawToolCore tools
11685
- *
11686
- * Provides shared access to state objects via a ToolContext interface.
11687
- *
11688
- * NOTE: This is for the OLD DrawToolCore system.
11689
- * The new SegmentationManager system has its own tools in manager/tools/.
11690
- */
11691
- class BaseTool {
11692
- constructor(ctx) {
11693
- this.ctx = ctx;
11694
- }
11695
- setContext(ctx) {
11696
- this.ctx = ctx;
11697
- }
11698
- }
11699
-
11700
11699
  /**
11701
11700
  * Outline stroke width, in screen pixels.
11702
11701
  *
@@ -11831,6 +11830,370 @@
11831
11830
  }
11832
11831
  }
11833
11832
 
11833
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
11834
+ /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
11835
+ function sliceDims(dims, axis) {
11836
+ const [w, h, d] = [dims[0], dims[1], dims[2]];
11837
+ return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [h, d];
11838
+ }
11839
+ /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
11840
+ function isIdentity(m, tol = 1e-9) {
11841
+ if (!m)
11842
+ return true;
11843
+ for (let i = 0; i < 16; i++) {
11844
+ if (Math.abs(m[i] - IDENTITY[i]) > tol)
11845
+ return false;
11846
+ }
11847
+ return true;
11848
+ }
11849
+ /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
11850
+ function isDiagonal(m, tol = 1e-9) {
11851
+ for (const i of [1, 2, 4, 6, 8, 9]) {
11852
+ if (Math.abs(m[i]) > tol)
11853
+ return false;
11854
+ }
11855
+ return true;
11856
+ }
11857
+ /**
11858
+ * For each mirror index along one axis, the inclusive source index range it covers, clamped
11859
+ * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
11860
+ * source voxel covers the one nearest its centre; a larger one covers every source voxel
11861
+ * whose centre lies within it.
11862
+ */
11863
+ function coveredRanges(s, t, count, extent) {
11864
+ const lo = new Int32Array(count);
11865
+ const hi = new Int32Array(count);
11866
+ const half = Math.abs(s) / 2;
11867
+ for (let i = 0; i < count; i++) {
11868
+ const c = s * i + t;
11869
+ let a, b;
11870
+ if (Math.abs(s) <= 1) {
11871
+ a = b = Math.round(c);
11872
+ }
11873
+ else {
11874
+ a = Math.ceil(c - half - 1e-9);
11875
+ b = Math.floor(c + half - 1e-9);
11876
+ }
11877
+ lo[i] = Math.max(a, 0);
11878
+ hi[i] = Math.min(b, extent - 1);
11879
+ }
11880
+ return { lo, hi };
11881
+ }
11882
+ /**
11883
+ * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
11884
+ * the source is 0. On the same grid with the identity, it is the source's own slice.
11885
+ *
11886
+ * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
11887
+ * coarser than the source shows the first label found among every source voxel it spans, so
11888
+ * a finding thinner than the mirror's slice still appears on the slice that contains it.
11889
+ * Any other transform samples the nearest source voxel.
11890
+ */
11891
+ function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
11892
+ const sd = source.getDimensions();
11893
+ if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
11894
+ const s = source.getSliceUint8(index, axis);
11895
+ return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
11896
+ }
11897
+ const mat = m !== null && m !== void 0 ? m : IDENTITY;
11898
+ const [W, H] = sliceDims(mirrorDims, axis);
11899
+ const raw = source.getRawData();
11900
+ const nch = source.getChannels();
11901
+ const out = new Uint8Array(W * H);
11902
+ if (isDiagonal(mat)) {
11903
+ const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
11904
+ const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
11905
+ const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
11906
+ for (let v = 0; v < H; v++) {
11907
+ for (let u = 0; u < W; u++) {
11908
+ const x = axis === "x" ? index : u;
11909
+ const y = axis === "y" ? index : axis === "x" ? u : v;
11910
+ const z = axis === "z" ? index : v;
11911
+ let label = 0;
11912
+ for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
11913
+ for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
11914
+ for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
11915
+ label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
11916
+ }
11917
+ }
11918
+ }
11919
+ out[v * W + u] = label;
11920
+ }
11921
+ }
11922
+ return { data: out, width: W, height: H, stride: 1 };
11923
+ }
11924
+ for (let v = 0; v < H; v++) {
11925
+ for (let u = 0; u < W; u++) {
11926
+ // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
11927
+ const x = axis === "x" ? index : u;
11928
+ const y = axis === "y" ? index : axis === "x" ? u : v;
11929
+ const z = axis === "z" ? index : v;
11930
+ const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
11931
+ const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
11932
+ const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
11933
+ if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
11934
+ continue;
11935
+ out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
11936
+ }
11937
+ }
11938
+ return { data: out, width: W, height: H, stride: 1 };
11939
+ }
11940
+ /**
11941
+ * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
11942
+ * volumes and display state. A new transform means a new instance, so the cache never holds
11943
+ * contours from another transform.
11944
+ */
11945
+ class MaskMirror {
11946
+ constructor(self, source, matrix) {
11947
+ this.self = self;
11948
+ this.source = source;
11949
+ this.matrix = matrix;
11950
+ /** One contour entry per source layer, for the slice last painted. */
11951
+ this.cache = new Map();
11952
+ /** The source volume each cache entry was built from; a case load replaces the object. */
11953
+ this.cachedVolumes = new Map();
11954
+ }
11955
+ /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
11956
+ paint(ctx, width, height) {
11957
+ var _a, _b;
11958
+ // The source hides its own layers in sphere mode, so the mirror shows none either.
11959
+ if (this.source.gui_states.mode.sphere)
11960
+ return;
11961
+ const dims = this.self.nrrd_states.image.dimensions;
11962
+ if (!dims || dims.length !== 3)
11963
+ return;
11964
+ const axis = this.self.protectedData.axis;
11965
+ const index = this.self.nrrd_states.view.currentSliceIndex;
11966
+ const lc = this.source.gui_states.layerChannel;
11967
+ const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
11968
+ for (const layerId of this.source.nrrd_states.image.layers) {
11969
+ if (!lc.layerVisibility[layerId])
11970
+ continue;
11971
+ const volume = this.source.protectedData.maskData.volumes[layerId];
11972
+ if (!volume)
11973
+ continue;
11974
+ if (this.cachedVolumes.get(layerId) !== volume) {
11975
+ this.cache.delete(layerId);
11976
+ this.cachedVolumes.set(layerId, volume);
11977
+ }
11978
+ try {
11979
+ const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
11980
+ ctx.save();
11981
+ try {
11982
+ ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
11983
+ paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
11984
+ }
11985
+ finally {
11986
+ // A throw must not leave this layer's alpha or transform on the master canvas.
11987
+ ctx.restore();
11988
+ }
11989
+ }
11990
+ catch (_c) {
11991
+ // The source is not ready for this slice: nothing to draw for this layer.
11992
+ }
11993
+ }
11994
+ }
11995
+ }
11996
+
11997
+ /**
11998
+ * A probability heatmap drawn over a view: a colour scale, a threshold, and slice painting
11999
+ * in the layout `MaskVolume.getSliceUint8` uses, so it lines up with the masks.
12000
+ */
12001
+ /** Colour stops as [LUT index, r, g, b]; entries between stops are linear in index. */
12002
+ const STOPS = [
12003
+ [0, 0, 0, 128],
12004
+ [32, 0, 0, 255],
12005
+ [96, 0, 255, 255],
12006
+ [159, 255, 255, 0],
12007
+ [223, 255, 0, 0],
12008
+ [255, 128, 0, 0],
12009
+ ];
12010
+ function buildColormap() {
12011
+ const lut = new Uint8ClampedArray(256 * 4);
12012
+ for (let s = 0; s < STOPS.length - 1; s++) {
12013
+ const [i0, r0, g0, b0] = STOPS[s];
12014
+ const [i1, r1, g1, b1] = STOPS[s + 1];
12015
+ for (let i = i0; i <= i1; i++) {
12016
+ const f = (i - i0) / (i1 - i0);
12017
+ lut[i * 4] = Math.round(r0 + (r1 - r0) * f);
12018
+ lut[i * 4 + 1] = Math.round(g0 + (g1 - g0) * f);
12019
+ lut[i * 4 + 2] = Math.round(b0 + (b1 - b0) * f);
12020
+ lut[i * 4 + 3] = 255;
12021
+ }
12022
+ }
12023
+ return lut;
12024
+ }
12025
+ /** 256 × RGBA: probability byte → colour. */
12026
+ const HEATMAP_COLORMAP = buildColormap();
12027
+ /** The same table as one 32-bit word per entry, in the byte order of an RGBA output view. */
12028
+ const COLORMAP32 = new Uint32Array(HEATMAP_COLORMAP.buffer);
12029
+ /** The smallest byte drawn for a 0–1 threshold. */
12030
+ function heatmapThresholdByte(t) {
12031
+ return Math.min(255, Math.max(0, Math.ceil(t * 255)));
12032
+ }
12033
+ /** Whether the heatmap view is on. Older state fakes carry no `heatmap`. */
12034
+ function isHeatmapShown(state) {
12035
+ var _a;
12036
+ const gui = state.gui_states;
12037
+ return ((_a = gui === null || gui === void 0 ? void 0 : gui.heatmap) === null || _a === void 0 ? void 0 : _a.visible) === true;
12038
+ }
12039
+ const defaultMakeCanvas = (w, h) => {
12040
+ const c = document.createElement("canvas");
12041
+ c.width = w;
12042
+ c.height = h;
12043
+ return c;
12044
+ };
12045
+ /** The most raster pixels per voxel along an axis. */
12046
+ const HEATMAP_MAX_UPSAMPLE = 4;
12047
+ class HeatmapOverlay {
12048
+ constructor(volume, dims, makeCanvas = defaultMakeCanvas) {
12049
+ this.cache = null;
12050
+ /** The offscreen canvas and its pixels, kept while the raster size stays the same. */
12051
+ this.raster = null;
12052
+ this.volume = volume;
12053
+ this.dims = dims;
12054
+ this.makeCanvas = makeCanvas;
12055
+ }
12056
+ /** Raster pixels per voxel along one axis: enough for the displayed size, at most HEATMAP_MAX_UPSAMPLE. */
12057
+ static rasterFactor(displayed, voxels) {
12058
+ return Math.min(HEATMAP_MAX_UPSAMPLE, Math.max(1, Math.ceil(displayed / voxels)));
12059
+ }
12060
+ /**
12061
+ * One slice as RGBA at `fx × fy` raster pixels per voxel. The probability is interpolated
12062
+ * bilinearly between voxel centres; a pixel is drawn, in the colour of that value, where it
12063
+ * reaches `thresholdByte`. Elsewhere it is fully transparent. With `out` (exactly
12064
+ * `width × height × 4` bytes) the slice is written into it, cleared first, instead of a new array.
12065
+ * `fx` and `fy` must be integers of at least 1.
12066
+ */
12067
+ sliceRGBA(axis, index, thresholdByte, fx = 1, fy = 1, outBytes) {
12068
+ if (!Number.isInteger(fx) || !Number.isInteger(fy) || fx < 1 || fy < 1) {
12069
+ throw new Error(`heatmap factors must be integers of at least 1, got ${fx} x ${fy}`);
12070
+ }
12071
+ const [W, H] = this.dims;
12072
+ const [cols, rows] = sliceDims(this.dims, axis);
12073
+ const width = cols * fx;
12074
+ const height = rows * fy;
12075
+ if (outBytes && outBytes.length !== width * height * 4) {
12076
+ throw new Error(`heatmap output holds ${outBytes.length} bytes, the slice needs ${width * height * 4}`);
12077
+ }
12078
+ const data = outBytes !== null && outBytes !== void 0 ? outBytes : new Uint8ClampedArray(width * height * 4);
12079
+ const out = new Uint32Array(data.buffer, data.byteOffset, width * height);
12080
+ if (outBytes)
12081
+ out.fill(0);
12082
+ const vol = this.volume;
12083
+ const rowStride = axis === "z" ? W : W * H;
12084
+ const colStride = axis === "x" ? W : 1;
12085
+ const base = axis === "z" ? index * W * H : axis === "y" ? index * W : index;
12086
+ // Per raster column: the weight of its right voxel. `start[c]` is the first raster column
12087
+ // whose left voxel is c, so a voxel cell is a contiguous run.
12088
+ const wx = new Float64Array(width);
12089
+ const start = new Int32Array(cols + 1).fill(width);
12090
+ for (let px = width - 1; px >= 0; px--) {
12091
+ const u = Math.min(cols - 1, Math.max(0, (px + 0.5) / fx - 0.5));
12092
+ const c0 = Math.floor(u);
12093
+ wx[px] = u - c0;
12094
+ start[c0] = px;
12095
+ }
12096
+ // The same run table for rows: `rowStart[r]` is the first raster row whose upper voxel row is r.
12097
+ const rowStart = new Int32Array(rows + 1).fill(height);
12098
+ for (let py = height - 1; py >= 0; py--) {
12099
+ rowStart[Math.floor(Math.min(rows - 1, Math.max(0, (py + 0.5) / fy - 0.5)))] = py;
12100
+ }
12101
+ for (let r = 0; r < rows; r++) {
12102
+ const row0 = base + r * rowStride;
12103
+ const row1 = base + Math.min(r + 1, rows - 1) * rowStride;
12104
+ const pyEnd = rowStart[r + 1];
12105
+ for (let c = 0; c < cols; c++) {
12106
+ const x0 = c * colStride;
12107
+ const x1 = Math.min(c + 1, cols - 1) * colStride;
12108
+ const q00 = vol[row0 + x0];
12109
+ const q10 = vol[row0 + x1];
12110
+ const q01 = vol[row1 + x0];
12111
+ const q11 = vol[row1 + x1];
12112
+ // The interpolated value never exceeds its four voxels, so a cell of all-low voxels is empty.
12113
+ if (q00 < thresholdByte && q10 < thresholdByte && q01 < thresholdByte && q11 < thresholdByte)
12114
+ continue;
12115
+ const pxStart = start[c];
12116
+ const pxEnd = start[c + 1];
12117
+ if (q00 === q10 && q00 === q01 && q00 === q11) {
12118
+ // Equal corners interpolate to that value everywhere in the cell.
12119
+ const word = COLORMAP32[q00];
12120
+ for (let py = rowStart[r]; py < pyEnd; py++) {
12121
+ const rowBase = py * width;
12122
+ for (let px = pxStart; px < pxEnd; px++)
12123
+ out[rowBase + px] = word;
12124
+ }
12125
+ continue;
12126
+ }
12127
+ for (let py = rowStart[r]; py < pyEnd; py++) {
12128
+ const v = Math.min(rows - 1, Math.max(0, (py + 0.5) / fy - 0.5));
12129
+ const b = v - r;
12130
+ const rowBase = py * width;
12131
+ for (let px = pxStart; px < pxEnd; px++) {
12132
+ const a = wx[px];
12133
+ const p = (q00 + (q10 - q00) * a) * (1 - b) + (q01 + (q11 - q01) * a) * b;
12134
+ if (p < thresholdByte)
12135
+ continue;
12136
+ out[rowBase + px] = COLORMAP32[Math.round(p)];
12137
+ }
12138
+ }
12139
+ }
12140
+ }
12141
+ return { data, width, height };
12142
+ }
12143
+ /** Draw a slice scaled to `width × height`; the offscreen slice is reused until its key changes. */
12144
+ paint(ctx, axis, index, width, height, threshold, opacity) {
12145
+ const tb = heatmapThresholdByte(threshold);
12146
+ const [cols, rows] = sliceDims(this.dims, axis);
12147
+ const fx = HeatmapOverlay.rasterFactor(width, cols);
12148
+ const fy = HeatmapOverlay.rasterFactor(height, rows);
12149
+ const key = `${axis}:${index}:${tb}:${fx}x${fy}`;
12150
+ if (!this.cache || this.cache.key !== key) {
12151
+ const w = cols * fx;
12152
+ const h = rows * fy;
12153
+ const size = `${w}x${h}`;
12154
+ if (!this.raster || this.raster.size !== size) {
12155
+ const canvas = this.makeCanvas(w, h);
12156
+ const img = canvas.getContext("2d").createImageData(w, h);
12157
+ this.raster = { size, canvas, img };
12158
+ }
12159
+ const { canvas, img } = this.raster;
12160
+ this.sliceRGBA(axis, index, tb, fx, fy, img.data);
12161
+ canvas.getContext("2d").putImageData(img, 0, 0);
12162
+ this.cache = { key, canvas };
12163
+ }
12164
+ ctx.save();
12165
+ try {
12166
+ ctx.imageSmoothingEnabled = true;
12167
+ ctx.globalAlpha = opacity;
12168
+ if (rowsRunUp(axis)) {
12169
+ ctx.translate(0, height);
12170
+ ctx.scale(1, -1);
12171
+ }
12172
+ ctx.drawImage(this.cache.canvas, 0, 0, width, height);
12173
+ }
12174
+ finally {
12175
+ ctx.restore();
12176
+ }
12177
+ }
12178
+ }
12179
+
12180
+ /**
12181
+ * BaseTool - Abstract base for extracted DrawToolCore tools
12182
+ *
12183
+ * Provides shared access to state objects via a ToolContext interface.
12184
+ *
12185
+ * NOTE: This is for the OLD DrawToolCore system.
12186
+ * The new SegmentationManager system has its own tools in manager/tools/.
12187
+ */
12188
+ class BaseTool {
12189
+ constructor(ctx) {
12190
+ this.ctx = ctx;
12191
+ }
12192
+ setContext(ctx) {
12193
+ this.ctx = ctx;
12194
+ }
12195
+ }
12196
+
11834
12197
  /**
11835
12198
  * SphereTool - Sphere drawing and calculator sphere operations
11836
12199
  *
@@ -12025,6 +12388,9 @@
12025
12388
  * draws the sphere canvas directly to drawingCtx for proper layering.
12026
12389
  */
12027
12390
  drawSphere(mouseX, mouseY, radius) {
12391
+ // Clearing the sphere canvas also clears the master, which holds the heatmap while shown.
12392
+ if (isHeatmapShown(this.ctx))
12393
+ return;
12028
12394
  const [, ctx] = this.clearSphereCanvas();
12029
12395
  const color = this.getColorForSphereType(this.ctx.gui_states.mode.activeSphereType);
12030
12396
  drawSphereCore(ctx, mouseX, mouseY, radius, color);
@@ -12180,6 +12546,8 @@
12180
12546
  * @param radius - Sphere radius to draw
12181
12547
  */
12182
12548
  drawCalculatorSphere(radius) {
12549
+ if (isHeatmapShown(this.ctx))
12550
+ return;
12183
12551
  const [, ctx] = this.clearSphereCanvas();
12184
12552
  const nrrd = this.ctx.nrrd_states;
12185
12553
  const axis = this.ctx.protectedData.axis;
@@ -13003,7 +13371,11 @@
13003
13371
  // Skip layer mask rendering when sphere mode is active —
13004
13372
  // layer masks should remain hidden until the user exits sphere mode.
13005
13373
  if (view.switchSliceFlag) {
13006
- if (!this.ctx.gui_states.mode.sphere) {
13374
+ if (isHeatmapShown(this.ctx)) {
13375
+ // The heatmap view paints in the composite instead of any layer, whatever tool is selected.
13376
+ this.callbacks.compositeAllLayers();
13377
+ }
13378
+ else if (!this.ctx.gui_states.mode.sphere) {
13007
13379
  const axis = this.ctx.protectedData.axis;
13008
13380
  const sliceIndex = view.currentSliceIndex;
13009
13381
  // Get a single reusable buffer — shared across all layer renders
@@ -13254,6 +13626,8 @@
13254
13626
  this.setEmptyCanvasSize = () => { };
13255
13627
  /** Set while this viewer draws another viewer's masks; painted after this viewer's own layers. */
13256
13628
  this.mirror = null;
13629
+ /** The probability heatmap; painted instead of the layers while the heatmap view is on. */
13630
+ this.heatmap = null;
13257
13631
  /** Called after every composite. The owner refreshes the viewers mirroring this one. */
13258
13632
  this.onComposited = null;
13259
13633
  // Reusable ImageData buffer for zero-allocation slice rendering
@@ -13426,25 +13800,38 @@
13426
13800
  * Only draws layers whose visibility is enabled.
13427
13801
  */
13428
13802
  compositeAllLayers() {
13429
- var _a, _b, _c, _d;
13803
+ var _a, _b, _c, _d, _e;
13430
13804
  const masterCtx = this.state.protectedData.ctxes.drawingLayerMasterCtx;
13431
13805
  const width = this.state.nrrd_states.view.changedWidth;
13432
13806
  const height = this.state.nrrd_states.view.changedHeight;
13433
13807
  masterCtx.clearRect(0, 0, width, height);
13808
+ // The heatmap view replaces every layer and the mirror; with no volume set it draws nothing.
13809
+ if (isHeatmapShown(this.state)) {
13810
+ if (this.heatmap) {
13811
+ const { threshold, opacity } = this.state.gui_states.heatmap;
13812
+ const axis = this.state.protectedData.axis;
13813
+ // Just after an axis switch the index may still belong to the previous axis.
13814
+ const last = this.heatmap.dims[axis === "x" ? 0 : axis === "y" ? 1 : 2] - 1;
13815
+ const index = Math.min(last, Math.max(0, this.state.nrrd_states.view.currentSliceIndex));
13816
+ this.heatmap.paint(masterCtx, axis, index, width, height, threshold, opacity);
13817
+ }
13818
+ (_a = this.onComposited) === null || _a === void 0 ? void 0 : _a.call(this);
13819
+ return;
13820
+ }
13434
13821
  for (const layerId of this.state.nrrd_states.image.layers) {
13435
13822
  if (!this.state.gui_states.layerChannel.layerVisibility[layerId])
13436
13823
  continue;
13437
13824
  const target = this.state.protectedData.layerTargets.get(layerId);
13438
13825
  if (target) {
13439
- const layerAlpha = (_b = (_a = this.state.gui_states.layerChannel.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1.0;
13826
+ const layerAlpha = (_c = (_b = this.state.gui_states.layerChannel.layerOpacity) === null || _b === void 0 ? void 0 : _b[layerId]) !== null && _c !== void 0 ? _c : 1.0;
13440
13827
  masterCtx.save();
13441
13828
  masterCtx.globalAlpha = layerAlpha;
13442
13829
  masterCtx.drawImage(target.canvas, 0, 0, width, height);
13443
13830
  masterCtx.restore();
13444
13831
  }
13445
13832
  }
13446
- (_c = this.mirror) === null || _c === void 0 ? void 0 : _c.paint(masterCtx, width, height);
13447
- (_d = this.onComposited) === null || _d === void 0 ? void 0 : _d.call(this);
13833
+ (_d = this.mirror) === null || _d === void 0 ? void 0 : _d.paint(masterCtx, width, height);
13834
+ (_e = this.onComposited) === null || _e === void 0 ? void 0 : _e.call(this);
13448
13835
  }
13449
13836
  }
13450
13837
 
@@ -14762,9 +15149,16 @@
14762
15149
  this.ctx.protectedData.canvases.drawingCanvas.removeEventListener("mousemove", handler);
14763
15150
  }
14764
15151
  else if (e.type === "mouseover") {
14765
- this.ctx.nrrd_states.interaction.mouseOver = true;
15152
+ this.ctx.nrrd_states.interaction.mouseOver = !isHeatmapShown(this.ctx);
14766
15153
  this.ctx.protectedData.canvases.drawingCanvas.addEventListener("mousemove", handler);
14767
15154
  }
15155
+ else if (isHeatmapShown(this.ctx)) {
15156
+ // The ring would mark a brush that cannot paint while the heatmap is shown.
15157
+ this.ctx.nrrd_states.interaction.mouseOver = false;
15158
+ }
15159
+ else {
15160
+ this.ctx.nrrd_states.interaction.mouseOver = true;
15161
+ }
14768
15162
  };
14769
15163
  return handler;
14770
15164
  }
@@ -16816,6 +17210,13 @@
16816
17210
  isAnnotationSuspended() {
16817
17211
  return this.annotationSuspended;
16818
17212
  }
17213
+ /**
17214
+ * True while a mask must not be written: annotation is suspended, or the heatmap is
17215
+ * shown (it owns the master canvas, and what is on screen is not a mask).
17216
+ */
17217
+ writesBlocked() {
17218
+ return this.annotationSuspended || isHeatmapShown(this.state);
17219
+ }
16819
17220
  /**
16820
17221
  * Left/right button press on the drawing canvas.
16821
17222
  *
@@ -16833,7 +17234,7 @@
16833
17234
  if (e.button === 0) {
16834
17235
  // Every branch that can write into a mask is gated; the crosshair below is a
16835
17236
  // read-only probe and stays available, as do pan (button 2) and the wheel.
16836
- if (this.annotationSuspended && !this.eventRouter.isCrosshairEnabled()) {
17237
+ if (this.writesBlocked() && !this.eventRouter.isCrosshairEnabled()) {
16837
17238
  return;
16838
17239
  }
16839
17240
  if (this.eventRouter.getMode() === 'aiAssist') {
@@ -16875,6 +17276,12 @@
16875
17276
  return;
16876
17277
  }
16877
17278
  }
17279
+ /** Pointer move while a stroke or pan is active; a stroke can only continue where writes are allowed. */
17280
+ onCanvasPointerMove(e) {
17281
+ if (this.writesBlocked())
17282
+ return;
17283
+ this.drawingTool.onPointerMove(e);
17284
+ }
16878
17285
  /**
16879
17286
  * Left/right button release on the drawing canvas.
16880
17287
  *
@@ -16889,7 +17296,7 @@
16889
17296
  onCanvasPointerUp(e) {
16890
17297
  if (e.button === 0) {
16891
17298
  if (this.drawingTool.painting ||
16892
- (this.eventRouter.getMode() === 'draw' && !this.annotationSuspended)) {
17299
+ (this.eventRouter.getMode() === 'draw' && !this.writesBlocked())) {
16893
17300
  this.drawingTool.onPointerUp(e);
16894
17301
  this.activeWheelMode = 'zoom';
16895
17302
  }
@@ -16905,7 +17312,10 @@
16905
17312
  }
16906
17313
  else if (this.state.gui_states.mode.sphere &&
16907
17314
  !this.eventRouter.isCrosshairEnabled()) {
16908
- this.sphereTool.onSpherePointerUp();
17315
+ // A placement held when the heatmap appeared is dropped, not written; the wheel
17316
+ // is handed back either way.
17317
+ if (!isHeatmapShown(this.state))
17318
+ this.sphereTool.onSpherePointerUp();
16909
17319
  this.activeWheelMode = 'zoom';
16910
17320
  this.zoomActionAfterDrawSphere();
16911
17321
  }
@@ -17367,11 +17777,7 @@
17367
17777
  this.drawingPrameters.handleOnDrawingBrushCricleMove =
17368
17778
  this.drawingTool.createBrushTrackingHandler();
17369
17779
  // drawing move — delegated to DrawingTool
17370
- this.drawingPrameters.handleOnDrawingMouseMove = (e) => {
17371
- if (this.annotationSuspended)
17372
- return;
17373
- this.drawingTool.onPointerMove(e);
17374
- };
17780
+ this.drawingPrameters.handleOnDrawingMouseMove = (e) => this.onCanvasPointerMove(e);
17375
17781
  this.drawingPrameters.handleOnDrawingMouseDown = (e) => this.onCanvasPointerDown(e);
17376
17782
  // Route pointerdown through EventRouter
17377
17783
  this.eventRouter.setPointerDownHandler((e) => {
@@ -17409,7 +17815,15 @@
17409
17815
  else if (currentMode === 'crosshair' || this.eventRouter.isCrosshairEnabled()) {
17410
17816
  this.crosshairTool.renderCrosshair(this.state.protectedData.ctxes.drawingCtx, this.state.nrrd_states.view.changedWidth, this.state.nrrd_states.view.changedHeight);
17411
17817
  }
17818
+ // The heatmap carries its own opacity; the mask opacity must not dim it.
17819
+ const heatmapShown = isHeatmapShown(this.state);
17820
+ if (heatmapShown)
17821
+ this.state.protectedData.ctxes.drawingCtx.globalAlpha = 1;
17412
17822
  this.state.protectedData.ctxes.drawingCtx.drawImage(this.state.protectedData.canvases.drawingCanvasLayerMaster, 0, 0);
17823
+ if (heatmapShown) {
17824
+ this.state.protectedData.ctxes.drawingCtx.globalAlpha =
17825
+ this.state.gui_states.drawing.globalAlpha;
17826
+ }
17413
17827
  // Brush/eraser size ring is drawn AFTER the mask composite so it stays
17414
17828
  // visible during an active stroke (not just on hover) — e.g. while the
17415
17829
  // user resizes with Shift+wheel mid-paint. Gated on draw mode so it only
@@ -17528,15 +17942,22 @@
17528
17942
  }
17529
17943
  /****************************Sphere functions (delegated to SphereTool)****************************************************/
17530
17944
  drawCalculatorSphereOnEachViews(axis) {
17945
+ // Placing a marker clears the master canvas, which holds the heatmap while it is shown.
17946
+ if (isHeatmapShown(this.state))
17947
+ return;
17531
17948
  this.sphereTool.drawCalculatorSphereOnEachViews(axis);
17532
17949
  }
17533
17950
  configMouseSphereWheel() {
17534
17951
  return this.sphereTool.configMouseSphereWheel();
17535
17952
  }
17536
17953
  drawCalculatorSphere(radius) {
17954
+ if (isHeatmapShown(this.state))
17955
+ return;
17537
17956
  this.sphereTool.drawCalculatorSphere(radius);
17538
17957
  }
17539
17958
  drawSphere(mouseX, mouseY, radius) {
17959
+ if (isHeatmapShown(this.state))
17960
+ return;
17540
17961
  this.sphereTool.drawSphere(mouseX, mouseY, radius);
17541
17962
  }
17542
17963
  /**
@@ -17570,6 +17991,8 @@
17570
17991
  * Clear the mask on the current slice canvas for the active layer ONLY.
17571
17992
  */
17572
17993
  clearActiveSlice() {
17994
+ if (isHeatmapShown(this.state))
17995
+ return;
17573
17996
  this.state.protectedData.isDrawing = true;
17574
17997
  this.state.protectedData.canvases.originCanvas.width =
17575
17998
  this.state.protectedData.canvases.originCanvas.width;
@@ -17618,9 +18041,29 @@
17618
18041
  * Undo the last drawing operation on the active layer.
17619
18042
  */
17620
18043
  undoLastPainting() {
17621
- const entry = this.undoManager.undo();
17622
- if (!entry)
18044
+ if (isHeatmapShown(this.state))
17623
18045
  return;
18046
+ const entry = this.undoManager.undo();
18047
+ if (entry)
18048
+ this.applyUndo(entry);
18049
+ }
18050
+ /**
18051
+ * Undo `entry` on its own layer if it is still that layer's latest operation, whichever
18052
+ * layer is active; otherwise change nothing.
18053
+ *
18054
+ * @returns Whether it was undone. False when a later operation is stacked on top of it, or
18055
+ * when it has already been undone.
18056
+ */
18057
+ undoEntry(entry) {
18058
+ const layerId = entryLayer(entry);
18059
+ if (layerId === undefined || this.undoManager.peek(layerId) !== entry)
18060
+ return false;
18061
+ this.undoManager.undoOn(layerId);
18062
+ this.applyUndo(entry);
18063
+ return true;
18064
+ }
18065
+ /** Write an entry's "before" state back into its volume, repaint, and report the change. */
18066
+ applyUndo(entry) {
17624
18067
  this.state.protectedData.isDrawing = true;
17625
18068
  if (!Array.isArray(entry)) {
17626
18069
  // VolumeSnapshot: restore the pre-replacement volume in one step.
@@ -17651,6 +18094,8 @@
17651
18094
  * Redo the last undone operation on the active layer.
17652
18095
  */
17653
18096
  redoLastPainting() {
18097
+ if (isHeatmapShown(this.state))
18098
+ return;
17654
18099
  const entry = this.undoManager.redo();
17655
18100
  if (!entry)
17656
18101
  return;
@@ -17911,11 +18356,12 @@
17911
18356
  /**
17912
18357
  * GuiState — Grouped state management for GUI configuration.
17913
18358
  *
17914
- * Replaces the flat IGUIStates object with 4 semantic sub-groups:
18359
+ * Replaces the flat IGUIStates object with 5 semantic sub-groups:
17915
18360
  * - mode: Tool mode flags (pencil/eraser/sphere)
17916
18361
  * - drawing: Brush/pencil appearance and behavior
17917
18362
  * - viewConfig: UI layout and interaction parameters
17918
18363
  * - layerChannel: Active layer, channel, and visibility
18364
+ * - heatmap: Probability heatmap view: shown, threshold, opacity
17919
18365
  */
17920
18366
  class GuiState {
17921
18367
  constructor(options) {
@@ -17958,6 +18404,7 @@
17958
18404
  ])),
17959
18405
  layerOpacity: Object.fromEntries(layers.map((l) => [l, 1.0])),
17960
18406
  };
18407
+ this.heatmap = { visible: false, threshold: 0.1, opacity: 0.5 };
17961
18408
  }
17962
18409
  }
17963
18410
 
@@ -18704,6 +19151,11 @@
18704
19151
  * Replaces the old reloadMaskToLayer approach
18705
19152
  */
18706
19153
  reloadMasksFromVolume() {
19154
+ // The heatmap view paints in the composite instead of any layer, whatever tool is selected.
19155
+ if (isHeatmapShown(this.ctx)) {
19156
+ this.callbacks.compositeAllLayers();
19157
+ return;
19158
+ }
18707
19159
  // When sphere mode is active, do NOT redraw layer masks.
18708
19160
  // Layer mask data should remain hidden until the user exits sphere mode.
18709
19161
  if (this.ctx.gui_states.mode.sphere) {
@@ -18967,170 +19419,6 @@
18967
19419
  }
18968
19420
  }
18969
19421
 
18970
- const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
18971
- /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
18972
- function sliceDims(dims, axis) {
18973
- const [w, h, d] = [dims[0], dims[1], dims[2]];
18974
- return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [h, d];
18975
- }
18976
- /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
18977
- function isIdentity(m, tol = 1e-9) {
18978
- if (!m)
18979
- return true;
18980
- for (let i = 0; i < 16; i++) {
18981
- if (Math.abs(m[i] - IDENTITY[i]) > tol)
18982
- return false;
18983
- }
18984
- return true;
18985
- }
18986
- /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
18987
- function isDiagonal(m, tol = 1e-9) {
18988
- for (const i of [1, 2, 4, 6, 8, 9]) {
18989
- if (Math.abs(m[i]) > tol)
18990
- return false;
18991
- }
18992
- return true;
18993
- }
18994
- /**
18995
- * For each mirror index along one axis, the inclusive source index range it covers, clamped
18996
- * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
18997
- * source voxel covers the one nearest its centre; a larger one covers every source voxel
18998
- * whose centre lies within it.
18999
- */
19000
- function coveredRanges(s, t, count, extent) {
19001
- const lo = new Int32Array(count);
19002
- const hi = new Int32Array(count);
19003
- const half = Math.abs(s) / 2;
19004
- for (let i = 0; i < count; i++) {
19005
- const c = s * i + t;
19006
- let a, b;
19007
- if (Math.abs(s) <= 1) {
19008
- a = b = Math.round(c);
19009
- }
19010
- else {
19011
- a = Math.ceil(c - half - 1e-9);
19012
- b = Math.floor(c + half - 1e-9);
19013
- }
19014
- lo[i] = Math.max(a, 0);
19015
- hi[i] = Math.min(b, extent - 1);
19016
- }
19017
- return { lo, hi };
19018
- }
19019
- /**
19020
- * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
19021
- * the source is 0. On the same grid with the identity, it is the source's own slice.
19022
- *
19023
- * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
19024
- * coarser than the source shows the first label found among every source voxel it spans, so
19025
- * a finding thinner than the mirror's slice still appears on the slice that contains it.
19026
- * Any other transform samples the nearest source voxel.
19027
- */
19028
- function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
19029
- const sd = source.getDimensions();
19030
- if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
19031
- const s = source.getSliceUint8(index, axis);
19032
- return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
19033
- }
19034
- const mat = m !== null && m !== void 0 ? m : IDENTITY;
19035
- const [W, H] = sliceDims(mirrorDims, axis);
19036
- const raw = source.getRawData();
19037
- const nch = source.getChannels();
19038
- const out = new Uint8Array(W * H);
19039
- if (isDiagonal(mat)) {
19040
- const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
19041
- const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
19042
- const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
19043
- for (let v = 0; v < H; v++) {
19044
- for (let u = 0; u < W; u++) {
19045
- const x = axis === "x" ? index : u;
19046
- const y = axis === "y" ? index : axis === "x" ? u : v;
19047
- const z = axis === "z" ? index : v;
19048
- let label = 0;
19049
- for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
19050
- for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
19051
- for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
19052
- label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
19053
- }
19054
- }
19055
- }
19056
- out[v * W + u] = label;
19057
- }
19058
- }
19059
- return { data: out, width: W, height: H, stride: 1 };
19060
- }
19061
- for (let v = 0; v < H; v++) {
19062
- for (let u = 0; u < W; u++) {
19063
- // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
19064
- const x = axis === "x" ? index : u;
19065
- const y = axis === "y" ? index : axis === "x" ? u : v;
19066
- const z = axis === "z" ? index : v;
19067
- const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
19068
- const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
19069
- const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
19070
- if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
19071
- continue;
19072
- out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
19073
- }
19074
- }
19075
- return { data: out, width: W, height: H, stride: 1 };
19076
- }
19077
- /**
19078
- * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
19079
- * volumes and display state. A new transform means a new instance, so the cache never holds
19080
- * contours from another transform.
19081
- */
19082
- class MaskMirror {
19083
- constructor(self, source, matrix) {
19084
- this.self = self;
19085
- this.source = source;
19086
- this.matrix = matrix;
19087
- /** One contour entry per source layer, for the slice last painted. */
19088
- this.cache = new Map();
19089
- /** The source volume each cache entry was built from; a case load replaces the object. */
19090
- this.cachedVolumes = new Map();
19091
- }
19092
- /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
19093
- paint(ctx, width, height) {
19094
- var _a, _b;
19095
- // The source hides its own layers in sphere mode, so the mirror shows none either.
19096
- if (this.source.gui_states.mode.sphere)
19097
- return;
19098
- const dims = this.self.nrrd_states.image.dimensions;
19099
- if (!dims || dims.length !== 3)
19100
- return;
19101
- const axis = this.self.protectedData.axis;
19102
- const index = this.self.nrrd_states.view.currentSliceIndex;
19103
- const lc = this.source.gui_states.layerChannel;
19104
- const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
19105
- for (const layerId of this.source.nrrd_states.image.layers) {
19106
- if (!lc.layerVisibility[layerId])
19107
- continue;
19108
- const volume = this.source.protectedData.maskData.volumes[layerId];
19109
- if (!volume)
19110
- continue;
19111
- if (this.cachedVolumes.get(layerId) !== volume) {
19112
- this.cache.delete(layerId);
19113
- this.cachedVolumes.set(layerId, volume);
19114
- }
19115
- try {
19116
- const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
19117
- ctx.save();
19118
- try {
19119
- ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
19120
- paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
19121
- }
19122
- finally {
19123
- // A throw must not leave this layer's alpha or transform on the master canvas.
19124
- ctx.restore();
19125
- }
19126
- }
19127
- catch (_c) {
19128
- // The source is not ready for this slice: nothing to draw for this layer.
19129
- }
19130
- }
19131
- }
19132
- }
19133
-
19134
19422
  /**
19135
19423
  * NrrdTools.setMasksFromNIfTI forwards its `Map<string, Uint8Array>` argument
19136
19424
  * straight through to here with no second channel for metadata, so a caller that
@@ -19797,6 +20085,10 @@
19797
20085
  }
19798
20086
  executeAction(action, opts) {
19799
20087
  var _a;
20088
+ // Every other action writes a mask, and nothing may while the heatmap is shown.
20089
+ const readOnly = action === "resetZoom" || action === "downloadCurrentMask";
20090
+ if (!readOnly && isHeatmapShown(this.state))
20091
+ return;
19800
20092
  switch (action) {
19801
20093
  case "undo":
19802
20094
  this.undo();
@@ -19900,6 +20192,7 @@
19900
20192
  *
19901
20193
  * @param layerId Layer whose mask to edit.
19902
20194
  * @param channel Label to erase, 1-255.
20195
+ * @returns The clear, for `undoChannelClear`; null when the channel held nothing.
19903
20196
  * @throws {Error} If `layerId` names no layer. Deliberately NOT routed through
19904
20197
  * `getVolumeForLayer`, which warns and falls back to the first layer — for a
19905
20198
  * destructive call that would quietly erase a different layer's annotation.
@@ -19927,7 +20220,7 @@
19927
20220
  });
19928
20221
  }
19929
20222
  if (deltas.length === 0)
19930
- return; // nothing drawn on this channel
20223
+ return null; // nothing drawn on this channel
19931
20224
  volume.clearChannel(channel);
19932
20225
  for (const delta of deltas) {
19933
20226
  delta.newSlice = volume.getSliceUint8(delta.sliceIndex, "z").data.slice();
@@ -19938,6 +20231,28 @@
19938
20231
  this.state.annotationCallbacks.onMaskChanged(data, layerId, channel, delta.sliceIndex, "z", width, height, false);
19939
20232
  }
19940
20233
  this.reloadMasksFromVolume();
20234
+ return { layerId, channel, entry: deltas };
20235
+ }
20236
+ /**
20237
+ * Undo one `clearChannel`, on its own layer, whatever layer is active now.
20238
+ *
20239
+ * `undo()` acts on the active layer's latest operation, and by the time a caller offers to
20240
+ * reverse a clear the active layer may have changed. This names the clear instead, and
20241
+ * reverses it only while it is still the latest operation on its layer: a later edit there is
20242
+ * newer work, never undone in passing -- `undo()` steps back through it in order.
20243
+ *
20244
+ * Reported through `onMaskChanged` with the channels it restored, exactly as `undo()` reports.
20245
+ *
20246
+ * @returns Whether the clear was undone. False when a later operation is stacked on it, or
20247
+ * it has already been undone.
20248
+ */
20249
+ undoChannelClear(clear) {
20250
+ if (!this.drawCore.undoEntry(clear.entry))
20251
+ return false;
20252
+ // `undo()` repaints only the slice on screen when it lies on the clear's axis; a clear
20253
+ // spans every slice of the label, so repaint them all, as the clear itself does.
20254
+ this.reloadMasksFromVolume();
20255
+ return true;
19941
20256
  }
19942
20257
  // ═══════════════════════════════════════════════════════════════════════════
19943
20258
  // 4. Public API — Keyboard & History
@@ -20420,6 +20735,54 @@
20420
20735
  this.reloadMasksFromVolume();
20421
20736
  }
20422
20737
  getMaskRenderMode() { return this.state.gui_states.drawing.maskRenderMode; }
20738
+ /**
20739
+ * Canonical uint8 probabilities (p × 255), x fastest, in the loaded image's dimensions.
20740
+ * Throws when `dims` differ from the image's or do not match the volume's length. null clears.
20741
+ */
20742
+ setHeatmap(volume, dims) {
20743
+ if (volume === null) {
20744
+ this.drawCore.renderer.heatmap = null;
20745
+ }
20746
+ else {
20747
+ const image = this.getCurrentImageDimension();
20748
+ if (!dims || image.length !== 3 || dims.length !== 3 || dims.some((n, i) => n !== image[i])) {
20749
+ throw new Error(`setHeatmap: heatmap dimensions ${dims !== null && dims !== void 0 ? dims : "(none)"} differ from the image's ${image}`);
20750
+ }
20751
+ const [w, h, d] = dims;
20752
+ if (volume.length !== w * h * d) {
20753
+ throw new Error(`setHeatmap: ${volume.length} heatmap voxels for dimensions ${dims}`);
20754
+ }
20755
+ this.drawCore.renderer.heatmap = new HeatmapOverlay(volume, [w, h, d]);
20756
+ }
20757
+ if (this.isHeatmapVisible())
20758
+ this.drawCore.renderer.compositeAllLayers();
20759
+ }
20760
+ /** Show the heatmap instead of every mask layer, or bring the layers back. */
20761
+ setHeatmapVisible(visible) {
20762
+ this.state.gui_states.heatmap.visible = visible;
20763
+ if (visible) {
20764
+ this.drawCore.renderer.compositeAllLayers();
20765
+ return;
20766
+ }
20767
+ // Clear first: the reload returns without compositing in sphere mode and in a viewer with
20768
+ // no layers and no mirror, and would leave the heatmap drawn. Sphere mode keeps nothing on
20769
+ // the master (its overlay has its own canvas), so this is what that mode shows anyway.
20770
+ this.state.protectedData.ctxes.drawingLayerMasterCtx.clearRect(0, 0, this.state.nrrd_states.view.changedWidth, this.state.nrrd_states.view.changedHeight);
20771
+ this.reloadMasksFromVolume();
20772
+ }
20773
+ isHeatmapVisible() { return this.state.gui_states.heatmap.visible; }
20774
+ /** Probabilities below `t` (clamped to 0–1) are not drawn. */
20775
+ setHeatmapThreshold(t) {
20776
+ this.state.gui_states.heatmap.threshold = Math.min(1, Math.max(0, t));
20777
+ if (this.isHeatmapVisible())
20778
+ this.drawCore.renderer.compositeAllLayers();
20779
+ }
20780
+ /** Clamped to 0–1. */
20781
+ setHeatmapOpacity(a) {
20782
+ this.state.gui_states.heatmap.opacity = Math.min(1, Math.max(0, a));
20783
+ if (this.isHeatmapVisible())
20784
+ this.drawCore.renderer.compositeAllLayers();
20785
+ }
20423
20786
  // ═══════════════════════════════════════════════════════════════════════════
20424
20787
  // 8. Delegated — SliceRenderPipeline
20425
20788
  // ═══════════════════════════════════════════════════════════════════════════
@@ -20446,6 +20809,9 @@
20446
20809
  // 10. Sphere Orchestration
20447
20810
  // ═══════════════════════════════════════════════════════════════════════════
20448
20811
  setCalculateDistanceSphere(x, y, sliceIndex, cal_position) {
20812
+ // A marker repaints the master canvas, which holds the heatmap while it is shown.
20813
+ if (isHeatmapShown(this.state))
20814
+ return;
20449
20815
  this.state.nrrd_states.sphere.sphereRadius = 5;
20450
20816
  const steps = sliceIndex - this.state.nrrd_states.view.currentSliceIndex;
20451
20817
  this.setSliceMoving(steps * this.state.protectedData.displaySlices.length);
@@ -20694,6 +21060,8 @@
20694
21060
  // 11. Clear / Reset
20695
21061
  // ═══════════════════════════════════════════════════════════════════════════
20696
21062
  clearActiveLayer() {
21063
+ if (isHeatmapShown(this.state))
21064
+ return;
20697
21065
  if (this.state.nrrd_states.image.dimensions.length === 3) {
20698
21066
  const [w, h, d] = this.state.nrrd_states.image.dimensions;
20699
21067
  const activeLayer = this.state.gui_states.layerChannel.layer;
@@ -22143,15 +22511,15 @@
22143
22511
  }
22144
22512
 
22145
22513
  // import * as kiwrious from "copper3d_plugin_heart_k";
22146
- // "v4.1.3" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
22514
+ // "v4.2.0" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
22147
22515
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
22148
22516
  // referencing it throws a ReferenceError — guard it so local loading still works.
22149
22517
  let _revision = "unknown";
22150
22518
  try {
22151
- _revision = "v4.1.3";
22519
+ _revision = "v4.2.0";
22152
22520
  }
22153
22521
  catch (_a) {
22154
- /* "v4.1.3" not injected (local source build) */
22522
+ /* "v4.2.0" not injected (local source build) */
22155
22523
  }
22156
22524
  const REVISION = _revision;
22157
22525
  // "186" is three's revision at build time, injected the same way.
@@ -22181,6 +22549,7 @@
22181
22549
  exports.DEFAULT_AXES = DEFAULT_AXES;
22182
22550
  exports.DEFAULT_TARGET_GREY = DEFAULT_TARGET_GREY;
22183
22551
  exports.GaussianSmoother = GaussianSmoother;
22552
+ exports.HEATMAP_COLORMAP = HEATMAP_COLORMAP;
22184
22553
  exports.MAX_ENGINE_CHANNEL = MAX_ENGINE_CHANNEL;
22185
22554
  exports.MeshNodeTool = MeshNodeTool;
22186
22555
  exports.NrrdTools = NrrdTools;