copper3d 4.1.4 → 4.2.1

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 (43) hide show
  1. package/README.md +6 -0
  2. package/ai-index/guides/nrrd-tools.md +55 -0
  3. package/ai-index/guides/segmentation-module.md +31 -0
  4. package/ai-index/manifest.json +5 -5
  5. package/ai-index/symbols.json +1 -1
  6. package/dist/Utils/segmentation/DrawToolCore.d.ts +7 -0
  7. package/dist/Utils/segmentation/DrawToolCore.js +42 -8
  8. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  9. package/dist/Utils/segmentation/NrrdTools.d.ts +12 -0
  10. package/dist/Utils/segmentation/NrrdTools.js +58 -0
  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/types.d.ts +9 -0
  16. package/dist/Utils/segmentation/core/types.js.map +1 -1
  17. package/dist/Utils/segmentation/coreTools/GuiState.d.ts +4 -2
  18. package/dist/Utils/segmentation/coreTools/GuiState.js +3 -1
  19. package/dist/Utils/segmentation/coreTools/GuiState.js.map +1 -1
  20. package/dist/Utils/segmentation/tools/DragSliceTool.js +6 -1
  21. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  22. package/dist/Utils/segmentation/tools/DrawingTool.js +9 -1
  23. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  24. package/dist/Utils/segmentation/tools/HeatmapOverlay.d.ts +37 -0
  25. package/dist/Utils/segmentation/tools/HeatmapOverlay.js +185 -0
  26. package/dist/Utils/segmentation/tools/HeatmapOverlay.js.map +1 -0
  27. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +6 -0
  28. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  29. package/dist/Utils/segmentation/tools/SphereTool.js +6 -0
  30. package/dist/Utils/segmentation/tools/SphereTool.js.map +1 -1
  31. package/dist/bundle.esm.mjs +511 -200
  32. package/dist/bundle.umd.js +512 -199
  33. package/dist/index.d.ts +2 -1
  34. package/dist/index.js +2 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/types/Utils/segmentation/DrawToolCore.d.ts +7 -0
  37. package/dist/types/Utils/segmentation/NrrdTools.d.ts +12 -0
  38. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +3 -0
  39. package/dist/types/Utils/segmentation/core/types.d.ts +9 -0
  40. package/dist/types/Utils/segmentation/coreTools/GuiState.d.ts +4 -2
  41. package/dist/types/Utils/segmentation/tools/HeatmapOverlay.d.ts +37 -0
  42. package/dist/types/index.d.ts +2 -1
  43. package/package.json +1 -1
@@ -11687,23 +11687,6 @@ function findLabelsInSlice(labels, width, height, stride = 1, channelOffset = 0,
11687
11687
  return Array.from(seen).sort((a, b) => a - b);
11688
11688
  }
11689
11689
 
11690
- /**
11691
- * BaseTool - Abstract base for extracted DrawToolCore tools
11692
- *
11693
- * Provides shared access to state objects via a ToolContext interface.
11694
- *
11695
- * NOTE: This is for the OLD DrawToolCore system.
11696
- * The new SegmentationManager system has its own tools in manager/tools/.
11697
- */
11698
- class BaseTool {
11699
- constructor(ctx) {
11700
- this.ctx = ctx;
11701
- }
11702
- setContext(ctx) {
11703
- this.ctx = ctx;
11704
- }
11705
- }
11706
-
11707
11690
  /**
11708
11691
  * Outline stroke width, in screen pixels.
11709
11692
  *
@@ -11838,6 +11821,370 @@ function drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, c
11838
11821
  }
11839
11822
  }
11840
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
+
11841
12188
  /**
11842
12189
  * SphereTool - Sphere drawing and calculator sphere operations
11843
12190
  *
@@ -12032,6 +12379,9 @@ class SphereTool extends BaseTool {
12032
12379
  * draws the sphere canvas directly to drawingCtx for proper layering.
12033
12380
  */
12034
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;
12035
12385
  const [, ctx] = this.clearSphereCanvas();
12036
12386
  const color = this.getColorForSphereType(this.ctx.gui_states.mode.activeSphereType);
