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
@@ -11231,6 +11231,11 @@ class MaskVolume {
11231
11231
  * - maxStackSize: 50 entries per layer.
11232
11232
  * - Undo/redo operations also trigger backend sync via getMask callback.
11233
11233
  */
11234
+ /** The layer an entry belongs to. */
11235
+ function entryLayer(entry) {
11236
+ var _a;
11237
+ return Array.isArray(entry) ? (_a = entry[0]) === null || _a === void 0 ? void 0 : _a.layerId : entry.layerId;
11238
+ }
11234
11239
  const MAX_STACK_SIZE = 50;
11235
11240
  class UndoManager {
11236
11241
  constructor() {
@@ -11303,13 +11308,24 @@ class UndoManager {
11303
11308
  * @returns The delta(s) that were undone, or undefined if nothing to undo.
11304
11309
  */
11305
11310
  undo() {
11306
- const stack = this.stackFor(this.undoStacks, this.activeLayer);
11307
- const entry = stack.pop();
11311
+ return this.undoOn(this.activeLayer);
11312
+ }
11313
+ /**
11314
+ * Undo the last operation on `layerId`, whichever layer is active. The entry moves to that
11315
+ * layer's redo stack, exactly as `undo` does for the active one.
11316
+ */
11317
+ undoOn(layerId) {
11318
+ const entry = this.stackFor(this.undoStacks, layerId).pop();
11308
11319
  if (entry) {
11309
- this.stackFor(this.redoStacks, this.activeLayer).push(entry);
11320
+ this.stackFor(this.redoStacks, layerId).push(entry);
11310
11321
  }
11311
11322
  return entry;
11312
11323
  }
11324
+ /** The entry an undo on `layerId` would take next, left in place. */
11325
+ peek(layerId) {
11326
+ const stack = this.undoStacks.get(layerId);
11327
+ return stack === null || stack === void 0 ? void 0 : stack[stack.length - 1];
11328
+ }
11313
11329
  /**
11314
11330
  * Redo the last undone operation on the active layer.
11315
11331
  * @returns The delta(s) that were redone, or undefined if nothing to redo.
@@ -11671,23 +11687,6 @@ function findLabelsInSlice(labels, width, height, stride = 1, channelOffset = 0,
11671
11687
  return Array.from(seen).sort((a, b) => a - b);
11672
11688
  }
11673
11689
 
11674
- /**
11675
- * BaseTool - Abstract base for extracted DrawToolCore tools
11676
- *
11677
- * Provides shared access to state objects via a ToolContext interface.
11678
- *
11679
- * NOTE: This is for the OLD DrawToolCore system.
11680
- * The new SegmentationManager system has its own tools in manager/tools/.
11681
- */
11682
- class BaseTool {
11683
- constructor(ctx) {
11684
- this.ctx = ctx;
11685
- }
11686
- setContext(ctx) {
11687
- this.ctx = ctx;
11688
- }
11689
- }
11690
-
11691
11690
  /**
11692
11691
  * Outline stroke width, in screen pixels.
11693
11692
  *
@@ -11822,6 +11821,370 @@ function drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, c
11822
11821
  }
11823
11822
  }
11824
11823
 
11824
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
11825
+ /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
11826
+ function sliceDims(dims, axis) {
11827
+ const [w, h, d] = [dims[0], dims[1], dims[2]];
11828
+ return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [h, d];
11829
+ }
11830
+ /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
11831
+ function isIdentity(m, tol = 1e-9) {
11832
+ if (!m)
11833
+ return true;
11834
+ for (let i = 0; i < 16; i++) {
11835
+ if (Math.abs(m[i] - IDENTITY[i]) > tol)
11836
+ return false;
11837
+ }
11838
+ return true;
11839
+ }
11840
+ /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
11841
+ function isDiagonal(m, tol = 1e-9) {
11842
+ for (const i of [1, 2, 4, 6, 8, 9]) {
11843
+ if (Math.abs(m[i]) > tol)
11844
+ return false;
11845
+ }
11846
+ return true;
11847
+ }
11848
+ /**
11849
+ * For each mirror index along one axis, the inclusive source index range it covers, clamped
11850
+ * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
11851
+ * source voxel covers the one nearest its centre; a larger one covers every source voxel
11852
+ * whose centre lies within it.
11853
+ */
11854
+ function coveredRanges(s, t, count, extent) {
11855
+ const lo = new Int32Array(count);
11856
+ const hi = new Int32Array(count);
11857
+ const half = Math.abs(s) / 2;
11858
+ for (let i = 0; i < count; i++) {
11859
+ const c = s * i + t;
11860
+ let a, b;
11861
+ if (Math.abs(s) <= 1) {
11862
+ a = b = Math.round(c);
11863
+ }
11864
+ else {
11865
+ a = Math.ceil(c - half - 1e-9);
11866
+ b = Math.floor(c + half - 1e-9);
11867
+ }
11868
+ lo[i] = Math.max(a, 0);
11869
+ hi[i] = Math.min(b, extent - 1);
11870
+ }
11871
+ return { lo, hi };
11872
+ }
11873
+ /**
11874
+ * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
11875
+ * the source is 0. On the same grid with the identity, it is the source's own slice.
11876
+ *
11877
+ * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
11878
+ * coarser than the source shows the first label found among every source voxel it spans, so
11879
+ * a finding thinner than the mirror's slice still appears on the slice that contains it.
11880
+ * Any other transform samples the nearest source voxel.
11881
+ */
11882
+ function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
11883
+ const sd = source.getDimensions();
11884
+ if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
11885
+ const s = source.getSliceUint8(index, axis);
11886
+ return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
11887
+ }
11888
+ const mat = m !== null && m !== void 0 ? m : IDENTITY;
11889
+ const [W, H] = sliceDims(mirrorDims, axis);
11890
+ const raw = source.getRawData();
11891
+ const nch = source.getChannels();
11892
+ const out = new Uint8Array(W * H);
11893
+ if (isDiagonal(mat)) {
11894
+ const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
11895
+ const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
11896
+ const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
11897
+ for (let v = 0; v < H; v++) {
11898
+ for (let u = 0; u < W; u++) {
11899
+ const x = axis === "x" ? index : u;
11900
+ const y = axis === "y" ? index : axis === "x" ? u : v;
11901
+ const z = axis === "z" ? index : v;
11902
+ let label = 0;
11903
+ for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
11904
+ for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
11905
+ for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
11906
+ label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
11907
+ }
11908
+ }
11909
+ }
11910
+ out[v * W + u] = label;
11911
+ }
11912
+ }
11913
+ return { data: out, width: W, height: H, stride: 1 };
11914
+ }
11915
+ for (let v = 0; v < H; v++) {
11916
+ for (let u = 0; u < W; u++) {
11917
+ // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
11918
+ const x = axis === "x" ? index : u;
11919
+ const y = axis === "y" ? index : axis === "x" ? u : v;
11920
+ const z = axis === "z" ? index : v;
11921
+ const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
11922
+ const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
11923
+ const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
11924
+ if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
11925
+ continue;
11926
+ out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
11927
+ }
11928
+ }
11929
+ return { data: out, width: W, height: H, stride: 1 };
11930
+ }
11931
+ /**
11932
+ * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
11933
+ * volumes and display state. A new transform means a new instance, so the cache never holds
11934
+ * contours from another transform.
11935
+ */
11936
+ class MaskMirror {
11937
+ constructor(self, source, matrix) {
11938
+ this.self = self;
11939
+ this.source = source;
11940
+ this.matrix = matrix;
11941
+ /** One contour entry per source layer, for the slice last painted. */
11942
+ this.cache = new Map();
11943
+ /** The source volume each cache entry was built from; a case load replaces the object. */
11944
+ this.cachedVolumes = new Map();
11945
+ }
11946
+ /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
11947
+ paint(ctx, width, height) {
11948
+ var _a, _b;
11949
+ // The source hides its own layers in sphere mode, so the mirror shows none either.
11950
+ if (this.source.gui_states.mode.sphere)
11951
+ return;
11952
+ const dims = this.self.nrrd_states.image.dimensions;
11953
+ if (!dims || dims.length !== 3)
11954
+ return;
11955
+ const axis = this.self.protectedData.axis;
11956
+ const index = this.self.nrrd_states.view.currentSliceIndex;
11957
+ const lc = this.source.gui_states.layerChannel;
11958
+ const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
11959
+ for (const layerId of this.source.nrrd_states.image.layers) {
11960
+ if (!lc.layerVisibility[layerId])
11961
+ continue;
11962
+ const volume = this.source.protectedData.maskData.volumes[layerId];
11963
+ if (!volume)
11964
+ continue;
11965
+ if (this.cachedVolumes.get(layerId) !== volume) {
11966
+ this.cache.delete(layerId);
11967
+ this.cachedVolumes.set(layerId, volume);
11968
+ }
11969
+ try {
11970
+ const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
11971
+ ctx.save();
11972
+ try {
11973
+ ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
11974
+ paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
11975
+ }
11976
+ finally {
11977
+ // A throw must not leave this layer's alpha or transform on the master canvas.
11978
+ ctx.restore();
11979
+ }
11980
+ }
11981
+ catch (_c) {
11982
+ // The source is not ready for this slice: nothing to draw for this layer.
11983
+ }
11984
+ }
11985
+ }
11986
+ }
11987
+
11988
+ /**
11989
+ * A probability heatmap drawn over a view: a colour scale, a threshold, and slice painting
11990
+ * in the layout `MaskVolume.getSliceUint8` uses, so it lines up with the masks.
11991
+ */
11992
+ /** Colour stops as [LUT index, r, g, b]; entries between stops are linear in index. */
11993
+ const STOPS = [
11994
+ [0, 0, 0, 128],
11995
+ [32, 0, 0, 255],
11996
+ [96, 0, 255, 255],
11997
+ [159, 255, 255, 0],
11998
+ [223, 255, 0, 0],
11999
+ [255, 128, 0, 0],
12000
+ ];
12001
+ function buildColormap() {
12002
+ const lut = new Uint8ClampedArray(256 * 4);
12003
+ for (let s = 0; s < STOPS.length - 1; s++) {
12004
+ const [i0, r0, g0, b0] = STOPS[s];
12005
+ const [i1, r1, g1, b1] = STOPS[s + 1];
12006
+ for (let i = i0; i <= i1; i++) {
12007
+ const f = (i - i0) / (i1 - i0);
12008
+ lut[i * 4] = Math.round(r0 + (r1 - r0) * f);
12009
+ lut[i * 4 + 1] = Math.round(g0 + (g1 - g0) * f);
12010
+ lut[i * 4 + 2] = Math.round(b0 + (b1 - b0) * f);
12011
+ lut[i * 4 + 3] = 255;
12012
+ }
12013
+ }
12014
+ return lut;
12015
+ }
12016
+ /** 256 × RGBA: probability byte → colour. */
12017
+ const HEATMAP_COLORMAP = buildColormap();
12018
+ /** The same table as one 32-bit word per entry, in the byte order of an RGBA output view. */
12019
+ const COLORMAP32 = new Uint32Array(HEATMAP_COLORMAP.buffer);
12020
+ /** The smallest byte drawn for a 0–1 threshold. */
12021
+ function heatmapThresholdByte(t) {
12022
+ return Math.min(255, Math.max(0, Math.ceil(t * 255)));
12023
+ }
12024
+ /** Whether the heatmap view is on. Older state fakes carry no `heatmap`. */
12025
+ function isHeatmapShown(state) {
12026
+ var _a;
12027
+ const gui = state.gui_states;
12028
+ return ((_a = gui === null || gui === void 0 ? void 0 : gui.heatmap) === null || _a === void 0 ? void 0 : _a.visible) === true;
12029
+ }
12030
+ const defaultMakeCanvas = (w, h) => {
12031
+ const c = document.createElement("canvas");
12032
+ c.width = w;
12033
+ c.height = h;
12034
+ return c;
12035
+ };
12036
+ /** The most raster pixels per voxel along an axis. */
12037
+ const HEATMAP_MAX_UPSAMPLE = 4;
12038
+ class HeatmapOverlay {
12039
+ constructor(volume, dims, makeCanvas = defaultMakeCanvas) {
12040
+ this.cache = null;
12041
+ /** The offscreen canvas and its pixels, kept while the raster size stays the same. */
12042
+ this.raster = null;
12043
+ this.volume = volume;
12044
+ this.dims = dims;
12045
+ this.makeCanvas = makeCanvas;
12046
+ }
12047
+ /** Raster pixels per voxel along one axis: enough for the displayed size, at most HEATMAP_MAX_UPSAMPLE. */
12048
+ static rasterFactor(displayed, voxels) {
12049
+ return Math.min(HEATMAP_MAX_UPSAMPLE, Math.max(1, Math.ceil(displayed / voxels)));
12050
+ }
12051
+ /**
12052
+ * One slice as RGBA at `fx × fy` raster pixels per voxel. The probability is interpolated
12053
+ * bilinearly between voxel centres; a pixel is drawn, in the colour of that value, where it
12054
+ * reaches `thresholdByte`. Elsewhere it is fully transparent. With `out` (exactly
12055
+ * `width × height × 4` bytes) the slice is written into it, cleared first, instead of a new array.
12056
+ * `fx` and `fy` must be integers of at least 1.
12057
+ */
12058
+ sliceRGBA(axis, index, thresholdByte, fx = 1, fy = 1, outBytes) {
12059
+ if (!Number.isInteger(fx) || !Number.isInteger(fy) || fx < 1 || fy < 1) {
12060
+ throw new Error(`heatmap factors must be integers of at least 1, got ${fx} x ${fy}`);
12061
+ }
12062
+ const [W, H] = this.dims;
12063
+ const [cols, rows] = sliceDims(this.dims, axis);
12064
+ const width = cols * fx;
12065
+ const height = rows * fy;
12066
+ if (outBytes && outBytes.length !== width * height * 4) {
12067
+ throw new Error(`heatmap output holds ${outBytes.length} bytes, the slice needs ${width * height * 4}`);
12068
+ }
12069
+ const data = outBytes !== null && outBytes !== void 0 ? outBytes : new Uint8ClampedArray(width * height * 4);
12070
+ const out = new Uint32Array(data.buffer, data.byteOffset, width * height);
12071
+ if (outBytes)
12072
+ out.fill(0);
12073
+ const vol = this.volume;
12074
+ const rowStride = axis === "z" ? W : W * H;
12075
+ const colStride = axis === "x" ? W : 1;
12076
+ const base = axis === "z" ? index * W * H : axis === "y" ? index * W : index;
12077
+ // Per raster column: the weight of its right voxel. `start[c]` is the first raster column
12078
+ // whose left voxel is c, so a voxel cell is a contiguous run.
12079
+ const wx = new Float64Array(width);
12080
+ const start = new Int32Array(cols + 1).fill(width);
12081
+ for (let px = width - 1; px >= 0; px--) {
12082
+ const u = Math.min(cols - 1, Math.max(0, (px + 0.5) / fx - 0.5));
12083
+ const c0 = Math.floor(u);
12084
+ wx[px] = u - c0;
12085
+ start[c0] = px;
12086
+ }
12087
+ // The same run table for rows: `rowStart[r]` is the first raster row whose upper voxel row is r.
12088
+ const rowStart = new Int32Array(rows + 1).fill(height);
12089
+ for (let py = height - 1; py >= 0; py--) {
12090
+ rowStart[Math.floor(Math.min(rows - 1, Math.max(0, (py + 0.5) / fy - 0.5)))] = py;
12091
+ }
12092
+ for (let r = 0; r < rows; r++) {
12093
+ const row0 = base + r * rowStride;
12094
+ const row1 = base + Math.min(r + 1, rows - 1) * rowStride;
12095
+ const pyEnd = rowStart[r + 1];
12096
+ for (let c = 0; c < cols; c++) {
12097
+ const x0 = c * colStride;
12098
+ const x1 = Math.min(c + 1, cols - 1) * colStride;
12099
+ const q00 = vol[row0 + x0];
12100
+ const q10 = vol[row0 + x1];
12101
+ const q01 = vol[row1 + x0];
12102
+ const q11 = vol[row1 + x1];
12103
+ // The interpolated value never exceeds its four voxels, so a cell of all-low voxels is empty.
12104
+ if (q00 < thresholdByte && q10 < thresholdByte && q01 < thresholdByte && q11 < thresholdByte)
12105
+ continue;
12106
+ const pxStart = start[c];
12107
+ const pxEnd = start[c + 1];
12108
+ if (q00 === q10 && q00 === q01 && q00 === q11) {
12109
+ // Equal corners interpolate to that value everywhere in the cell.
12110
+ const word = COLORMAP32[q00];
12111
+ for (let py = rowStart[r]; py < pyEnd; py++) {
12112
+ const rowBase = py * width;
12113
+ for (let px = pxStart; px < pxEnd; px++)
12114
+ out[rowBase + px] = word;
12115
+ }
12116
+ continue;
12117
+ }
12118
+ for (let py = rowStart[r]; py < pyEnd; py++) {
12119
+ const v = Math.min(rows - 1, Math.max(0, (py + 0.5) / fy - 0.5));
12120
+ const b = v - r;
12121
+ const rowBase = py * width;
12122
+ for (let px = pxStart; px < pxEnd; px++) {
12123
+ const a = wx[px];
12124
+ const p = (q00 + (q10 - q00) * a) * (1 - b) + (q01 + (q11 - q01) * a) * b;
12125
+ if (p < thresholdByte)
12126
+ continue;
12127
+ out[rowBase + px] = COLORMAP32[Math.round(p)];
12128
+ }
12129
+ }
12130
+ }
12131
+ }
12132
+ return { data, width, height };
12133
+ }
12134
+ /** Draw a slice scaled to `width × height`; the offscreen slice is reused until its key changes. */
12135
+ paint(ctx, axis, index, width, height, threshold, opacity) {
12136
+ const tb = heatmapThresholdByte(threshold);
12137
+ const [cols, rows] = sliceDims(this.dims, axis);
12138
+ const fx = HeatmapOverlay.rasterFactor(width, cols);
12139
+ const fy = HeatmapOverlay.rasterFactor(height, rows);
12140
+ const key = `${axis}:${index}:${tb}:${fx}x${fy}`;
12141
+ if (!this.cache || this.cache.key !== key) {
12142
+ const w = cols * fx;
12143
+ const h = rows * fy;
12144
+ const size = `${w}x${h}`;
12145
+ if (!this.raster || this.raster.size !== size) {
12146
+ const canvas = this.makeCanvas(w, h);
12147
+ const img = canvas.getContext("2d").createImageData(w, h);
12148
+ this.raster = { size, canvas, img };
12149
+ }
12150
+ const { canvas, img } = this.raster;
12151
+ this.sliceRGBA(axis, index, tb, fx, fy, img.data);
12152
+ canvas.getContext("2d").putImageData(img, 0, 0);
12153
+ this.cache = { key, canvas };
12154
+ }
12155
+ ctx.save();
12156
+ try {
12157
+ ctx.imageSmoothingEnabled = true;
12158
+ ctx.globalAlpha = opacity;
12159
+ if (rowsRunUp(axis)) {
12160
+ ctx.translate(0, height);
12161
+ ctx.scale(1, -1);
12162
+ }
12163
+ ctx.drawImage(this.cache.canvas, 0, 0, width, height);
12164
+ }
12165
+ finally {
12166
+ ctx.restore();
12167
+ }
12168
+ }
12169
+ }
12170
+
12171
+ /**
12172
+ * BaseTool - Abstract base for extracted DrawToolCore tools
12173
+ *
12174
+ * Provides shared access to state objects via a ToolContext interface.
12175
+ *
12176
+ * NOTE: This is for the OLD DrawToolCore system.
12177
+ * The new SegmentationManager system has its own tools in manager/tools/.
12178
+ */
12179
+ class BaseTool {
12180
+ constructor(ctx) {
12181
+ this.ctx = ctx;
12182
+ }
12183
+ setContext(ctx) {
12184
+ this.ctx = ctx;
12185
+ }
12186
+ }
12187
+
11825
12188
  /**
11826
12189
  * SphereTool - Sphere drawing and calculator sphere operations
11827
12190
  *
@@ -12016,6 +12379,9 @@ class SphereTool extends BaseTool {
12016
12379
  * draws the sphere canvas directly to drawingCtx for proper layering.
12017
12380
  */