12037
12387
  drawSphereCore(ctx, mouseX, mouseY, radius, color);
@@ -12187,6 +12537,8 @@ class SphereTool extends BaseTool {
12187
12537
  * @param radius - Sphere radius to draw
12188
12538
  */
12189
12539
  drawCalculatorSphere(radius) {
12540
+ if (isHeatmapShown(this.ctx))
12541
+ return;
12190
12542
  const [, ctx] = this.clearSphereCanvas();
12191
12543
  const nrrd = this.ctx.nrrd_states;
12192
12544
  const axis = this.ctx.protectedData.axis;
@@ -13010,7 +13362,11 @@ class DragSliceTool extends BaseTool {
13010
13362
  // Skip layer mask rendering when sphere mode is active —
13011
13363
  // layer masks should remain hidden until the user exits sphere mode.
13012
13364
  if (view.switchSliceFlag) {
13013
- 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) {
13014
13370
  const axis = this.ctx.protectedData.axis;
13015
13371
  const sliceIndex = view.currentSliceIndex;
13016
13372
  // Get a single reusable buffer — shared across all layer renders
@@ -13261,6 +13617,8 @@ class RenderingUtils {
13261
13617
  this.setEmptyCanvasSize = () => { };
13262
13618
  /** Set while this viewer draws another viewer's masks; painted after this viewer's own layers. */
13263
13619
  this.mirror = null;
13620
+ /** The probability heatmap; painted instead of the layers while the heatmap view is on. */
13621
+ this.heatmap = null;
13264
13622
  /** Called after every composite. The owner refreshes the viewers mirroring this one. */
13265
13623
  this.onComposited = null;
13266
13624
  // Reusable ImageData buffer for zero-allocation slice rendering
@@ -13433,25 +13791,38 @@ class RenderingUtils {
13433
13791
  * Only draws layers whose visibility is enabled.
13434
13792
  */
13435
13793
  compositeAllLayers() {
13436
- var _a, _b, _c, _d;
13794
+ var _a, _b, _c, _d, _e;
13437
13795
  const masterCtx = this.state.protectedData.ctxes.drawingLayerMasterCtx;
13438
13796
  const width = this.state.nrrd_states.view.changedWidth;
13439
13797
  const height = this.state.nrrd_states.view.changedHeight;
13440
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
+ }
13441
13812
  for (const layerId of this.state.nrrd_states.image.layers) {
13442
13813
  if (!this.state.gui_states.layerChannel.layerVisibility[layerId])
13443
13814
  continue;
13444
13815
  const target = this.state.protectedData.layerTargets.get(layerId);
13445
13816
  if (target) {
13446
- 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;
13447
13818
  masterCtx.save();
13448
13819
  masterCtx.globalAlpha = layerAlpha;
13449
13820
  masterCtx.drawImage(target.canvas, 0, 0, width, height);
13450
13821
  masterCtx.restore();
13451
13822
  }
13452
13823
  }
13453
- (_c = this.mirror) === null || _c === void 0 ? void 0 : _c.paint(masterCtx, width, height);
13454
- (_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);
13455
13826
  }
13456
13827
  }
13457
13828
 
@@ -14769,9 +15140,16 @@ class DrawingTool extends BaseTool {
14769
15140
  this.ctx.protectedData.canvases.drawingCanvas.removeEventListener("mousemove", handler);
14770
15141
  }
14771
15142
  else if (e.type === "mouseover") {
14772
- this.ctx.nrrd_states.interaction.mouseOver = true;
15143
+ this.ctx.nrrd_states.interaction.mouseOver = !isHeatmapShown(this.ctx);
14773
15144
  this.ctx.protectedData.canvases.drawingCanvas.addEventListener("mousemove", handler);
14774
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
+ }
14775
15153
  };
14776
15154
  return handler;
14777
15155
  }
@@ -16823,6 +17201,13 @@ class DrawToolCore {
16823
17201
  isAnnotationSuspended() {
16824
17202
  return this.annotationSuspended;
16825
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
+ }
16826
17211
  /**
16827
17212
  * Left/right button press on the drawing canvas.
16828
17213
  *
@@ -16840,7 +17225,7 @@ class DrawToolCore {
16840
17225
  if (e.button === 0) {
16841
17226
  // Every branch that can write into a mask is gated; the crosshair below is a
16842
17227
  // read-only probe and stays available, as do pan (button 2) and the wheel.
16843
- if (this.annotationSuspended && !this.eventRouter.isCrosshairEnabled()) {
17228
+ if (this.writesBlocked() && !this.eventRouter.isCrosshairEnabled()) {
16844
17229
  return;
16845
17230
  }
16846
17231
  if (this.eventRouter.getMode() === 'aiAssist') {
@@ -16882,6 +17267,12 @@ class DrawToolCore {
16882
17267
  return;
16883
17268
  }
16884
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
+ }
16885
17276
  /**
16886
17277
  * Left/right button release on the drawing canvas.
16887
17278
  *
@@ -16896,7 +17287,7 @@ class DrawToolCore {
16896
17287
  onCanvasPointerUp(e) {
16897
17288
  if (e.button === 0) {
16898
17289
  if (this.drawingTool.painting ||
16899
- (this.eventRouter.getMode() === 'draw' && !this.annotationSuspended)) {
17290
+ (this.eventRouter.getMode() === 'draw' && !this.writesBlocked())) {
16900
17291
  this.drawingTool.onPointerUp(e);
16901
17292
  this.activeWheelMode = 'zoom';
16902
17293
  }
@@ -16912,7 +17303,10 @@ class DrawToolCore {
16912
17303
  }
16913
17304
  else if (this.state.gui_states.mode.sphere &&
16914
17305
  !this.eventRouter.isCrosshairEnabled()) {
16915
- 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();
16916
17310
  this.activeWheelMode = 'zoom';
16917
17311
  this.zoomActionAfterDrawSphere();
16918
17312
  }
@@ -17374,11 +17768,7 @@ class DrawToolCore {
17374
17768
  this.drawingPrameters.handleOnDrawingBrushCricleMove =
17375
17769
  this.drawingTool.createBrushTrackingHandler();
17376
17770
  // drawing move — delegated to DrawingTool
17377
- this.drawingPrameters.handleOnDrawingMouseMove = (e) => {
17378
- if (this.annotationSuspended)
17379
- return;
17380
- this.drawingTool.onPointerMove(e);
17381
- };
17771
+ this.drawingPrameters.handleOnDrawingMouseMove = (e) => this.onCanvasPointerMove(e);
17382
17772
  this.drawingPrameters.handleOnDrawingMouseDown = (e) => this.onCanvasPointerDown(e);
17383
17773
  // Route pointerdown through EventRouter
17384
17774
  this.eventRouter.setPointerDownHandler((e) => {
@@ -17416,7 +17806,15 @@ class DrawToolCore {
17416
17806
  else if (currentMode === 'crosshair' || this.eventRouter.isCrosshairEnabled()) {
17417
17807
  this.crosshairTool.renderCrosshair(this.state.protectedData.ctxes.drawingCtx, this.state.nrrd_states.view.changedWidth, this.state.nrrd_states.view.changedHeight);
17418
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;
17419
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
+ }
17420
17818
  // Brush/eraser size ring is drawn AFTER the mask composite so it stays
17421
17819
  // visible during an active stroke (not just on hover) — e.g. while the
17422
17820
  // user resizes with Shift+wheel mid-paint. Gated on draw mode so it only
@@ -17535,15 +17933,22 @@ class DrawToolCore {
17535
17933
  }
17536
17934
  /****************************Sphere functions (delegated to SphereTool)****************************************************/
17537
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;
17538
17939
  this.sphereTool.drawCalculatorSphereOnEachViews(axis);
17539
17940
  }
17540
17941
  configMouseSphereWheel() {
17541
17942
  return this.sphereTool.configMouseSphereWheel();
17542
17943
  }
17543
17944
  drawCalculatorSphere(radius) {
17945
+ if (isHeatmapShown(this.state))
17946
+ return;
17544
17947
  this.sphereTool.drawCalculatorSphere(radius);
17545
17948
  }
17546
17949
  drawSphere(mouseX, mouseY, radius) {
17950
+ if (isHeatmapShown(this.state))
17951
+ return;
17547
17952
  this.sphereTool.drawSphere(mouseX, mouseY, radius);
17548
17953
  }
17549
17954
  /**
@@ -17577,6 +17982,8 @@ class DrawToolCore {
17577
17982
  * Clear the mask on the current slice canvas for the active layer ONLY.
17578
17983
  */
17579
17984
  clearActiveSlice() {
17985
+ if (isHeatmapShown(this.state))
17986
+ return;
17580
17987
  this.state.protectedData.isDrawing = true;
17581
17988
  this.state.protectedData.canvases.originCanvas.width =
17582
17989
  this.state.protectedData.canvases.originCanvas.width;
@@ -17625,6 +18032,8 @@ class DrawToolCore {
17625
18032
  * Undo the last drawing operation on the active layer.
17626
18033
  */
17627
18034
  undoLastPainting() {
18035
+ if (isHeatmapShown(this.state))
18036
+ return;
17628
18037
  const entry = this.undoManager.undo();
17629
18038
  if (entry)
17630
18039
  this.applyUndo(entry);
@@ -17676,6 +18085,8 @@ class DrawToolCore {
17676
18085
  * Redo the last undone operation on the active layer.
17677
18086
  */
17678
18087
  redoLastPainting() {
18088
+ if (isHeatmapShown(this.state))
18089
+ return;
17679
18090
  const entry = this.undoManager.redo();
17680
18091
  if (!entry)
17681
18092
  return;
@@ -17936,11 +18347,12 @@ class NrrdState {
17936
18347
  /**
17937
18348
  * GuiState — Grouped state management for GUI configuration.
17938
18349
  *
17939
- * Replaces the flat IGUIStates object with 4 semantic sub-groups:
18350
+ * Replaces the flat IGUIStates object with 5 semantic sub-groups:
17940
18351
  * - mode: Tool mode flags (pencil/eraser/sphere)
17941
18352
  * - drawing: Brush/pencil appearance and behavior
17942
18353
  * - viewConfig: UI layout and interaction parameters
17943
18354
  * - layerChannel: Active layer, channel, and visibility
18355
+ * - heatmap: Probability heatmap view: shown, threshold, opacity
17944
18356
  */
17945
18357
  class GuiState {
17946
18358
  constructor(options) {
@@ -17983,6 +18395,7 @@ class GuiState {
17983
18395
  ])),
17984
18396
  layerOpacity: Object.fromEntries(layers.map((l) => [l, 1.0])),
17985
18397
  };
18398
+ this.heatmap = { visible: false, threshold: 0.1, opacity: 0.5 };
17986
18399
  }
17987
18400
  }
17988
18401
 
@@ -18729,6 +19142,11 @@ class SliceRenderPipeline extends BaseTool {
18729
19142
  * Replaces the old reloadMaskToLayer approach
18730
19143
  */
18731
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
+ }
18732
19150
  // When sphere mode is active, do NOT redraw layer masks.
18733
19151
  // Layer mask data should remain hidden until the user exits sphere mode.
18734
19152
  if (this.ctx.gui_states.mode.sphere) {
@@ -18992,170 +19410,6 @@ class SliceRenderPipeline extends BaseTool {
18992
19410
  }
18993
19411
  }
18994
19412
 
18995
- const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
18996
- /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
18997
- function sliceDims(dims, axis) {
18998
- const [w, h, d] = [dims[0], dims[1], dims[2]];
18999
- return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [h, d];
19000
- }
19001
- /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
19002
- function isIdentity(m, tol = 1e-9) {
19003
- if (!m)
19004
- return true;
19005
- for (let i = 0; i < 16; i++) {
19006
- if (Math.abs(m[i] - IDENTITY[i]) > tol)
19007
- return false;
19008
- }
19009
- return true;
19010
- }
19011
- /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
19012
- function isDiagonal(m, tol = 1e-9) {
19013
- for (const i of [1, 2, 4, 6, 8, 9]) {
19014
- if (Math.abs(m[i]) > tol)
19015
- return false;
19016
- }
19017
- return true;
19018
- }
19019
- /**
19020
- * For each mirror index along one axis, the inclusive source index range it covers, clamped
19021
- * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
19022
- * source voxel covers the one nearest its centre; a larger one covers every source voxel
19023
- * whose centre lies within it.
19024
- */
19025
- function coveredRanges(s, t, count, extent) {
19026
- const lo = new Int32Array(count);
19027
- const hi = new Int32Array(count);
19028
- const half = Math.abs(s) / 2;
19029
- for (let i = 0; i < count; i++) {
19030
- const c = s * i + t;
19031
- let a, b;
19032
- if (Math.abs(s) <= 1) {
19033
- a = b = Math.round(c);
19034
- }
19035
- else {
19036
- a = Math.ceil(c - half - 1e-9);
19037
- b = Math.floor(c + half - 1e-9);
19038
- }
19039
- lo[i] = Math.max(a, 0);
19040
- hi[i] = Math.min(b, extent - 1);
19041
- }
19042
- return { lo, hi };
19043
- }
19044
- /**
19045
- * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
19046
- * the source is 0. On the same grid with the identity, it is the source's own slice.
19047
- *
19048
- * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
19049
- * coarser than the source shows the first label found among every source voxel it spans, so
19050
- * a finding thinner than the mirror's slice still appears on the slice that contains it.
19051
- * Any other transform samples the nearest source voxel.
19052
- */
19053
- function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
19054
- const sd = source.getDimensions();
19055
- if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
19056
- const s = source.getSliceUint8(index, axis);
19057
- return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
19058
- }
19059
- const mat = m !== null && m !== void 0 ? m : IDENTITY;
19060
- const [W, H] = sliceDims(mirrorDims, axis);
19061
- const raw = source.getRawData();
19062
- const nch = source.getChannels();
19063
- const out = new Uint8Array(W * H);
19064
- if (isDiagonal(mat)) {
19065
- const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
19066
- const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
19067
- const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
19068
- for (let v = 0; v < H; v++) {
19069
- for (let u = 0; u < W; u++) {
19070
- const x = axis === "x" ? index : u;
19071
- const y = axis === "y" ? index : axis === "x" ? u : v;
19072
- const z = axis === "z" ? index : v;
19073
- let label = 0;
19074
- for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
19075
- for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
19076
- for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
19077
- label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
19078
- }
19079
- }
19080
- }
19081
- out[v * W + u] = label;
19082
- }
19083
- }
19084
- return { data: out, width: W, height: H, stride: 1 };
19085
- }
19086
- for (let v = 0; v < H; v++) {
19087
- for (let u = 0; u < W; u++) {
19088
- // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
19089
- const x = axis === "x" ? index : u;
19090
- const y = axis === "y" ? index : axis === "x" ? u : v;
19091
- const z = axis === "z" ? index : v;
19092
- const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
19093
- const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
19094
- const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
19095
- if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
19096
- continue;
19097
- out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
19098
- }
19099
- }
19100
- return { data: out, width: W, height: H, stride: 1 };
19101
- }
19102
- /**
19103
- * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
19104
- * volumes and display state. A new transform means a new instance, so the cache never holds
19105
- * contours from another transform.
19106
- */
19107
- class MaskMirror {
19108
- constructor(self, source, matrix) {
19109
- this.self = self;
19110
- this.source = source;
19111
- this.matrix = matrix;
19112
- /** One contour entry per source layer, for the slice last painted. */
19113
- this.cache = new Map();
19114
- /** The source volume each cache entry was built from; a case load replaces the object. */
19115
- this.cachedVolumes = new Map();
19116
- }
19117
- /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
19118
- paint(ctx, width, height) {
19119
- var _a, _b;
19120
- // The source hides its own layers in sphere mode, so the mirror shows none either.
19121
- if (this.source.gui_states.mode.sphere)
19122
- return;
19123
- const dims = this.self.nrrd_states.image.dimensions;
19124
- if (!dims || dims.length !== 3)
19125
- return;
19126
- const axis = this.self.protectedData.axis;
19127
- const index = this.self.nrrd_states.view.currentSliceIndex;
19128
- const lc = this.source.gui_states.layerChannel;
19129
- const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
19130
- for (const layerId of this.source.nrrd_states.image.layers) {
19131
- if (!lc.layerVisibility[layerId])
19132
- continue;
19133
- const volume = this.source.protectedData.maskData.volumes[layerId];
19134
- if (!volume)
19135
- continue;
19136
- if (this.cachedVolumes.get(layerId) !== volume) {
19137
- this.cache.delete(layerId);
19138
- this.cachedVolumes.set(layerId, volume);
19139
- }
19140
- try {
19141
- const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
19142
- ctx.save();
19143
- try {
19144
- ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
19145
- paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
19146
- }
19147
- finally {
19148
- // A throw must not leave this layer's alpha or transform on the master canvas.
19149
- ctx.restore();
19150
- }
19151
- }
19152
- catch (_c) {
19153
- // The source is not ready for this slice: nothing to draw for this layer.
19154
- }
19155
- }
19156
- }
19157
- }
19158
-
19159
19413
  /**
19160
19414
  * NrrdTools.setMasksFromNIfTI forwards its `Map<string, Uint8Array>` argument
19161
19415
  * straight through to here with no second channel for metadata, so a caller that
@@ -19822,6 +20076,10 @@ class NrrdTools {
19822
20076
  }
19823
20077
  executeAction(action, opts) {
19824
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;
19825
20083
  switch (action) {
19826
20084
  case "undo":
19827
20085
  this.undo();
@@ -20468,6 +20726,54 @@ class NrrdTools {
20468
20726
  this.reloadMasksFromVolume();
20469
20727
  }
20470
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
+ }
20471
20777
  // ═══════════════════════════════════════════════════════════════════════════
20472
20778
  // 8. Delegated — SliceRenderPipeline
20473
20779
  // ═══════════════════════════════════════════════════════════════════════════
@@ -20494,6 +20800,9 @@ class NrrdTools {
20494
20800
  // 10. Sphere Orchestration
20495
20801
  // ═══════════════════════════════════════════════════════════════════════════
20496
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;
20497
20806
  this.state.nrrd_states.sphere.sphereRadius = 5;
20498
20807
  const steps = sliceIndex - this.state.nrrd_states.view.currentSliceIndex;
20499
20808
  this.setSliceMoving(steps * this.state.protectedData.displaySlices.length);
@@ -20742,6 +21051,8 @@ class NrrdTools {
20742
21051
  // 11. Clear / Reset
20743
21052
  // ═══════════════════════════════════════════════════════════════════════════
20744
21053
  clearActiveLayer() {
21054
+ if (isHeatmapShown(this.state))
21055
+ return;
20745
21056
  if (this.state.nrrd_states.image.dimensions.length === 3) {
20746
21057
  const [w, h, d] = this.state.nrrd_states.image.dimensions;
20747
21058
  const activeLayer = this.state.gui_states.layerChannel.layer;
@@ -22191,15 +22502,15 @@ function checkThreeRevision(built, loaded) {
22191
22502
  }
22192
22503
 
22193
22504
  // import * as kiwrious from "copper3d_plugin_heart_k";
22194
- // "v4.1.4" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
22505
+ // "v4.2.1" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
22195
22506
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
22196
22507
  // referencing it throws a ReferenceError — guard it so local loading still works.
22197
22508
  let _revision = "unknown";
22198
22509
  try {
22199
- _revision = "v4.1.4";
22510
+ _revision = "v4.2.1";
22200
22511
  }
22201
22512
  catch (_a) {
22202
- /* "v4.1.4" not injected (local source build) */
22513
+ /* "v4.2.1" not injected (local source build) */
22203
22514
  }
22204
22515
  const REVISION = _revision;
22205
22516
  // "186" is three's revision at build time, injected the same way.
@@ -22219,4 +22530,4 @@ if (typeof console !== "undefined") {
22219
22530
  console.log(`%cCopper3D Visualisation %c${REVISION}`, "padding: 3px;color:white; background:#023047", "padding: 3px;color:white; background:#f50a25");
22220
22531
  }
22221
22532
 
22222
- 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, heatmapThresholdByte, 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 };