12018
12381
  drawSphere(mouseX, mouseY, radius) {
12382
+ // Clearing the sphere canvas also clears the master, which holds the heatmap while shown.
12383
+ if (isHeatmapShown(this.ctx))
12384
+ return;
12019
12385
  const [, ctx] = this.clearSphereCanvas();
12020
12386
  const color = this.getColorForSphereType(this.ctx.gui_states.mode.activeSphereType);
12021
12387
  drawSphereCore(ctx, mouseX, mouseY, radius, color);
@@ -12171,6 +12537,8 @@ class SphereTool extends BaseTool {
12171
12537
  * @param radius - Sphere radius to draw
12172
12538
  */
12173
12539
  drawCalculatorSphere(radius) {
12540
+ if (isHeatmapShown(this.ctx))
12541
+ return;
12174
12542
  const [, ctx] = this.clearSphereCanvas();
12175
12543
  const nrrd = this.ctx.nrrd_states;
12176
12544
  const axis = this.ctx.protectedData.axis;
@@ -12994,7 +13362,11 @@ class DragSliceTool extends BaseTool {
12994
13362
  // Skip layer mask rendering when sphere mode is active —
12995
13363
  // layer masks should remain hidden until the user exits sphere mode.
12996
13364
  if (view.switchSliceFlag) {
12997
- if (!this.ctx.gui_states.mode.sphere) {
13365
+ if (isHeatmapShown(this.ctx)) {
13366
+ // The heatmap view paints in the composite instead of any layer, whatever tool is selected.
13367
+ this.callbacks.compositeAllLayers();
13368
+ }
13369
+ else if (!this.ctx.gui_states.mode.sphere) {
12998
13370
  const axis = this.ctx.protectedData.axis;
12999
13371
  const sliceIndex = view.currentSliceIndex;
13000
13372
  // Get a single reusable buffer — shared across all layer renders
@@ -13245,6 +13617,8 @@ class RenderingUtils {
13245
13617
  this.setEmptyCanvasSize = () => { };
13246
13618
  /** Set while this viewer draws another viewer's masks; painted after this viewer's own layers. */
13247
13619
  this.mirror = null;
13620
+ /** The probability heatmap; painted instead of the layers while the heatmap view is on. */
13621
+ this.heatmap = null;
13248
13622
  /** Called after every composite. The owner refreshes the viewers mirroring this one. */
13249
13623
  this.onComposited = null;
13250
13624
  // Reusable ImageData buffer for zero-allocation slice rendering
@@ -13417,25 +13791,38 @@ class RenderingUtils {
13417
13791
  * Only draws layers whose visibility is enabled.
13418
13792
  */
13419
13793
  compositeAllLayers() {
13420
- var _a, _b, _c, _d;
13794
+ var _a, _b, _c, _d, _e;
13421
13795
  const masterCtx = this.state.protectedData.ctxes.drawingLayerMasterCtx;
13422
13796
  const width = this.state.nrrd_states.view.changedWidth;
13423
13797
  const height = this.state.nrrd_states.view.changedHeight;
13424
13798
  masterCtx.clearRect(0, 0, width, height);
13799
+ // The heatmap view replaces every layer and the mirror; with no volume set it draws nothing.
13800
+ if (isHeatmapShown(this.state)) {
13801
+ if (this.heatmap) {
13802
+ const { threshold, opacity } = this.state.gui_states.heatmap;
13803
+ const axis = this.state.protectedData.axis;
13804
+ // Just after an axis switch the index may still belong to the previous axis.
13805
+ const last = this.heatmap.dims[axis === "x" ? 0 : axis === "y" ? 1 : 2] - 1;
13806
+ const index = Math.min(last, Math.max(0, this.state.nrrd_states.view.currentSliceIndex));
13807
+ this.heatmap.paint(masterCtx, axis, index, width, height, threshold, opacity);
13808
+ }
13809
+ (_a = this.onComposited) === null || _a === void 0 ? void 0 : _a.call(this);
13810
+ return;
13811
+ }
13425
13812
  for (const layerId of this.state.nrrd_states.image.layers) {
13426
13813
  if (!this.state.gui_states.layerChannel.layerVisibility[layerId])
13427
13814
  continue;
13428
13815
  const target = this.state.protectedData.layerTargets.get(layerId);
13429
13816
  if (target) {
13430
- 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;
13817
+ 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;
13431
13818
  masterCtx.save();
13432
13819
  masterCtx.globalAlpha = layerAlpha;
13433
13820
  masterCtx.drawImage(target.canvas, 0, 0, width, height);
13434
13821
  masterCtx.restore();
13435
13822
  }
13436
13823
  }
13437
- (_c = this.mirror) === null || _c === void 0 ? void 0 : _c.paint(masterCtx, width, height);
13438
- (_d = this.onComposited) === null || _d === void 0 ? void 0 : _d.call(this);
13824
+ (_d = this.mirror) === null || _d === void 0 ? void 0 : _d.paint(masterCtx, width, height);
13825
+ (_e = this.onComposited) === null || _e === void 0 ? void 0 : _e.call(this);
13439
13826
  }
13440
13827
  }
13441
13828
 
@@ -14753,9 +15140,16 @@ class DrawingTool extends BaseTool {
14753
15140
  this.ctx.protectedData.canvases.drawingCanvas.removeEventListener("mousemove", handler);
14754
15141
  }
14755
15142
  else if (e.type === "mouseover") {
14756
- this.ctx.nrrd_states.interaction.mouseOver = true;
15143
+ this.ctx.nrrd_states.interaction.mouseOver = !isHeatmapShown(this.ctx);
14757
15144
  this.ctx.protectedData.canvases.drawingCanvas.addEventListener("mousemove", handler);
14758
15145
  }
15146
+ else if (isHeatmapShown(this.ctx)) {
15147
+ // The ring would mark a brush that cannot paint while the heatmap is shown.
15148
+ this.ctx.nrrd_states.interaction.mouseOver = false;
15149
+ }
15150
+ else {
15151
+ this.ctx.nrrd_states.interaction.mouseOver = true;
15152
+ }
14759
15153
  };
14760
15154
  return handler;
14761
15155
  }
@@ -16807,6 +17201,13 @@ class DrawToolCore {
16807
17201
  isAnnotationSuspended() {
16808
17202
  return this.annotationSuspended;
16809
17203
  }
17204
+ /**
17205
+ * True while a mask must not be written: annotation is suspended, or the heatmap is
17206
+ * shown (it owns the master canvas, and what is on screen is not a mask).
17207
+ */
17208
+ writesBlocked() {
17209
+ return this.annotationSuspended || isHeatmapShown(this.state);
17210
+ }
16810
17211
  /**
16811
17212
  * Left/right button press on the drawing canvas.
16812
17213
  *
@@ -16824,7 +17225,7 @@ class DrawToolCore {
16824
17225
  if (e.button === 0) {
16825
17226
  // Every branch that can write into a mask is gated; the crosshair below is a
16826
17227
  // read-only probe and stays available, as do pan (button 2) and the wheel.
16827
- if (this.annotationSuspended && !this.eventRouter.isCrosshairEnabled()) {
17228
+ if (this.writesBlocked() && !this.eventRouter.isCrosshairEnabled()) {
16828
17229
  return;
16829
17230
  }
16830
17231
  if (this.eventRouter.getMode() === 'aiAssist') {
@@ -16866,6 +17267,12 @@ class DrawToolCore {
16866
17267
  return;
16867
17268
  }
16868
17269
  }
17270
+ /** Pointer move while a stroke or pan is active; a stroke can only continue where writes are allowed. */
17271
+ onCanvasPointerMove(e) {
17272
+ if (this.writesBlocked())
17273
+ return;
17274
+ this.drawingTool.onPointerMove(e);
17275
+ }
16869
17276
  /**
16870
17277
  * Left/right button release on the drawing canvas.
16871
17278
  *
@@ -16880,7 +17287,7 @@ class DrawToolCore {
16880
17287
  onCanvasPointerUp(e) {
16881
17288
  if (e.button === 0) {
16882
17289
  if (this.drawingTool.painting ||
16883
- (this.eventRouter.getMode() === 'draw' && !this.annotationSuspended)) {
17290
+ (this.eventRouter.getMode() === 'draw' && !this.writesBlocked())) {
16884
17291
  this.drawingTool.onPointerUp(e);
16885
17292
  this.activeWheelMode = 'zoom';
16886
17293
  }
@@ -16896,7 +17303,10 @@ class DrawToolCore {
16896
17303
  }
16897
17304
  else if (this.state.gui_states.mode.sphere &&
16898
17305
  !this.eventRouter.isCrosshairEnabled()) {
16899
- this.sphereTool.onSpherePointerUp();
17306
+ // A placement held when the heatmap appeared is dropped, not written; the wheel
17307
+ // is handed back either way.
17308
+ if (!isHeatmapShown(this.state))
17309
+ this.sphereTool.onSpherePointerUp();
16900
17310
  this.activeWheelMode = 'zoom';
16901
17311
  this.zoomActionAfterDrawSphere();
16902
17312
  }
@@ -17358,11 +17768,7 @@ class DrawToolCore {
17358
17768
  this.drawingPrameters.handleOnDrawingBrushCricleMove =
17359
17769
  this.drawingTool.createBrushTrackingHandler();
17360
17770
  // drawing move — delegated to DrawingTool
17361
- this.drawingPrameters.handleOnDrawingMouseMove = (e) => {
17362
- if (this.annotationSuspended)
17363
- return;
17364
- this.drawingTool.onPointerMove(e);
17365
- };
17771
+ this.drawingPrameters.handleOnDrawingMouseMove = (e) => this.onCanvasPointerMove(e);
17366
17772
  this.drawingPrameters.handleOnDrawingMouseDown = (e) => this.onCanvasPointerDown(e);
17367
17773
  // Route pointerdown through EventRouter
17368
17774
  this.eventRouter.setPointerDownHandler((e) => {
@@ -17400,7 +17806,15 @@ class DrawToolCore {
17400
17806
  else if (currentMode === 'crosshair' || this.eventRouter.isCrosshairEnabled()) {
17401
17807
  this.crosshairTool.renderCrosshair(this.state.protectedData.ctxes.drawingCtx, this.state.nrrd_states.view.changedWidth, this.state.nrrd_states.view.changedHeight);
17402
17808
  }
17809
+ // The heatmap carries its own opacity; the mask opacity must not dim it.
17810
+ const heatmapShown = isHeatmapShown(this.state);
17811
+ if (heatmapShown)
17812
+ this.state.protectedData.ctxes.drawingCtx.globalAlpha = 1;
17403
17813
  this.state.protectedData.ctxes.drawingCtx.drawImage(this.state.protectedData.canvases.drawingCanvasLayerMaster, 0, 0);
17814
+ if (heatmapShown) {
17815
+ this.state.protectedData.ctxes.drawingCtx.globalAlpha =
17816
+ this.state.gui_states.drawing.globalAlpha;
17817
+ }
17404
17818
  // Brush/eraser size ring is drawn AFTER the mask composite so it stays
17405
17819
  // visible during an active stroke (not just on hover) — e.g. while the
17406
17820
  // user resizes with Shift+wheel mid-paint. Gated on draw mode so it only
@@ -17519,15 +17933,22 @@ class DrawToolCore {
17519
17933
  }
17520
17934
  /****************************Sphere functions (delegated to SphereTool)****************************************************/
17521
17935
  drawCalculatorSphereOnEachViews(axis) {
17936
+ // Placing a marker clears the master canvas, which holds the heatmap while it is shown.
17937
+ if (isHeatmapShown(this.state))
17938
+ return;
17522
17939
  this.sphereTool.drawCalculatorSphereOnEachViews(axis);
17523
17940
  }
17524
17941
  configMouseSphereWheel() {
17525
17942
  return this.sphereTool.configMouseSphereWheel();
17526
17943
  }
17527
17944
  drawCalculatorSphere(radius) {
17945
+ if (isHeatmapShown(this.state))
17946
+ return;
17528
17947
  this.sphereTool.drawCalculatorSphere(radius);
17529
17948
  }
17530
17949
  drawSphere(mouseX, mouseY, radius) {
17950
+ if (isHeatmapShown(this.state))
17951
+ return;
17531
17952
  this.sphereTool.drawSphere(mouseX, mouseY, radius);
17532
17953
  }
17533
17954
  /**
@@ -17561,6 +17982,8 @@ class DrawToolCore {
17561
17982
  * Clear the mask on the current slice canvas for the active layer ONLY.
17562
17983
  */
17563
17984
  clearActiveSlice() {
17985
+ if (isHeatmapShown(this.state))
17986
+ return;
17564
17987
  this.state.protectedData.isDrawing = true;
17565
17988
  this.state.protectedData.canvases.originCanvas.width =
17566
17989
  this.state.protectedData.canvases.originCanvas.width;
@@ -17609,9 +18032,29 @@ class DrawToolCore {
17609
18032
  * Undo the last drawing operation on the active layer.
17610
18033
  */
17611
18034
  undoLastPainting() {
17612
- const entry = this.undoManager.undo();
17613
- if (!entry)
18035
+ if (isHeatmapShown(this.state))
17614
18036
  return;
18037
+ const entry = this.undoManager.undo();
18038
+ if (entry)
18039
+ this.applyUndo(entry);
18040
+ }
18041
+ /**
18042
+ * Undo `entry` on its own layer if it is still that layer's latest operation, whichever
18043
+ * layer is active; otherwise change nothing.
18044
+ *
18045
+ * @returns Whether it was undone. False when a later operation is stacked on top of it, or
18046
+ * when it has already been undone.
18047
+ */
18048
+ undoEntry(entry) {
18049
+ const layerId = entryLayer(entry);
18050
+ if (layerId === undefined || this.undoManager.peek(layerId) !== entry)
18051
+ return false;
18052
+ this.undoManager.undoOn(layerId);
18053
+ this.applyUndo(entry);
18054
+ return true;
18055
+ }
18056
+ /** Write an entry's "before" state back into its volume, repaint, and report the change. */
18057
+ applyUndo(entry) {
17615
18058
  this.state.protectedData.isDrawing = true;
17616
18059
  if (!Array.isArray(entry)) {
17617
18060
  // VolumeSnapshot: restore the pre-replacement volume in one step.
@@ -17642,6 +18085,8 @@ class DrawToolCore {
17642
18085
  * Redo the last undone operation on the active layer.
17643
18086
  */
17644
18087
  redoLastPainting() {
18088
+ if (isHeatmapShown(this.state))
18089
+ return;
17645
18090
  const entry = this.undoManager.redo();
17646
18091
  if (!entry)
17647
18092
  return;
@@ -17902,11 +18347,12 @@ class NrrdState {
17902
18347
  /**
17903
18348
  * GuiState — Grouped state management for GUI configuration.
17904
18349
  *
17905
- * Replaces the flat IGUIStates object with 4 semantic sub-groups:
18350
+ * Replaces the flat IGUIStates object with 5 semantic sub-groups:
17906
18351
  * - mode: Tool mode flags (pencil/eraser/sphere)
17907
18352
  * - drawing: Brush/pencil appearance and behavior
17908
18353
  * - viewConfig: UI layout and interaction parameters
17909
18354
  * - layerChannel: Active layer, channel, and visibility
18355
+ * - heatmap: Probability heatmap view: shown, threshold, opacity
17910
18356
  */
17911
18357
  class GuiState {
17912
18358
  constructor(options) {
@@ -17949,6 +18395,7 @@ class GuiState {
17949
18395
  ])),
17950
18396
  layerOpacity: Object.fromEntries(layers.map((l) => [l, 1.0])),
17951
18397
  };
18398
+ this.heatmap = { visible: false, threshold: 0.1, opacity: 0.5 };
17952
18399
  }
17953
18400
  }
17954
18401
 
@@ -18695,6 +19142,11 @@ class SliceRenderPipeline extends BaseTool {
18695
19142
  * Replaces the old reloadMaskToLayer approach
18696
19143
  */
18697
19144
  reloadMasksFromVolume() {
19145
+ // The heatmap view paints in the composite instead of any layer, whatever tool is selected.
19146
+ if (isHeatmapShown(this.ctx)) {
19147
+ this.callbacks.compositeAllLayers();
19148
+ return;
19149
+ }
18698
19150
  // When sphere mode is active, do NOT redraw layer masks.
18699
19151
  // Layer mask data should remain hidden until the user exits sphere mode.
18700
19152
  if (this.ctx.gui_states.mode.sphere) {
@@ -18958,170 +19410,6 @@ class SliceRenderPipeline extends BaseTool {
18958
19410
  }
18959
19411
  }
18960
19412
 
18961
- const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
18962
- /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
18963
- function sliceDims(dims, axis) {
18964
- const [w, h, d] = [dims[0], dims[1], dims[2]];
18965
- return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [h, d];
18966
- }
18967
- /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
18968
- function isIdentity(m, tol = 1e-9) {
18969
- if (!m)
18970
- return true;
18971
- for (let i = 0; i < 16; i++) {
18972
- if (Math.abs(m[i] - IDENTITY[i]) > tol)
18973
- return false;
18974
- }
18975
- return true;
18976
- }
18977
- /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
18978
- function isDiagonal(m, tol = 1e-9) {
18979
- for (const i of [1, 2, 4, 6, 8, 9]) {
18980
- if (Math.abs(m[i]) > tol)
18981
- return false;
18982
- }
18983
- return true;
18984
- }
18985
- /**
18986
- * For each mirror index along one axis, the inclusive source index range it covers, clamped
18987
- * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
18988
- * source voxel covers the one nearest its centre; a larger one covers every source voxel
18989
- * whose centre lies within it.
18990
- */
18991
- function coveredRanges(s, t, count, extent) {
18992
- const lo = new Int32Array(count);
18993
- const hi = new Int32Array(count);
18994
- const half = Math.abs(s) / 2;
18995
- for (let i = 0; i < count; i++) {
18996
- const c = s * i + t;
18997
- let a, b;
18998
- if (Math.abs(s) <= 1) {
18999
- a = b = Math.round(c);
19000
- }
19001
- else {
19002
- a = Math.ceil(c - half - 1e-9);
19003
- b = Math.floor(c + half - 1e-9);
19004
- }
19005
- lo[i] = Math.max(a, 0);
19006
- hi[i] = Math.min(b, extent - 1);
19007
- }
19008
- return { lo, hi };
19009
- }
19010
- /**
19011
- * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
19012
- * the source is 0. On the same grid with the identity, it is the source's own slice.
19013
- *
19014
- * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
19015
- * coarser than the source shows the first label found among every source voxel it spans, so
19016
- * a finding thinner than the mirror's slice still appears on the slice that contains it.
19017
- * Any other transform samples the nearest source voxel.
19018
- */
19019
- function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
19020
- const sd = source.getDimensions();
19021
- if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
19022
- const s = source.getSliceUint8(index, axis);
19023
- return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
19024
- }
19025
- const mat = m !== null && m !== void 0 ? m : IDENTITY;
19026
- const [W, H] = sliceDims(mirrorDims, axis);
19027
- const raw = source.getRawData();
19028
- const nch = source.getChannels();
19029
- const out = new Uint8Array(W * H);
19030
- if (isDiagonal(mat)) {
19031
- const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
19032
- const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
19033
- const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
19034
- for (let v = 0; v < H; v++) {
19035
- for (let u = 0; u < W; u++) {
19036
- const x = axis === "x" ? index : u;
19037
- const y = axis === "y" ? index : axis === "x" ? u : v;
19038
- const z = axis === "z" ? index : v;
19039
- let label = 0;
19040
- for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
19041
- for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
19042
- for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
19043
- label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
19044
- }
19045
- }
19046
- }
19047
- out[v * W + u] = label;
19048
- }
19049
- }
19050
- return { data: out, width: W, height: H, stride: 1 };
19051
- }
19052
- for (let v = 0; v < H; v++) {
19053
- for (let u = 0; u < W; u++) {
19054
- // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
19055
- const x = axis === "x" ? index : u;
19056
- const y = axis === "y" ? index : axis === "x" ? u : v;
19057
- const z = axis === "z" ? index : v;
19058
- const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
19059
- const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
19060
- const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
19061
- if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
19062
- continue;
19063
- out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
19064
- }
19065
- }
19066
- return { data: out, width: W, height: H, stride: 1 };
19067
- }
19068
- /**
19069
- * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
19070
- * volumes and display state. A new transform means a new instance, so the cache never holds
19071
- * contours from another transform.
19072
- */
19073
- class MaskMirror {
19074
- constructor(self, source, matrix) {
19075
- this.self = self;
19076
- this.source = source;
19077
- this.matrix = matrix;
19078
- /** One contour entry per source layer, for the slice last painted. */
19079
- this.cache = new Map();
19080
- /** The source volume each cache entry was built from; a case load replaces the object. */
19081
- this.cachedVolumes = new Map();
19082
- }
19083
- /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
19084
- paint(ctx, width, height) {
19085
- var _a, _b;
19086
- // The source hides its own layers in sphere mode, so the mirror shows none either.
19087
- if (this.source.gui_states.mode.sphere)
19088
- return;
19089
- const dims = this.self.nrrd_states.image.dimensions;
19090
- if (!dims || dims.length !== 3)
19091
- return;
19092
- const axis = this.self.protectedData.axis;
19093
- const index = this.self.nrrd_states.view.currentSliceIndex;
19094
- const lc = this.source.gui_states.layerChannel;
19095
- const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
19096
- for (const layerId of this.source.nrrd_states.image.layers) {
19097
- if (!lc.layerVisibility[layerId])
19098
- continue;
19099
- const volume = this.source.protectedData.maskData.volumes[layerId];
19100
- if (!volume)
19101
- continue;
19102
- if (this.cachedVolumes.get(layerId) !== volume) {
19103
- this.cache.delete(layerId);
19104
- this.cachedVolumes.set(layerId, volume);
19105
- }
19106
- try {
19107
- const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
19108
- ctx.save();
19109
- try {
19110
- ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
19111
- paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
19112
- }
19113
- finally {
19114
- // A throw must not leave this layer's alpha or transform on the master canvas.
19115
- ctx.restore();
19116
- }
19117
- }
19118
- catch (_c) {
19119
- // The source is not ready for this slice: nothing to draw for this layer.
19120
- }
19121
- }
19122
- }
19123
- }
19124
-
19125
19413
  /**
19126
19414
  * NrrdTools.setMasksFromNIfTI forwards its `Map<string, Uint8Array>` argument
19127
19415
  * straight through to here with no second channel for metadata, so a caller that
@@ -19788,6 +20076,10 @@ class NrrdTools {
19788
20076
  }
19789
20077
  executeAction(action, opts) {
19790
20078
  var _a;
20079
+ // Every other action writes a mask, and nothing may while the heatmap is shown.
20080
+ const readOnly = action === "resetZoom" || action === "downloadCurrentMask";
20081
+ if (!readOnly && isHeatmapShown(this.state))
20082
+ return;
19791
20083
  switch (action) {
19792
20084
  case "undo":
19793
20085
  this.undo();
@@ -19891,6 +20183,7 @@ class NrrdTools {
19891
20183
  *
19892
20184
  * @param layerId Layer whose mask to edit.
19893
20185
  * @param channel Label to erase, 1-255.
20186
+ * @returns The clear, for `undoChannelClear`; null when the channel held nothing.
19894
20187
  * @throws {Error} If `layerId` names no layer. Deliberately NOT routed through
19895
20188
  * `getVolumeForLayer`, which warns and falls back to the first layer — for a
19896
20189
  * destructive call that would quietly erase a different layer's annotation.
@@ -19918,7 +20211,7 @@ class NrrdTools {
19918
20211
  });
19919
20212
  }
19920
20213
  if (deltas.length === 0)
19921
- return; // nothing drawn on this channel
20214
+ return null; // nothing drawn on this channel
19922
20215
  volume.clearChannel(channel);
19923
20216
  for (const delta of deltas) {
19924
20217
  delta.newSlice = volume.getSliceUint8(delta.sliceIndex, "z").data.slice();
@@ -19929,6 +20222,28 @@ class NrrdTools {
19929
20222
  this.state.annotationCallbacks.onMaskChanged(data, layerId, channel, delta.sliceIndex, "z", width, height, false);
19930
20223
  }
19931
20224
  this.reloadMasksFromVolume();
20225
+ return { layerId, channel, entry: deltas };
20226
+ }
20227
+ /**
20228
+ * Undo one `clearChannel`, on its own layer, whatever layer is active now.
20229
+ *
20230
+ * `undo()` acts on the active layer's latest operation, and by the time a caller offers to
20231
+ * reverse a clear the active layer may have changed. This names the clear instead, and
20232
+ * reverses it only while it is still the latest operation on its layer: a later edit there is
20233
+ * newer work, never undone in passing -- `undo()` steps back through it in order.
20234
+ *
20235
+ * Reported through `onMaskChanged` with the channels it restored, exactly as `undo()` reports.
20236
+ *
20237
+ * @returns Whether the clear was undone. False when a later operation is stacked on it, or
20238
+ * it has already been undone.
20239
+ */
20240
+ undoChannelClear(clear) {
20241
+ if (!this.drawCore.undoEntry(clear.entry))
20242
+ return false;
20243
+ // `undo()` repaints only the slice on screen when it lies on the clear's axis; a clear
20244
+ // spans every slice of the label, so repaint them all, as the clear itself does.
20245
+ this.reloadMasksFromVolume();
20246
+ return true;
19932
20247
  }
19933
20248
  // ═══════════════════════════════════════════════════════════════════════════
19934
20249
  // 4. Public API — Keyboard & History
@@ -20411,6 +20726,54 @@ class NrrdTools {
20411
20726
  this.reloadMasksFromVolume();
20412
20727
  }
20413
20728
  getMaskRenderMode() { return this.state.gui_states.drawing.maskRenderMode; }
20729
+ /**
20730
+ * Canonical uint8 probabilities (p × 255), x fastest, in the loaded image's dimensions.
20731
+ * Throws when `dims` differ from the image's or do not match the volume's length. null clears.
20732
+ */
20733
+ setHeatmap(volume, dims) {
20734
+ if (volume === null) {
20735
+ this.drawCore.renderer.heatmap = null;
20736
+ }
20737
+ else {
20738
+ const image = this.getCurrentImageDimension();
20739
+ if (!dims || image.length !== 3 || dims.length !== 3 || dims.some((n, i) => n !== image[i])) {
20740
+ throw new Error(`setHeatmap: heatmap dimensions ${dims !== null && dims !== void 0 ? dims : "(none)"} differ from the image's ${image}`);
20741
+ }
20742
+ const [w, h, d] = dims;
20743
+ if (volume.length !== w * h * d) {
20744
+ throw new Error(`setHeatmap: ${volume.length} heatmap voxels for dimensions ${dims}`);
20745
+ }
20746
+ this.drawCore.renderer.heatmap = new HeatmapOverlay(volume, [w, h, d]);
20747
+ }
20748
+ if (this.isHeatmapVisible())
20749
+ this.drawCore.renderer.compositeAllLayers();
20750
+ }
20751
+ /** Show the heatmap instead of every mask layer, or bring the layers back. */
20752
+ setHeatmapVisible(visible) {
20753
+ this.state.gui_states.heatmap.visible = visible;
20754
+ if (visible) {
20755
+ this.drawCore.renderer.compositeAllLayers();
20756
+ return;
20757
+ }
20758
+ // Clear first: the reload returns without compositing in sphere mode and in a viewer with
20759
+ // no layers and no mirror, and would leave the heatmap drawn. Sphere mode keeps nothing on
20760
+ // the master (its overlay has its own canvas), so this is what that mode shows anyway.
20761
+ this.state.protectedData.ctxes.drawingLayerMasterCtx.clearRect(0, 0, this.state.nrrd_states.view.changedWidth, this.state.nrrd_states.view.changedHeight);
20762
+ this.reloadMasksFromVolume();
20763
+ }
20764
+ isHeatmapVisible() { return this.state.gui_states.heatmap.visible; }
20765
+ /** Probabilities below `t` (clamped to 0–1) are not drawn. */
20766
+ setHeatmapThreshold(t) {
20767
+ this.state.gui_states.heatmap.threshold = Math.min(1, Math.max(0, t));
20768
+ if (this.isHeatmapVisible())
20769
+ this.drawCore.renderer.compositeAllLayers();
20770
+ }
20771
+ /** Clamped to 0–1. */
20772
+ setHeatmapOpacity(a) {
20773
+ this.state.gui_states.heatmap.opacity = Math.min(1, Math.max(0, a));
20774
+ if (this.isHeatmapVisible())
20775
+ this.drawCore.renderer.compositeAllLayers();
20776
+ }
20414
20777
  // ═══════════════════════════════════════════════════════════════════════════
20415
20778
  // 8. Delegated — SliceRenderPipeline
20416
20779
  // ═══════════════════════════════════════════════════════════════════════════
@@ -20437,6 +20800,9 @@ class NrrdTools {
20437
20800
  // 10. Sphere Orchestration
20438
20801
  // ═══════════════════════════════════════════════════════════════════════════
20439
20802
  setCalculateDistanceSphere(x, y, sliceIndex, cal_position) {
20803
+ // A marker repaints the master canvas, which holds the heatmap while it is shown.
20804
+ if (isHeatmapShown(this.state))
20805
+ return;
20440
20806
  this.state.nrrd_states.sphere.sphereRadius = 5;
20441
20807
  const steps = sliceIndex - this.state.nrrd_states.view.currentSliceIndex;
20442
20808
  this.setSliceMoving(steps * this.state.protectedData.displaySlices.length);
@@ -20685,6 +21051,8 @@ class NrrdTools {
20685
21051
  // 11. Clear / Reset
20686
21052
  // ═══════════════════════════════════════════════════════════════════════════
20687
21053
  clearActiveLayer() {
21054
+ if (isHeatmapShown(this.state))
21055
+ return;
20688
21056
  if (this.state.nrrd_states.image.dimensions.length === 3) {
20689
21057
  const [w, h, d] = this.state.nrrd_states.image.dimensions;
20690
21058
  const activeLayer = this.state.gui_states.layerChannel.layer;
@@ -22134,15 +22502,15 @@ function checkThreeRevision(built, loaded) {
22134
22502
  }
22135
22503
 
22136
22504
  // import * as kiwrious from "copper3d_plugin_heart_k";
22137
- // "v4.1.3" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
22505
+ // "v4.2.0" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
22138
22506
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
22139
22507
  // referencing it throws a ReferenceError — guard it so local loading still works.
22140
22508
  let _revision = "unknown";
22141
22509
  try {
22142
- _revision = "v4.1.3";
22510
+ _revision = "v4.2.0";
22143
22511
  }
22144
22512
  catch (_a) {
22145
- /* "v4.1.3" not injected (local source build) */
22513
+ /* "v4.2.0" not injected (local source build) */
22146
22514
  }
22147
22515
  const REVISION = _revision;
22148
22516
  // "186" is three's revision at build time, injected the same way.
@@ -22162,4 +22530,4 @@ if (typeof console !== "undefined") {
22162
22530
  console.log(`%cCopper3D Visualisation %c${REVISION}`, "padding: 3px;color:white; background:#023047", "padding: 3px;color:white; background:#f50a25");
22163
22531
  }
22164
22532
 
22165
- export { AI_CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, CHANNEL_COLORS, CHANNEL_HEX_COLORS, CameraViewPoint, Copper3dOrbitControls, Copper3dTrackballControls, DEFAULT_AXES, DEFAULT_TARGET_GREY, GaussianSmoother, MAX_ENGINE_CHANNEL, MeshNodeTool, NrrdTools, OrientationError, REVISION, SurfaceAnnotator, VOLUME_BOUNDS_NAME, addBoxHelper, addLabelToScene, addVolumeBoundingBox, beginGesture, canonicalTransform, collectFadeTargets, configKiwriousHeart, convert3DPostoScreenPos, convertScreenPosto3DPos, copperGltfLoader, copperMScene, copperMSceneRenderer, copperRenderer, copperRendererOnDemond, copperScene, copperSceneOnDemond, createSceneBudget, createTexture2D_NRRD, defaultBudgetBytes, disposeMaterial, disposeObject3D, disposeScene, easeInOutCubic, ensureAxisExtracted, exposureExponent, fitDistance, fitView, fullScreenListenner, geometryFromNrrd, installFastSliceRepaint, interpolateFlightPose, isGestureActive, isPanEnabled, isRotateEnabled, isZoomEnabled, kiwrious, loadKiwrious, loading$1 as loading, orbitStepPose, orbitSwingAngle, poseDistance, prepareVolumeSlices, rasDimensions, readNrrdOrientationFields, registerNiftiMaskGrid, removeGuiFolderChilden, removeSceneFromMap, reorientVoxels, reorientedGeometry, restoreFade, rgbaToCss, rgbaToHex, rotateAroundAxis, setCameraPose, setDracoDecoderPath, setFade, setHDRFilePath, setKTX2TranscoderPath, setPanEnabled, setRotateEnabled, setZoomEnabled, throttle, viewLabels, viewPointToPose, zoomPose };
22533
+ export { AI_CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, CHANNEL_COLORS, CHANNEL_HEX_COLORS, CameraViewPoint, Copper3dOrbitControls, Copper3dTrackballControls, DEFAULT_AXES, DEFAULT_TARGET_GREY, GaussianSmoother, HEATMAP_COLORMAP, MAX_ENGINE_CHANNEL, MeshNodeTool, NrrdTools, OrientationError, REVISION, SurfaceAnnotator, VOLUME_BOUNDS_NAME, addBoxHelper, addLabelToScene, addVolumeBoundingBox, beginGesture, canonicalTransform, collectFadeTargets, configKiwriousHeart, convert3DPostoScreenPos, convertScreenPosto3DPos, copperGltfLoader, copperMScene, copperMSceneRenderer, copperRenderer, copperRendererOnDemond, copperScene, copperSceneOnDemond, createSceneBudget, createTexture2D_NRRD, defaultBudgetBytes, disposeMaterial, disposeObject3D, disposeScene, easeInOutCubic, ensureAxisExtracted, exposureExponent, fitDistance, fitView, fullScreenListenner, geometryFromNrrd, installFastSliceRepaint, interpolateFlightPose, isGestureActive, isPanEnabled, isRotateEnabled, isZoomEnabled, kiwrious, loadKiwrious, loading$1 as loading, orbitStepPose, orbitSwingAngle, poseDistance, prepareVolumeSlices, rasDimensions, readNrrdOrientationFields, registerNiftiMaskGrid, removeGuiFolderChilden, removeSceneFromMap, reorientVoxels, reorientedGeometry, restoreFade, rgbaToCss, rgbaToHex, rotateAroundAxis, setCameraPose, setDracoDecoderPath, setFade, setHDRFilePath, setKTX2TranscoderPath, setPanEnabled, setRotateEnabled, setZoomEnabled, throttle, viewLabels, viewPointToPose, zoomPose };