copper3d 3.10.4 → 3.11.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 (31) hide show
  1. package/README.md +128 -0
  2. package/ai-index/guides/4D-MRI-LV-rendering.md +580 -0
  3. package/ai-index/guides/ai-assist-api.md +382 -0
  4. package/ai-index/guides/camera-framing.md +238 -0
  5. package/ai-index/guides/control-axes.md +124 -0
  6. package/ai-index/guides/copper3d-4D-API.md +219 -0
  7. package/ai-index/guides/copper3d-rendering-optimization.md +155 -0
  8. package/ai-index/guides/gltf-decoders.md +105 -0
  9. package/ai-index/guides/heart-sensor.md +137 -0
  10. package/ai-index/guides/load-callbacks.md +244 -0
  11. package/ai-index/guides/mcp-server.md +139 -0
  12. package/ai-index/guides/nrrd-tools.md +1888 -0
  13. package/ai-index/guides/on-demand-controls.md +154 -0
  14. package/ai-index/guides/rotation-pivot.md +197 -0
  15. package/ai-index/guides/scene-resources.md +227 -0
  16. package/ai-index/guides/segmentation-module.md +1539 -0
  17. package/ai-index/guides/surface-annotation-api.md +388 -0
  18. package/ai-index/guides/volume-display.md +194 -0
  19. package/ai-index/manifest.json +144 -0
  20. package/ai-index/symbols.json +1 -0
  21. package/dist/Utils/segmentation/DrawToolCore.d.ts +19 -0
  22. package/dist/Utils/segmentation/DrawToolCore.js +62 -36
  23. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  24. package/dist/Utils/segmentation/tools/DrawingTool.js +14 -2
  25. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  26. package/dist/Utils/segmentation/tools/ToolHost.d.ts +2 -1
  27. package/dist/bundle.esm.js +79 -41
  28. package/dist/bundle.umd.js +79 -41
  29. package/dist/types/Utils/segmentation/DrawToolCore.d.ts +19 -0
  30. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +2 -1
  31. package/package.json +7 -4
@@ -0,0 +1,1888 @@
1
+ ## NrrdTools Usage Guide
2
+
3
+ > Copper3D `NrrdTools` — Medical Image Segmentation Annotation Engine
4
+
5
+ `NrrdTools` is the core annotation engine of Copper3D. It manages multi-layer mask volumes, a layered canvas pipeline, drawing tools, undo/redo history, channel color customization, and keyboard shortcuts — all on top of a Three.js medical image viewer.
6
+
7
+ > **Internal Architecture**: `NrrdTools` is a **Facade** class that uses **composition** (no inheritance). It composes:
8
+ > - **`CanvasState`** — pure state container (nrrd_states, gui_states, protectedData, cursorPage, annotationCallbacks, keyboardSettings)
9
+ > - **`DrawToolCore`** — tool orchestration, event routing (composes `CanvasState` + `RenderingUtils`)
10
+ > - **`RenderingUtils`** — rendering / slice-buffer helpers (compositeAllLayers, renderSliceToCanvas, etc.)
11
+ > - **`LayerChannelManager`** — layer/channel/sphere-type management and channel color customization
12
+ > - **`SliceRenderPipeline`** — slice setup, canvas rendering, mask reload, canvas flip
13
+ > - **`DataLoader`** — NRRD slice loading, legacy mask loading, NIfTI voxel loading
14
+ >
15
+ > The old 3-level inheritance chain (`NrrdTools → DrawToolCore → CommToolsData`) has been fully replaced. `CommToolsData` has been deleted.
16
+ > All modules communicate via `ToolContext` (shared state) and `Pick<ToolHost, ...>` type aliases (host method dependencies). The public API documented below is unchanged.
17
+
18
+ ---
19
+
20
+ ### Table of Contents
21
+
22
+ 1. [Quick Start](#1-quick-start)
23
+ 2. [Constructor & Initialization](#2-constructor--initialization)
24
+ 3. [Data Loading](#3-data-loading)
25
+ 4. [Render Loop Integration](#4-render-loop-integration)
26
+ 5. [Drawing Setup](#5-drawing-setup)
27
+ 6. [Layer & Channel Management](#6-layer--channel-management)
28
+ 7. [Channel Color Customization](#7-channel-color-customization)
29
+ 8. [Undo / Redo](#8-undo--redo)
30
+ 9. [Keyboard Shortcuts](#9-keyboard-shortcuts)
31
+ 10. [Display & Canvas Control](#10-display--canvas-control)
32
+ 11. [Reading State & Diagnostics](#11-reading-state--diagnostics)
33
+ 12. [Advanced Scenarios](#12-advanced-scenarios)
34
+ 13. [Vue 3 Integration Pattern](#13-vue-3-integration-pattern)
35
+ 14. [Type Reference](#14-type-reference)
36
+
37
+ ---
38
+
39
+ ### 1. Quick Start
40
+
41
+ ```typescript
42
+ import * as Copper from 'copper3d';
43
+
44
+ // 1. Mount the tool on a container div
45
+ const container = document.getElementById('viewer') as HTMLDivElement;
46
+ const nrrdTools = new Copper.NrrdTools(container);
47
+
48
+ // 2. After NRRD images are loaded via Copper scene:
49
+ nrrdTools.reset();
50
+ nrrdTools.setAllSlices(allSlices); // allSlices from Copper scene loader
51
+
52
+ // 3. Hook drawing callbacks
53
+ nrrdTools.drag({ getSliceNum: (index, contrastIndex) => {
54
+ console.log('Slice changed to:', index);
55
+ }});
56
+
57
+ nrrdTools.draw({
58
+ getMaskData: (sliceData, layerId, channelId, sliceIndex, axis, width, height, clearFlag) => {
59
+ // Called after every stroke, undo, redo — sync to backend here
60
+ console.log(`Layer ${layerId}, channel ${channelId}, slice ${sliceIndex} on ${axis}-axis`);
61
+ }
62
+ });
63
+
64
+ // 4. Register with the Copper render loop
65
+ scene.addPreRenderCallbackFunction(nrrdTools.start);
66
+ ```
67
+
68
+ ---
69
+
70
+ ### 2. Constructor & Initialization
71
+
72
+ #### Signature
73
+
74
+ ```typescript
75
+ new Copper.NrrdTools(container: HTMLDivElement, options?: { layers?: string[] })
76
+ ```
77
+
78
+ | Parameter | Type | Default | Description |
79
+ |-----------|------|---------|-------------|
80
+ | `container` | `HTMLDivElement` | required | The DOM element that will host all annotation canvases |
81
+ | `options.layers` | `string[]` | `["layer1","layer2","layer3"]` | Named layers to create. Each layer gets its own `MaskVolume` and canvas |
82
+
83
+ #### Example: Single-layer (minimal)
84
+
85
+ ```typescript
86
+ const nrrdTools = new Copper.NrrdTools(document.getElementById('viewer') as HTMLDivElement);
87
+ ```
88
+
89
+ #### Example: Custom layer set
90
+
91
+ ```typescript
92
+ // For a 4-layer segmentation workflow:
93
+ // layer1 = Tumour, layer2 = Edema, layer3 = Necrosis, layer4 = Enhancement
94
+ const nrrdTools = new Copper.NrrdTools(container, {
95
+ layers: ['layer1', 'layer2', 'layer3', 'layer4']
96
+ });
97
+ ```
98
+
99
+ > **Important**: The layer list you pass here must match what your backend and UI expect.
100
+ > Adding or removing layers later requires re-instantiation.
101
+
102
+ ::: tip Layer ids are arbitrary strings <Badge type="tip" text="3.10.4" />
103
+ They do not have to be `layerN`:
104
+
105
+ ```typescript
106
+ const nrrdTools = new Copper.NrrdTools(container, {
107
+ layers: ['tumour', 'edema', 'necrosis', 'vessel']
108
+ });
109
+ ```
110
+
111
+ Before 3.10.4 the undo stacks were pre-created for `layer1` / `layer2` / `layer3` only, so a
112
+ custom id either silently pushed onto another layer's history or threw on undo. Stacks are now
113
+ created on demand, keyed by whatever id you pass.
114
+ :::
115
+
116
+ #### Example: read-only reference viewer <Badge type="tip" text="3.11.1" />
117
+
118
+ Pass an empty list for a viewer that shows the image but has nothing to annotate into — a
119
+ side-by-side reference panel, a prior study, a QA view:
120
+
121
+ ```typescript
122
+ const reference = new Copper.NrrdTools(container, { layers: [] });
123
+ ```
124
+
125
+ Slice scrubbing, zoom, pan, window/level and the crosshair all work as usual. The drawing
126
+ tools have no layer to target and skip their work rather than failing: `setCurrentLayer()`
127
+ returns `null` and every caller checks it.
128
+
129
+ ::: tip Which one to reach for
130
+ `layers: []` is a **structural** choice — this instance will never annotate.
131
+ `setAnnotationSuspended(true)` (§5.6) is a **temporary** one on an instance that will, such as
132
+ during loading. Use the flag if the user gets to draw later; use the empty list if they never
133
+ do.
134
+ :::
135
+
136
+ #### Optional display panel
137
+
138
+ Attach a panel element to show current slice index in the viewer:
139
+
140
+ ```typescript
141
+ const slicePanel = document.getElementById('slice-index-panel') as HTMLDivElement;
142
+ nrrdTools.setDisplaySliceIndexPanel(slicePanel);
143
+ ```
144
+
145
+ #### Optional GUI (dat.GUI)
146
+
147
+ If your project uses `dat.GUI`, wire up the built-in control panel:
148
+
149
+ ```typescript
150
+ import GUI from 'lil-gui'; // or 'dat.gui'
151
+ const gui = new GUI();
152
+ nrrdTools.setupGUI(gui as any);
153
+ ```
154
+
155
+ ---
156
+
157
+ ### 3. Data Loading
158
+
159
+ #### 3.1 Loading NRRD / NIfTI image slices
160
+
161
+ This is the entry point that initializes all `MaskVolume` instances to the correct voxel dimensions.
162
+ Must be called **after** Copper has loaded and decoded the NRRD files.
163
+
164
+ ```typescript
165
+ // Reset state from previous case
166
+ nrrdTools.reset();
167
+
168
+ // allSlices is the array of decoded NRRD slice objects returned by Copper's loader
169
+ nrrdTools.setAllSlices(allSlices);
170
+ ```
171
+
172
+ > After `setAllSlices()` returns, you may safely call all layer/channel/color APIs.
173
+ > Calling color APIs **before** `setAllSlices()` will silently fail (no MaskVolume exists yet).
174
+
175
+ ::: tip Narrowed-axes loads are supported <Badge type="tip" text="3.10.0" />
176
+ `setAllSlices` reads its geometry (dimensions, spacing, space origin) from the shared
177
+ `Volume` behind whichever plane *is* present, so slices loaded with
178
+ [`axes: ["z"]`](./load-callbacks) work here
179
+ too. The missing planes are extracted on demand the first time
180
+ `setSliceOrientation()` asks for them.
181
+ :::
182
+
183
+ #### 3.2 Loading existing mask data (NIfTI)
184
+
185
+ If the user has previously saved annotations, reload them into the volumes:
186
+
187
+ ```typescript
188
+ // layerVoxels maps each layer ID to a Uint8Array of raw NIfTI voxels
189
+ const layerVoxels = new Map<string, Uint8Array>([
190
+ ['layer1', layer1Uint8Array],
191
+ ['layer2', layer2Uint8Array],
192
+ ]);
193
+
194
+ nrrdTools.setMasksFromNIfTI(layerVoxels);
195
+ ```
196
+
197
+ With a loading progress bar:
198
+
199
+ ```typescript
200
+ const loadingBar = { value: 0 }; // must be a reactive object with .value
201
+ nrrdTools.setMasksFromNIfTI(layerVoxels, loadingBar);
202
+ ```
203
+
204
+ ##### Grid validation — `registerNiftiMaskGrid()` <Badge type="tip" text="3.10.0" />
205
+
206
+ `setMasksFromNIfTI` used to make any buffer fit: a longer one was truncated, a shorter one
207
+ zero-padded. Either way a mask from the wrong grid rendered **silently offset onto the wrong
208
+ voxels**, with no error anywhere. A refused mask is recoverable; a misplaced one is not.
209
+
210
+ A buffer is now checked against the loaded image's voxel grid, and **refused** when it does
211
+ not match. The check needs the buffer's own NIfTI grid, which `setMasksFromNIfTI` has no
212
+ second parameter to receive — so register it out of band, keyed by the buffer itself:
213
+
214
+ ```typescript
215
+ import { registerNiftiMaskGrid } from 'copper3d';
216
+
217
+ const { voxels, dims } = await fetchNiftiVoxels(path); // dims = header [x, y, z]
218
+ registerNiftiMaskGrid(voxels, dims); // before setMasksFromNIfTI
219
+
220
+ layerVoxels.set('layer1', voxels);
221
+ nrrdTools.setMasksFromNIfTI(layerVoxels);
222
+ ```
223
+
224
+ ::: warning A buffer with no registered grid is refused
225
+ Not assumed to match. Every buffer you pass to `setMasksFromNIfTI` needs a
226
+ `registerNiftiMaskGrid` call first, or that layer is skipped. Register each buffer as you
227
+ decode it — the registry is keyed by buffer identity, so you can decode several layers
228
+ before `setMasksFromNIfTI` is ever called.
229
+ :::
230
+
231
+ A refused layer logs to `console.error` with both grids, calls `notifyUser` (see below), and
232
+ is skipped; the other layers in the same `Map` still load.
233
+
234
+ ##### `notifyUser` — surfacing engine messages in your UI <Badge type="tip" text="3.10.0" />
235
+
236
+ This package ships without a UI of its own, so it will not reach into your application's.
237
+ `NrrdTools.notifyUser` is the seam: it defaults to a console write, and a host with a toast
238
+ or a banner assigns its own after construction.
239
+
240
+ ```typescript
241
+ nrrdTools.notifyUser = (message, level) => {
242
+ // level: 'error' | 'warning' | 'info'
243
+ toast[level](message);
244
+ };
245
+ ```
246
+
247
+ A refused mask is currently the only thing that uses it.
248
+
249
+ #### Scenario: Loading a saved case
250
+
251
+ ```typescript
252
+ import { registerNiftiMaskGrid } from 'copper3d';
253
+
254
+ async function loadCase(caseDetail: ICaseDetail) {
255
+ const layerVoxels = new Map<string, Uint8Array>();
256
+
257
+ // layer1 — always load from NIfTI if it exists
258
+ if (Number(caseDetail.output.mask_layer1_nii_size) > 0) {
259
+ const { voxels, dims } = await fetchNiftiVoxels(caseDetail.output.mask_layer1_nii_path!);
260
+ if (voxels) {
261
+ registerNiftiMaskGrid(voxels, dims);
262
+ layerVoxels.set('layer1', voxels);
263
+ }
264
+ }
265
+
266
+ // layer2 — same pattern
267
+ if (Number(caseDetail.output.mask_layer2_nii_size) > 0) {
268
+ const { voxels, dims } = await fetchNiftiVoxels(caseDetail.output.mask_layer2_nii_path!);
269
+ if (voxels) {
270
+ registerNiftiMaskGrid(voxels, dims);
271
+ layerVoxels.set('layer2', voxels);
272
+ }
273
+ }
274
+
275
+ if (layerVoxels.size > 0) {
276
+ nrrdTools.setMasksFromNIfTI(layerVoxels);
277
+ }
278
+ }
279
+ ```
280
+
281
+ #### 3.3 Contrast series: skips, contrast index, and batched commits
282
+
283
+ A loaded case is a *series* of contrasts (phases). `allSlicesArray` holds every contrast;
284
+ `displaySlices` holds the subset actually shown, built from the skip list. Two index spaces
285
+ follow from that, and mixing them up is the usual bug here:
286
+
287
+ | Term | Addresses | Note |
288
+ |------|-----------|------|
289
+ | skip `index` | position in the **full** contrast list | what `addSkip` / `removeSkip` / `setSkips` take |
290
+ | `contrastIndex` | position in **`displaySlices`** — the selected subset | what `setContrastIndex` takes |
291
+
292
+ With three of five phases selected, valid `contrastIndex` values are `0..2`. Callers that
293
+ think in phase names must convert first.
294
+
295
+ ```typescript
296
+ nrrdTools.addSkip(2); // hide contrast 2
297
+ nrrdTools.removeSkip(2); // show it again
298
+ nrrdTools.setContrastIndex(1); // jump to the 2nd *displayed* contrast
299
+ ```
300
+
301
+ ##### Batched forms <Badge type="tip" text="3.10.0" />
302
+
303
+ Each of the calls above ends in a full display/canvas/mask refresh. In a loop — reconciling
304
+ a whole phase selection at case-load time — every refresh but the last is immediately
305
+ superseded, and the cost is real (measured at over a second of main-thread time for a
306
+ five-phase series). The batched forms do the same work with **one** refresh:
307
+
308
+ ```typescript
309
+ // Many skip changes, one refresh
310
+ nrrdTools.setSkips([
311
+ { index: 0, skip: false },
312
+ { index: 1, skip: true },
313
+ { index: 2, skip: true },
314
+ ]);
315
+
316
+ // Skip changes + land on a contrast, one refresh
317
+ nrrdTools.commitSkipsAndContrast(
318
+ [{ index: 1, skip: true }, { index: 3, skip: true }],
319
+ 0
320
+ );
321
+
322
+ // Whole case-load completion: swap the series, reconcile skips, land on a contrast
323
+ nrrdTools.commitSeriesLoad(allSlices, skipEntries, 0);
324
+ ```
325
+
326
+ `commitSeriesLoad` replaces the `switchAllSlicesArrayData` + `setSkips` + `setContrastIndex`
327
+ sequence, which used to pay three full refreshes where one is enough. `contrastIndex` is
328
+ clamped to the freshly rebuilt `displaySlices`, exactly like `setContrastIndex` does.
329
+
330
+ ::: tip Which one to use
331
+ - A single user-driven toggle → `addSkip` / `removeSkip`.
332
+ - Several skip changes in one turn → `setSkips`.
333
+ - Skip changes plus a target contrast → `commitSkipsAndContrast`.
334
+ - A complete case/series load → `commitSeriesLoad`.
335
+ :::
336
+
337
+ ##### Swapping the series without losing the view
338
+
339
+ ```typescript
340
+ // Resets slice index / zoom / pan
341
+ nrrdTools.switchAllSlicesArrayData(allSlices);
342
+
343
+ // Keeps current slice index, zoom and pan — for register/origin image switching
344
+ nrrdTools.switchSlicesPreservingView(allSlices);
345
+ ```
346
+
347
+ ---
348
+
349
+ ### 4. Render Loop Integration
350
+
351
+ `NrrdTools.start` is a function property that must be called every frame to refresh the annotation overlay on top of the Three.js rendered CT/MRI slice.
352
+
353
+ #### With Copper scene
354
+
355
+ ```typescript
356
+ // Register once after initialization
357
+ const callbackId = scene.addPreRenderCallbackFunction(nrrdTools.start);
358
+
359
+ // Unregister on teardown (e.g., Vue component unmount)
360
+ scene.removePreRenderCallbackFunction(callbackId);
361
+ ```
362
+
363
+ #### Manual render loop
364
+
365
+ ```typescript
366
+ function animate() {
367
+ requestAnimationFrame(animate);
368
+ renderer.render(scene, camera);
369
+ nrrdTools.start();
370
+ }
371
+ animate();
372
+ ```
373
+
374
+ ---
375
+
376
+ ### 5. Drawing Setup
377
+
378
+ #### 5.1 `drag()` — Slice navigation
379
+
380
+ Enables dragging to scroll through CT/MRI slices. Call once before adding to the render loop.
381
+
382
+ ```typescript
383
+ nrrdTools.drag({
384
+ showNumber: true, // optional: show slice number overlay
385
+ getSliceNum: (sliceIndex, contrastIndex) => { // optional: callback on slice change
386
+ console.log('Now viewing slice:', sliceIndex);
387
+ updateUISliceDisplay(sliceIndex);
388
+ }
389
+ });
390
+ ```
391
+
392
+ #### 5.2 `draw()` — Annotation callbacks
393
+
394
+ Hooks into the drawing events. The `getMaskData` callback is the primary integration point for syncing annotations to a backend.
395
+
396
+ ```typescript
397
+ nrrdTools.draw({
398
+ // Called after every draw stroke, undo, redo, or clear
399
+ getMaskData: (
400
+ sliceData: Uint8Array, // Raw voxel data for this slice (label values 0-8)
401
+ layerId: string, // Which layer was modified, e.g. "layer1"
402
+ channelId: number, // Active channel (1-255)
403
+ sliceIndex: number, // Index along the current axis
404
+ axis: 'x' | 'y' | 'z', // Current viewing axis
405
+ width: number, // Slice width in voxels
406
+ height: number, // Slice height in voxels
407
+ clearFlag?: boolean // true if the user cleared the slice
408
+ ) => {
409
+ sendSliceToBackend({ sliceData, layerId, channelId, sliceIndex, axis, width, height, clearFlag });
410
+ },
411
+
412
+ // Called when the user clears an entire layer volume
413
+ onClearLayerVolume: (layerId: string) => {
414
+ console.log(`Layer ${layerId} fully cleared`);
415
+ notifyBackendLayerCleared(layerId);
416
+ },
417
+
418
+ // Called when the 3D sphere annotation tool places a sphere (sphere mode)
419
+ //
420
+ // sphereOrigin: [mouseX, mouseY, sliceIndex] — center on z-axis view
421
+ // sphereRadius: radius in pixels (1-50)
422
+ //
423
+ // Note: Sphere data does NOT write to layer MaskVolume.
424
+ // It is rendered as a visual overlay via the dedicated sphereMaskVolume.
425
+ getSphereData: (sphereOrigin: number[], sphereRadius: number) => {
426
+ console.log('Sphere placed at', sphereOrigin, 'radius', sphereRadius);
427
+ sendSphereToBackend({ sphereOrigin, sphereRadius });
428
+ },
429
+
430
+ // Called when the calculator sphere positions are updated (calculator mode)
431
+ //
432
+ // Each sphere type maps to a specific channel on layer1:
433
+ // tumour → channel 1
434
+ // ribcage → channel 3
435
+ // skin → channel 4
436
+ // nipple → channel 2
437
+ //
438
+ // Origins are ICommXYZ: { x: [mx, my, slice], y: [...], z: [...] }
439
+ // representing sphere center coordinates on all 3 axis views.
440
+ // null if that sphere type has not been placed yet.
441
+ getCalculateSpherePositionsData: (
442
+ tumourOrigin, skinOrigin, ribOrigin, nippleOrigin, axis
443
+ ) => {
444
+ runAISegmentation({ tumourOrigin, skinOrigin, ribOrigin, nippleOrigin, axis });
445
+ },
446
+ });
447
+ ```
448
+
449
+ #### 5.3 SphereTool — 3D Sphere Placement & Distance Calculator
450
+
451
+ The SphereTool provides unified sphere placement with 4 sphere types controlled by `gui_states.mode.activeSphereType`. The active type determines which origin and color are used. The old separate "Calculator" mode has been merged into SphereTool.
452
+
453
+ ##### Sphere Types & Channel Mapping
454
+
455
+ Each sphere type maps to a specific channel on layer1. Switch between types using `gui_states.mode.activeSphereType`:
456
+
457
+ | Sphere Type | Channel | Default Color | `activeSphereType` value |
458
+ |-------------|---------|---------------|---------------------|
459
+ | tumour | 1 | `#10b981` (Emerald) | `"tumour"` (default) |
460
+ | nipple | 2 | `#f43f5e` (Rose) | `"nipple"` |
461
+ | ribcage | 3 | `#3b82f6` (Blue) | `"ribcage"` |
462
+ | skin | 4 | `#fbbf24` (Amber) | `"skin"` |
463
+
464
+ These mappings are exported as `SPHERE_CHANNEL_MAP` and `SPHERE_LABELS` from `tools/SphereTool.ts`. (`SPHERE_COLORS` was removed — colors are now derived dynamically from each volume's `colorMap`.)
465
+
466
+ ##### Switching Sphere Type
467
+
468
+ Use the public API — do NOT mutate `gui_states.mode.activeSphereType` directly, as `setActiveSphereType()` also updates brush/fill color as a side-effect:
469
+
470
+ ```typescript
471
+ // Set active sphere type (also updates fillColor / brushColor)
472
+ nrrdTools.setActiveSphereType('nipple'); // channel 2, Rose #f43f5e
473
+ nrrdTools.setActiveSphereType('tumour'); // channel 1, Emerald #10b981
474
+ nrrdTools.setActiveSphereType('skin'); // channel 4, Amber #fbbf24
475
+ nrrdTools.setActiveSphereType('ribcage'); // channel 3, Blue #3b82f6
476
+
477
+ // Read current type
478
+ const type = nrrdTools.getActiveSphereType();
479
+ // → 'tumour' | 'skin' | 'nipple' | 'ribcage'
480
+ ```
481
+
482
+ ##### Interaction Flow
483
+
484
+ ```
485
+ Sphere mode activated (gui_states.mode.sphere = true, keyboard shortcut: 'q'):
486
+ ├─ Shift key DISABLED (no draw mode)
487
+ ├─ Crosshair toggle allowed (S key)
488
+ │
489
+ ├─ Left-click DOWN → SphereTool.onSphereClick(e)
490
+ │ ├─ record origin for current activeSphereType
491
+ │ ├─ convert origin to all 3 axes (setUpSphereOrigins)
492
+ │ ├─ enable crosshair at click position
493
+ │ └─ draw calculator sphere preview
494
+ │ Then DrawToolCore sets activeWheelMode = 'sphere'
495
+ │ (EventRouter's permanent wheel handler dispatches to sphereWheel)
496
+ │
497
+ ├─ Scroll wheel (while holding) → adjust radius [1, 50]
498
+ │
499
+ └─ Left-click UP → SphereTool.onSpherePointerUp()
500
+ ├─ write all placed spheres to sphereMaskVolume
501
+ ├─ refresh sphere canvas overlay
502
+ ├─ fire onSphereChanged callback
503
+ └─ fire onCalculatorPositionsChanged callback
504
+ Then DrawToolCore sets activeWheelMode = 'zoom'
505
+ ```
506
+
507
+ ##### SphereMaskVolume
508
+
509
+ Sphere 3D data is stored in a dedicated `MaskVolume` (`nrrd_states.sphereMaskVolume`), separate from the layer draw mask volumes. This prevents sphere overlay data from polluting layer1's annotations.
510
+
511
+ - **Created** in `setAllSlices()` (same dimensions as CT volume)
512
+ - **Cleared** in `reset()` (when switching cases)
513
+
514
+ > **Note**: Currently sphere data does NOT write to layer1's MaskVolume. The channel mapping and `sphereMaskVolume` are reserved for future integration.
515
+
516
+ ##### Scenario: Sphere mode with AI backend (distance calculation)
517
+
518
+ ```typescript
519
+ nrrdTools.draw({
520
+ // Called on every sphere placement — receives all 4 sphere origins
521
+ getCalculateSpherePositionsData: (tumour, skin, rib, nipple, axis) => {
522
+ // Each origin is { x: [mx, my, slice], y: [...], z: [...] } or null
523
+ if (tumour && skin && rib && nipple) {
524
+ aiBackend.runSegmentation({ tumour, skin, rib, nipple, axis });
525
+ }
526
+ },
527
+ // Also called — receives the current sphere's origin and radius
528
+ getSphereData: (origin, radius) => {
529
+ console.log('Sphere placed at', origin, 'radius', radius);
530
+ },
531
+ });
532
+ ```
533
+
534
+ ##### Programmatic Sphere Placement (Backend → Frontend)
535
+
536
+ When the backend returns sphere coordinates (e.g., from AI detection), use `setCalculateDistanceSphere()` to place them without user interaction. This method replicates the full mouse-down → mouse-up flow internally:
537
+
538
+ ```typescript
539
+ // Backend returns sphere data for a case
540
+ interface BackendSphereData {
541
+ type: 'tumour' | 'skin' | 'nipple' | 'ribcage';
542
+ x: number; // X in unscaled image space
543
+ y: number; // Y in unscaled image space
544
+ sliceIndex: number; // Target slice index
545
+ }
546
+
547
+ // Place each sphere programmatically
548
+ function applySphereFromBackend(nrrdTools: Copper.NrrdTools, spheres: BackendSphereData[]) {
549
+ for (const s of spheres) {
550
+ nrrdTools.setCalculateDistanceSphere(s.x, s.y, s.sliceIndex, s.type);
551
+ }
552
+ }
553
+
554
+ // Example: place a tumour sphere at (120, 95) on slice 42
555
+ nrrdTools.setCalculateDistanceSphere(120, 95, 42, 'tumour');
556
+ ```
557
+
558
+ Internally, `setCalculateDistanceSphere` performs:
559
+ 1. Sets `sphereRadius = 5` and navigates to the target slice
560
+ 2. Records `sphereOrigin` on all 3 axes (via `crosshairTool.setUpSphereOrigins`)
561
+ 3. Deep-copies the origin into the type-specific field (e.g., `tumourSphereOrigin`)
562
+ 4. Draws the sphere preview on canvas (`drawCalculatorSphere`)
563
+ 5. Writes all placed spheres to `sphereMaskVolume` (`writeAllCalculatorSpheresToVolume`)
564
+ 6. Re-renders the sphere overlay (`refreshSphereCanvas`)
565
+
566
+ > **Note**: Coordinates (`x`, `y`) are in **unscaled** image space. The method automatically applies `sizeFactor` scaling internally.
567
+
568
+ #### 5.4 SphereBrush & SphereEraser — 3D Volume Painting & Erasing
569
+
570
+ SphereBrush and SphereEraser are direct 3D volume tools that write/erase a sphere into the **active layer's shared MaskVolume** using the active channel label. Unlike the Sphere (Marker) tool which uses a separate `sphereMaskVolume`, these tools modify layer data directly and are fully compatible with the undo/redo system, NIfTI export, and GLTF generation.
571
+
572
+ ##### Tool Modes
573
+
574
+ | Tool | Mode Value | Description |
575
+ |------|-----------|-------------|
576
+ | Sphere Brush | `"sphereBrush"` | Left-click to paint a 3D sphere into the active layer |
577
+ | Sphere Eraser | `"sphereEraser"` | Left-click to erase a 3D sphere (or drag to erase continuously). Only erases the active channel. |
578
+
579
+ ##### Activating SphereBrush / SphereEraser
580
+
581
+ ```typescript
582
+ // Switch to Sphere Brush mode
583
+ nrrdTools.setMode('sphereBrush');
584
+
585
+ // Switch to Sphere Eraser mode
586
+ nrrdTools.setMode('sphereEraser');
587
+
588
+ // Read current mode
589
+ const mode = nrrdTools.getMode();
590
+ // → 'sphereBrush' | 'sphereEraser' | 'pencil' | 'brush' | 'eraser' | 'sphere' | 'calculator'
591
+ ```
592
+
593
+ ##### Radius Control
594
+
595
+ ```typescript
596
+ // Set sphere brush/eraser radius (clamped to [1, 50])
597
+ nrrdTools.setSphereBrushRadius(10);
598
+
599
+ // Read current radius
600
+ const radius = nrrdTools.getSphereBrushRadius(); // → 10
601
+ ```
602
+
603
+ During interaction, the user can also adjust radius via the scroll wheel while holding the left mouse button.
604
+
605
+ ##### Interaction Flow
606
+
607
+ ```
608
+ SphereBrush mode (gui_states.mode.sphereBrush = true):
609
+ ├─ Shift key DISABLED (no draw mode)
610
+ ├─ Drag slice DISABLED
611
+ ├─ Crosshair toggle allowed (S key)
612
+ │
613
+ ├─ Left-click DOWN → record center, draw preview circle
614
+ │ Then activeWheelMode = 'sphereBrush'
615
+ │
616
+ ├─ Scroll wheel (while holding) → adjust radius [1, 50]
617
+ │
618
+ └─ Left-click UP → write 3D sphere to MaskVolume
619
+ ├─ push undo group (all affected Z-slices)
620
+ ├─ re-render layer canvas
621
+ ├─ fire onMaskChanged for ALL affected slices
622
+ └─ activeWheelMode = 'zoom'
623
+
624
+ SphereEraser mode (gui_states.mode.sphereEraser = true):
625
+ ├─ Same constraints as SphereBrush
626
+ │
627
+ ├─ Left-click DOWN → record center, capture before-snapshots
628
+ │
629
+ ├─ Drag (optional) → continuously erase along path
630
+ │ └─ lazily captures before-snapshots for newly touched Z-slices
631
+ │
632
+ ├─ Scroll wheel (while holding) → adjust radius [1, 50]
633
+ │
634
+ └─ Left-click UP → finalize erase
635
+ ├─ push cumulative undo group (all affected Z-slices from entire drag)
636
+ ├─ re-render layer canvas
637
+ ├─ fire onMaskChanged for ALL affected slices
638
+ └─ activeWheelMode = 'zoom'
639
+ ```
640
+
641
+ ##### Key Differences from Sphere (Marker)
642
+
643
+ | Feature | Sphere (Marker) | SphereBrush / SphereEraser |
644
+ |---------|----------------|---------------------------|
645
+ | Storage target | `sphereMaskVolume` (separate overlay) | Active layer's `MaskVolume` (shared) |
646
+ | Channel behavior | Fixed per sphere type | Uses active channel |
647
+ | NIfTI/GLTF export | Not exported (overlay only) | Fully exported as 3D volume |
648
+ | Undo support | No | Yes (grouped multi-slice undo) |
649
+ | Drag support | No | SphereEraser supports drag-to-erase |
650
+
651
+ ##### Scenario: AI result review with Sphere Eraser
652
+
653
+ ```typescript
654
+ // Load AI segmentation result
655
+ nrrdTools.setMasksFromNIfTI(layerVoxels);
656
+
657
+ // Switch to sphere eraser for quick cleanup
658
+ nrrdTools.setMode('sphereEraser');
659
+ nrrdTools.setSphereBrushRadius(8);
660
+
661
+ // User can now click or drag to erase incorrect regions
662
+ // All changes are undoable and will be correctly exported
663
+ ```
664
+
665
+ #### 5.5 `enableContrastDragEvents()` — Windowing
666
+
667
+ Enable Ctrl+drag to adjust window/level (brightness/contrast):
668
+
669
+ ```typescript
670
+ nrrdTools.enableContrastDragEvents((step: number, towards: 'horizental' | 'vertical') => {
671
+ // step: magnitude of drag movement
672
+ // towards: direction of drag
673
+ console.log(`Contrast adjusted: ${towards} ${step}`);
674
+ });
675
+ ```
676
+
677
+ #### 5.6 Suspending annotation — read-only preview <Badge type="tip" text="3.10.0" />
678
+
679
+ ```typescript
680
+ nrrdTools.setAnnotationSuspended(true); // preview only
681
+ nrrdTools.setAnnotationSuspended(false); // annotation live again
682
+ const suspended = nrrdTools.isAnnotationSuspended();
683
+ ```
684
+
685
+ While suspended, **no input can write into a mask**. Everything that only reads stays live,
686
+ so the case remains fully reviewable:
687
+
688
+ | Still works | Blocked |
689
+ |-------------|---------|
690
+ | Slice scrubbing (drag, wheel, `setSliceMoving`) | Pencil / brush / eraser strokes |
691
+ | Zoom and pan (right-drag) | Sphere placement |
692
+ | Crosshair placement | SphereBrush / SphereEraser |
693
+ | Window / level | AI-assist prompts |
694
+
695
+ The typical use is the window while a case's images are still arriving:
696
+
697
+ ```typescript
698
+ nrrdTools.setAnnotationSuspended(true);
699
+ await loadAllContrasts(caseId);
700
+ nrrdTools.commitSeriesLoad(allSlices, skipEntries, 0);
701
+ nrrdTools.setAnnotationSuspended(false);
702
+ ```
703
+
704
+ ::: warning Greying out your own toolbar is not equivalent
705
+ Two reasons this has to be enforced inside the engine:
706
+
707
+ 1. A tool selected **before** the load began stays armed on the canvas — the buttons are
708
+ disabled, but a left-drag still paints.
709
+ 2. A stroke made during loading cannot be undone. `afterLoadSlice` clears the undo stack
710
+ every time a slice lands, so the mask keeps the paint while the history that would
711
+ reverse it is thrown away by the next arrival.
712
+ :::
713
+
714
+ The gate sits at a single point — `DrawToolCore.onCanvasPointerDown` — rather than in each
715
+ tool, so a tool added later is covered by default.
716
+
717
+ ---
718
+
719
+ ### 6. Layer & Channel Management
720
+
721
+ NrrdTools supports **multi-layer** annotation (e.g., tumour, edema, necrosis) and **multi-channel** within each layer (e.g., different anatomical structures painted in different colors).
722
+
723
+ #### 6.1 Active Layer & Channel
724
+
725
+ ```typescript
726
+ // Switch the active layer (where new strokes go)
727
+ nrrdTools.setActiveLayer('layer2');
728
+
729
+ // Switch the active channel within the current layer
730
+ nrrdTools.setActiveChannel(3); // channel 3 = blue by default
731
+
732
+ // Query current state
733
+ const currentLayer = nrrdTools.getActiveLayer(); // → 'layer2'
734
+ const currentChannel = nrrdTools.getActiveChannel(); // → 3
735
+ ```
736
+
737
+ #### 6.2 Layer Visibility
738
+
739
+ Toggle layers on/off in the composite canvas:
740
+
741
+ ```typescript
742
+ // Hide layer2 (e.g., edema) while keeping layer1 visible
743
+ nrrdTools.setLayerVisible('layer2', false);
744
+ nrrdTools.setLayerVisible('layer1', true);
745
+
746
+ // Query visibility
747
+ const layer2Visible = nrrdTools.isLayerVisible('layer2'); // → false
748
+
749
+ // Get all at once
750
+ const visibilityMap = nrrdTools.getLayerVisibility();
751
+ // → { layer1: true, layer2: false, layer3: true, layer4: true }
752
+ ```
753
+
754
+ #### Scenario: Eye-button toggle in UI
755
+
756
+ ```typescript
757
+ function onToggleLayerEye(layerId: string) {
758
+ const current = nrrdTools.isLayerVisible(layerId);
759
+ nrrdTools.setLayerVisible(layerId, !current);
760
+ }
761
+ ```
762
+
763
+ #### 6.3 Channel Visibility
764
+
765
+ Each layer can independently show/hide its channels:
766
+
767
+ ```typescript
768
+ // Hide channel 2 in layer1 (e.g., secondary annotation color)
769
+ nrrdTools.setChannelVisible('layer1', 2, false);
770
+
771
+ // Show it again
772
+ nrrdTools.setChannelVisible('layer1', 2, true);
773
+
774
+ // Query
775
+ const ch2Visible = nrrdTools.isChannelVisible('layer1', 2); // → true
776
+
777
+ // Get all channel visibility for all layers
778
+ const allChannelVis = nrrdTools.getChannelVisibility();
779
+ // → { layer1: { 1: true, 2: false, 3: true, ... }, layer2: { 1: true, ... }, ... }
780
+ ```
781
+
782
+ #### Scenario: Showing only the selected channel
783
+
784
+ ```typescript
785
+ function isolateChannel(layerId: string, targetChannel: number, totalChannels = 8) {
786
+ for (let ch = 1; ch <= totalChannels; ch++) {
787
+ nrrdTools.setChannelVisible(layerId, ch, ch === targetChannel);
788
+ }
789
+ }
790
+
791
+ // Show only channel 1 in layer1
792
+ isolateChannel('layer1', 1);
793
+
794
+ // Restore all
795
+ for (let ch = 1; ch <= 8; ch++) {
796
+ nrrdTools.setChannelVisible('layer1', ch, true);
797
+ }
798
+ ```
799
+
800
+ #### 6.4 Checking if a layer has annotations
801
+
802
+ ```typescript
803
+ if (nrrdTools.hasLayerData('layer2')) {
804
+ console.log('layer2 has annotated voxels — saving...');
805
+ await saveLayer('layer2');
806
+ } else {
807
+ console.log('layer2 is empty, skipping save');
808
+ }
809
+ ```
810
+
811
+ #### 6.5 Per-Layer Opacity
812
+
813
+ Each layer can have an independent opacity value (0.1–1.0), in addition to the existing global opacity (`setOpacity()`). The final rendering opacity is multiplicative: `globalAlpha × layerOpacity[layerId]`.
814
+
815
+ ```typescript
816
+ // Set layer2's opacity to 50%
817
+ nrrdTools.setLayerOpacity('layer2', 0.5);
818
+
819
+ // Read a layer's opacity
820
+ const opacity = nrrdTools.getLayerOpacity('layer2'); // → 0.5
821
+
822
+ // Read all layer opacities
823
+ const opacityMap = nrrdTools.getLayerOpacityMap();
824
+ // → { layer1: 1.0, layer2: 0.5, layer3: 1.0, layer4: 1.0 }
825
+ ```
826
+
827
+ > **Rendering Behavior**: Per-layer opacity is applied during `compositeAllLayers()` via `masterCtx.globalAlpha`. It does **not** modify the voxel data — it only affects display compositing.
828
+ >
829
+ > **Default**: All layers start with opacity `1.0` (fully opaque relative to globalAlpha).
830
+
831
+ ##### Scenario: Dimming background layers while annotating
832
+
833
+ ```typescript
834
+ // Dim layer1 and layer3, keep layer2 fully visible
835
+ nrrdTools.setLayerOpacity('layer1', 0.3);
836
+ nrrdTools.setLayerOpacity('layer3', 0.3);
837
+ nrrdTools.setLayerOpacity('layer2', 1.0);
838
+ ```
839
+
840
+ ##### UI Slider Integration
841
+
842
+ The `getSliderMeta("layerAlpha")` method returns the slider metadata for the active layer’s opacity:
843
+
844
+ ```typescript
845
+ const meta = nrrdTools.getSliderMeta('layerAlpha');
846
+ // → { value: 0.5, min: 0.1, max: 1, step: 0.01 }
847
+ ```
848
+
849
+ This is used by `OperationCtl.vue`’s "Layer Alpha" slider radio option.
850
+
851
+ #### 6.6 Reading and replacing a layer's whole volume
852
+
853
+ Three ways to move voxels in and out of a layer wholesale. They differ in what ends up on the
854
+ undo stack, which is the thing to pick on:
855
+
856
+ | Method | Undoable | Notes |
857
+ |--------|----------|-------|
858
+ | `getLayerVolume(id)` | — | Returns a **copy** of the voxel buffer, or `null` if the layer has no volume |
859
+ | `replaceLayerVolume(id, data, { undoable })` | opt-in | `undoable: true` records one Ctrl+Z step for the whole volume |
860
+ | `copyLayerData(src, dst)` | **no** | Writes the target buffer directly; leaves nothing for Ctrl+Z |
861
+
862
+ ```typescript
863
+ // Move a mask from layer2 to layer3, undoably
864
+ const voxels = nrrdTools.getLayerVolume('layer2');
865
+ if (voxels) nrrdTools.replaceLayerVolume('layer3', voxels, { undoable: true });
866
+ ```
867
+
868
+ `getLayerVolume` hands back a copy, not the live buffer: the renderer's own array must not be
869
+ mutated from outside, because nothing would invalidate the slice cache behind it.
870
+
871
+ ::: tip Prefer this pair over `copyLayerData` <Badge type="tip" text="3.10.4" />
872
+ `copyLayerData(src, dst)` still exists for the case it was written for — mirroring a backend
873
+ cascade (editing layer2 implies layer3) without a network round-trip. It is faster and it
874
+ preserves the target's colour map, but the clinician cannot undo it. If a person triggered the
875
+ change, go through `getLayerVolume` + `replaceLayerVolume` instead.
876
+ :::
877
+
878
+ `replaceLayerVolume` does **not** fire `onLayerVolumeReplaced` itself — the caller (a mask
879
+ upload flow, say) is expected to persist the new volume. The callback fires only later, if the
880
+ clinician undoes or redoes the replacement, because at that point the backend holds the newer
881
+ volume and has to be told to fall back.
882
+
883
+ #### 6.7 Erasing one channel — `clearChannel()` <Badge type="tip" text="3.10.2" />
884
+
885
+ ```typescript
886
+ nrrdTools.clearChannel('layer1', 3); // finding 3 goes; 1, 2 and 4 stay
887
+ ```
888
+
889
+ This is the third member of the clear family. `executeAction("clearActiveSliceMask")` takes
890
+ one slice and `executeAction("clearActiveLayerMask")` takes a whole layer — neither can take
891
+ a single label. Deleting one annotation needs exactly that, because its mask is one label
892
+ inside a volume it shares with every other annotation on the layer.
893
+
894
+ | Method | Scope |
895
+ |--------|-------|
896
+ | `clearActiveSlice()` | One slice, every channel |
897
+ | `clearChannel(id, ch)` | One channel, every slice |
898
+ | `clearActiveLayer()` | One layer, everything |
899
+ | `reset()` | Every layer, everything |
900
+
901
+ **It is undoable.** The deltas go onto the engine's own undo stack, so a mistaken clear is
902
+ recoverable for as long as the case stays open:
903
+
904
+ ```typescript
905
+ nrrdTools.clearChannel('layer1', 3);
906
+ nrrdTools.undo(); // finding 3 is back
907
+ ```
908
+
909
+ That is the reason to use it rather than writing zeros into the volume yourself and forcing
910
+ a repaint — an outside write bypasses the stack, and the clear becomes permanent.
911
+
912
+ Only slices that actually carry the label are touched, so a small annotation in a deep volume
913
+ costs one scan and a handful of `getMaskData` callbacks rather than one callback per slice.
914
+ If the channel is empty, nothing is pushed and nothing fires.
915
+
916
+ ::: warning Errors are thrown, not swallowed
917
+ - Unknown `layerId` → `Error` listing the known layers. It deliberately does **not** go
918
+ through `getVolumeForLayer`, which warns and falls back to the first layer; for a
919
+ destructive call that would quietly erase a different layer's annotation.
920
+ - `channel` outside `[1, 255]` → `RangeError` from `MaskVolume`. `0` means empty, so it is
921
+ not a channel you can clear.
922
+ :::
923
+
924
+ It is not part of `executeAction` because that signature is an action name plus an options
925
+ bag, and this needs two required arguments.
926
+
927
+ ---
928
+
929
+ ### 7. Channel Color Customization
930
+
931
+ Each layer has its own independent color map. Changing channel 3's color in `layer1` does **not** affect `layer2`.
932
+
933
+ #### ⚠️ Timing Requirement — Must call AFTER `setAllSlices()`
934
+
935
+ Color APIs require `MaskVolume` instances to exist inside `protectedData.maskData.volumes`. Calling them before `setAllSlices()` completes results in a **silent no-op** — the method hits the guard check, emits `console.warn`, and returns without doing anything. There is no thrown exception and no visible error.
936
+
937
+ ```typescript
938
+ // ❌ WRONG — onFinishedCopperInit fires when the Copper3D renderer is ready,
939
+ // but no NRRD images have been loaded yet.
940
+ // protectedData.maskData.volumes["layer1"] is undefined at this point.
941
+ // setChannelColor silently returns with only a console.warn.
942
+ const onFinishedCopperInit = (copperInitData) => {
943
+ nrrdTools.value = copperInitData.nrrdTools;
944
+ nrrdTools.value.setChannelColor('layer1', 1, { r: 25, g: 0, b: 0, a: 255 }); // ← no-op
945
+ };
946
+
947
+ // ✅ CORRECT — call after images are fully loaded and setAllSlices() has run
948
+ const handleAllImagesLoaded = (res) => {
949
+ // setAllSlices() is called internally before this callback fires
950
+ nrrdTools.value.setChannelColor('layer1', 1, { r: 25, g: 0, b: 0, a: 255 }); // ← works
951
+ };
952
+ ```
953
+
954
+ The internal guard inside `LayerChannelManager.setChannelColor()` (and all other color APIs) is:
955
+
956
+ ```typescript
957
+ const volume = this.protectedData.maskData.volumes[layerId];
958
+ if (!volume) {
959
+ console.warn(`setChannelColor: unknown layer "${layerId}"`); // fires silently
960
+ return; // exits — color is never applied
961
+ }
962
+ ```
963
+
964
+ `MaskVolumes` are created (with correct voxel dimensions) only inside `DataLoader.setAllSlices()`. Until that runs, the volumes map is empty.
965
+
966
+ #### Default Channel Colors
967
+
968
+ Channels **1–8** ship with a fixed, hand-picked palette:
969
+
970
+ | Channel | Color | Hex |
971
+ |---------|-------|-----|
972
+ | 1 | Emerald (Tumour) | `#10b981` |
973
+ | 2 | Rose (Edema) | `#f43f5e` |
974
+ | 3 | Blue (Necrosis) | `#3b82f6` |
975
+ | 4 | Amber (Enhancement) | `#fbbf24` |
976
+ | 5 | Fuchsia (Vessel) | `#d946ef` |
977
+ | 6 | Cyan (Additional) | `#06b6d4` |
978
+ | 7 | Orange (Auxiliary) | `#f97316` |
979
+ | 8 | Violet (Extended) | `#8b5cf6` |
980
+
981
+ ##### Channels 9–255 are generated <Badge type="tip" text="3.10.2" />
982
+
983
+ `MaskVolume` stores one byte per voxel and the value *is* the label, so the engine supports
984
+ **255 annotation channels** (`0` means empty). `Copper.MAX_ENGINE_CHANNEL` is that ceiling.
985
+
986
+ Channels past 8 get a colour from a golden-angle hue walk (137.508° per step) at fixed
987
+ saturation and lightness. Only the hue varies, deliberately: these sit on greyscale MRI,
988
+ where a mask that changes *brightness* between channels reads as a difference in the image
989
+ rather than in the annotation.
990
+
991
+ The eight seeds above are kept verbatim rather than regenerated, so a case annotated before
992
+ this change keeps exactly the colours it was read and signed off with.
993
+
994
+ ::: warning Distinct is not the same as distinguishable
995
+ Past roughly twenty channels, neighbouring hues stop being tellable apart by eye on a
996
+ greyscale background. That is a limit on how many findings your product should offer at
997
+ once — not on what the engine will hand back. All 255 are addressable; only the first ~20
998
+ are comfortably readable.
999
+ :::
1000
+
1001
+ ```typescript
1002
+ import { MAX_ENGINE_CHANNEL, CHANNEL_HEX_COLORS } from 'copper3d';
1003
+
1004
+ MAX_ENGINE_CHANNEL; // → 255
1005
+ CHANNEL_HEX_COLORS[3]; // → '#3b82f6' (delivered)
1006
+ CHANNEL_HEX_COLORS[42]; // → generated, stable across runs
1007
+ ```
1008
+
1009
+ All four palettes — `MASK_CHANNEL_COLORS`, `MASK_CHANNEL_CSS_COLORS` / `CHANNEL_COLORS`,
1010
+ `CHANNEL_HEX_COLORS`, and the AI-scratch pair — are extended the same way and are built
1011
+ eagerly, so `Object.entries` over them works as it always did.
1012
+
1013
+ #### 7.1 Set a single channel color
1014
+
1015
+ ```typescript
1016
+ // RGBAColor: { r, g, b, a } — all values 0-255
1017
+ nrrdTools.setChannelColor('layer1', 3, { r: 255, g: 128, b: 0, a: 255 }); // → orange
1018
+ ```
1019
+
1020
+ #### 7.2 Batch-set multiple channel colors (recommended)
1021
+
1022
+ One `reloadMasksFromVolume()` call instead of N calls — better performance:
1023
+
1024
+ ```typescript
1025
+ nrrdTools.setChannelColors('layer1', {
1026
+ 1: { r: 255, g: 80, b: 80, a: 255 }, // Soft red
1027
+ 2: { r: 80, g: 180, b: 255, a: 255 }, // Sky blue
1028
+ 3: { r: 255, g: 230, b: 50, a: 255 }, // Golden yellow
1029
+ });
1030
+ ```
1031
+
1032
+ #### 7.3 Apply the same color to all layers
1033
+
1034
+ ```typescript
1035
+ // Paint all layers' channel 1 in the same tumour color
1036
+ nrrdTools.setAllLayersChannelColor(1, { r: 0, g: 220, b: 100, a: 255 });
1037
+ ```
1038
+
1039
+ #### 7.4 Read current colors
1040
+
1041
+ ```typescript
1042
+ const rgba = nrrdTools.getChannelColor('layer2', 3);
1043
+ // → { r: 255, g: 128, b: 0, a: 255 }
1044
+
1045
+ const hex = nrrdTools.getChannelHexColor('layer2', 3);
1046
+ // → "#ff8000" — suitable for canvas fillStyle
1047
+
1048
+ const css = nrrdTools.getChannelCssColor('layer2', 3);
1049
+ // → "rgba(255,128,0,1.00)" — suitable for Vue :style binding
1050
+ ```
1051
+
1052
+ #### 7.5 Reset colors
1053
+
1054
+ ```typescript
1055
+ // Reset one channel in one layer
1056
+ nrrdTools.resetChannelColors('layer1', 3);
1057
+
1058
+ // Reset all channels in one layer
1059
+ nrrdTools.resetChannelColors('layer1');
1060
+
1061
+ // Reset everything across all layers
1062
+ nrrdTools.resetChannelColors();
1063
+ ```
1064
+
1065
+ #### Scenario: Color picker integration
1066
+
1067
+ ```typescript
1068
+ // User picks a new color in the UI color picker
1069
+ function onColorPicked(hexColor: string) {
1070
+ // Parse hex to RGBA (simple implementation)
1071
+ const r = parseInt(hexColor.slice(1, 3), 16);
1072
+ const g = parseInt(hexColor.slice(3, 5), 16);
1073
+ const b = parseInt(hexColor.slice(5, 7), 16);
1074
+
1075
+ const activeLayer = nrrdTools.getActiveLayer();
1076
+ const activeChannel = nrrdTools.getActiveChannel();
1077
+
1078
+ nrrdTools.setChannelColor(activeLayer, activeChannel, { r, g, b, a: 255 });
1079
+ }
1080
+ ```
1081
+
1082
+ #### Scenario: Vue UI reactivity after color change
1083
+
1084
+ After calling `setChannelColor()`, the canvas re-renders automatically.
1085
+ But Vue computed properties that show the color need a manual nudge:
1086
+
1087
+ ```typescript
1088
+ // In your composable or component
1089
+ const colorVersion = ref(0);
1090
+
1091
+ const channelCssColor = computed(() => {
1092
+ colorVersion.value; // subscribe to version
1093
+ return nrrdTools.value?.getChannelCssColor(activeLayer.value, activeChannel.value) ?? '#00ff00';
1094
+ });
1095
+
1096
+ function refreshColors() {
1097
+ colorVersion.value++; // forces recompute
1098
+ }
1099
+
1100
+ // After setting color:
1101
+ nrrdTools.value.setChannelColor('layer1', 2, { r: 255, g: 0, b: 0, a: 255 });
1102
+ refreshColors();
1103
+ ```
1104
+
1105
+ ---
1106
+
1107
+ ### 8. Undo / Redo
1108
+
1109
+ NrrdTools maintains a per-layer undo stack (max 50 entries). Every completed brush stroke pushes a delta snapshot.
1110
+
1111
+ ```typescript
1112
+ // Undo the last stroke on the active layer
1113
+ nrrdTools.undo();
1114
+
1115
+ // Redo the last undone stroke
1116
+ nrrdTools.redo();
1117
+ ```
1118
+
1119
+ #### Scenario: Keyboard shortcut binding
1120
+
1121
+ ```typescript
1122
+ window.addEventListener('keydown', (e) => {
1123
+ if (e.ctrlKey && e.key === 'z') nrrdTools.undo();
1124
+ if (e.ctrlKey && e.key === 'y') nrrdTools.redo();
1125
+ });
1126
+ ```
1127
+
1128
+ > The built-in keyboard system also handles undo/redo (default: `z` and `y` without Ctrl).
1129
+ > See [Keyboard Shortcuts](#9-keyboard-shortcuts) for configuring this.
1130
+
1131
+ ---
1132
+
1133
+ ### 9. Keyboard Shortcuts
1134
+
1135
+ #### Default bindings
1136
+
1137
+ | Action | Default Key |
1138
+ |--------|-------------|
1139
+ | Draw mode | `Shift` (hold) |
1140
+ | Undo | `z` |
1141
+ | Redo | `y` |
1142
+ | Contrast adjust | `Ctrl` / `Meta` (hold) |
1143
+ | Crosshair | `s` |
1144
+ | Sphere mode | `q` |
1145
+ | Mouse wheel | Zoom |
1146
+ | Scroll:Zoom shortcut | `Ctrl+1` |
1147
+ | Scroll:Slice shortcut | `Ctrl+2` |
1148
+
1149
+ #### Reading current settings
1150
+
1151
+ ```typescript
1152
+ const settings = nrrdTools.getKeyboardSettings();
1153
+ console.log(settings);
1154
+ // {
1155
+ // draw: 'Shift',
1156
+ // undo: 'z',
1157
+ // redo: 'y',
1158
+ // contrast: ['Control', 'Meta'],
1159
+ // crosshair: 's',
1160
+ // mouseWheel: 'Scroll:Zoom'
1161
+ // }
1162
+ ```
1163
+
1164
+ #### Customizing bindings
1165
+
1166
+ ```typescript
1167
+ nrrdTools.setKeyboardSettings({
1168
+ undo: 'u', // Remap undo to 'u'
1169
+ mouseWheel: 'Scroll:Slice', // Mouse wheel scrolls slices instead of zooming
1170
+ });
1171
+ ```
1172
+
1173
+ #### Scenario: Form input focus — suppressing shortcuts
1174
+
1175
+ When a user types in an input field, you don't want tool shortcuts firing:
1176
+
1177
+ ```typescript
1178
+ inputElement.addEventListener('focus', () => {
1179
+ nrrdTools.enterKeyboardConfig(); // Suppress all tool shortcuts
1180
+ });
1181
+
1182
+ inputElement.addEventListener('blur', () => {
1183
+ nrrdTools.exitKeyboardConfig(); // Restore shortcuts
1184
+ });
1185
+ ```
1186
+
1187
+ #### Enabling / disabling contrast shortcut independently
1188
+
1189
+ ```typescript
1190
+ // Disable only the contrast (window/level) keyboard shortcut
1191
+ nrrdTools.setContrastShortcutEnabled(false);
1192
+
1193
+ // Check status
1194
+ const isEnabled = nrrdTools.isContrastShortcutEnabled(); // → false
1195
+
1196
+ // Re-enable
1197
+ nrrdTools.setContrastShortcutEnabled(true);
1198
+ ```
1199
+
1200
+ ---
1201
+
1202
+ ### 10. Display & Canvas Control
1203
+
1204
+ #### Mask render mode — fill or outline <Badge type="tip" text="3.10.3" />
1205
+
1206
+ ```typescript
1207
+ nrrdTools.setMaskRenderMode('outline'); // stroke only the boundary
1208
+ nrrdTools.setMaskRenderMode('fill'); // paint the silhouette (default)
1209
+ const mode = nrrdTools.getMaskRenderMode(); // → 'fill' | 'outline'
1210
+ ```
1211
+
1212
+ `"outline"` strokes only each mask's edge, leaving the interior clear so the tissue
1213
+ underneath stays readable — which is the point: a clinician can see what they annotated
1214
+ *and* what they annotated it on, at the same time.
1215
+
1216
+ ::: tip It is a display decision and nothing else
1217
+ `MaskVolume` is not read differently and not written at all. What is stored, uploaded,
1218
+ exported and undone is the complete mask either way, so switching mode can never lose data.
1219
+ :::
1220
+
1221
+ Applies to **every layer and channel at once** — there is no per-layer variant. It repaints
1222
+ immediately, the same way `setChannelVisible` does, so the change is on screen the moment you
1223
+ set it rather than at the next slice scrub.
1224
+
1225
+ The default is `"fill"`, which is what every existing caller already got.
1226
+
1227
+ **Cost.** The boundary is extracted per visible label and cached alongside the fill path for
1228
+ that slice. Switching mode costs one extraction per visible label the first time and is a
1229
+ cache hit every time after; a session that never leaves fill mode never builds an outline at
1230
+ all. Outline extraction scales with the *perimeter* rather than the area, so it is cheaper
1231
+ than the fill it replaces.
1232
+
1233
+ ::: warning Drawing still works on the solid mask
1234
+ The pencil and eraser rebuild a slice from what is on the layer canvas, so they render the
1235
+ layer filled for the duration of a stroke regardless of the display mode, and the mode comes
1236
+ back at pointer-up. You do not need to leave outline mode to annotate — but if you write your
1237
+ own tool that bakes a canvas back into a volume, it must render filled too (see the
1238
+ [architecture guide](./segmentation-module)).
1239
+ :::
1240
+
1241
+ #### Canvas size scaling
1242
+
1243
+ Set the base display size multiplier (1–8). Larger values use more GPU memory but give sharper annotations:
1244
+
1245
+ ```typescript
1246
+ nrrdTools.setBaseDrawDisplayCanvasesSize(2); // 2× base resolution
1247
+ ```
1248
+
1249
+ #### Reading image metadata
1250
+
1251
+ ```typescript
1252
+ // Voxel dimensions [width, height, depth]
1253
+ const dims = nrrdTools.getCurrentImageDimension();
1254
+ // → [512, 512, 256]
1255
+
1256
+ // Physical spacing (mm per voxel, from NRRD header)
1257
+ const spacing = nrrdTools.getVoxelSpacing();
1258
+ // → [0.488, 0.488, 1.0]
1259
+
1260
+ // World-space origin
1261
+ const origin = nrrdTools.getSpaceOrigin();
1262
+ // → [-125.0, -125.0, -127.5]
1263
+
1264
+ // Max slice count per axis
1265
+ const maxSlices = nrrdTools.getMaxSliceNum();
1266
+ // → [512, 512, 256] (one per axis)
1267
+
1268
+ // Current viewing state
1269
+ const { currentSliceIndex, contrastIndex } = nrrdTools.getCurrentSlicesNumAndContrastNum();
1270
+ ```
1271
+
1272
+ #### Accessing internal canvases
1273
+
1274
+ ```typescript
1275
+ // The topmost interactive canvas (mouse/pen events target here)
1276
+ const drawingCanvas = nrrdTools.getDrawingCanvas();
1277
+
1278
+ // The inner main-area container div (dynamically created by NrrdTools, NOT the original container passed to constructor)
1279
+ const container = nrrdTools.getContainer();
1280
+
1281
+ // Raw NrrdState (all internal state fields, grouped by semantic sub-objects)
1282
+ const states = nrrdTools.getNrrdToolsSettings();
1283
+ console.log(states.image.layers); // ["layer1", "layer2", ...]
1284
+ console.log(states.image.dimensions); // [512, 512, 256]
1285
+ ```
1286
+
1287
+ #### Accessing full mask data
1288
+
1289
+ ```typescript
1290
+ // All MaskVolume data structures
1291
+ const maskData = nrrdTools.getMaskData();
1292
+ // maskData.volumes is Record<string, MaskVolume>
1293
+ ```
1294
+
1295
+ ---
1296
+
1297
+ ### 11. Reading State & Diagnostics
1298
+
1299
+ ```typescript
1300
+ // Full snapshot of current state
1301
+ const state = nrrdTools.getNrrdToolsSettings();
1302
+
1303
+ // Active layer / channel
1304
+ const layer = nrrdTools.getActiveLayer();
1305
+ const channel = nrrdTools.getActiveChannel();
1306
+
1307
+ // Visibility maps
1308
+ const layerVis = nrrdTools.getLayerVisibility();
1309
+ const channelVis = nrrdTools.getChannelVisibility();
1310
+
1311
+ // Check if any real annotation exists in a layer
1312
+ const hasTumour = nrrdTools.hasLayerData('layer1');
1313
+
1314
+ // Get current channel color as hex
1315
+ const hex = nrrdTools.getChannelHexColor('layer1', 1); // → "#10b981"
1316
+
1317
+ // Keyboard settings
1318
+ const keys = nrrdTools.getKeyboardSettings();
1319
+ ```
1320
+
1321
+ ---
1322
+
1323
+ ### 12. Advanced Scenarios
1324
+
1325
+ #### Scenario A: Complete multi-layer initialization from scratch
1326
+
1327
+ ```typescript
1328
+ async function initAnnotationTool(container: HTMLDivElement, allSlices: any[]) {
1329
+ // Create tool with 4 layers
1330
+ const nrrdTools = new Copper.NrrdTools(container, {
1331
+ layers: ['layer1', 'layer2', 'layer3', 'layer4']
1332
+ });
1333
+
1334
+ // Attach GUI
1335
+ nrrdTools.setupGUI(gui as any);
1336
+
1337
+ // Attach contrast drag
1338
+ nrrdTools.enableContrastDragEvents((step, towards) => {
1339
+ console.log('Windowing:', towards, step);
1340
+ });
1341
+
1342
+ // Load image volume
1343
+ nrrdTools.reset();
1344
+ nrrdTools.setAllSlices(allSlices);
1345
+
1346
+ // Register callbacks
1347
+ nrrdTools.drag({ getSliceNum: (idx) => updateSliceUI(idx) });
1348
+
1349
+ nrrdTools.draw({
1350
+ getMaskData: (sliceData, layerId, channelId, sliceIndex, axis, w, h, clearFlag) => {
1351
+ syncSliceToBackend({ sliceData, layerId, channelId, sliceIndex, axis, clearFlag });
1352
+ },
1353
+ onClearLayerVolume: (layerId) => {
1354
+ notifyBackendCleared(layerId);
1355
+ },
1356
+ });
1357
+
1358
+ // Connect to render loop
1359
+ scene.addPreRenderCallbackFunction(nrrdTools.start);
1360
+
1361
+ return nrrdTools;
1362
+ }
1363
+ ```
1364
+
1365
+ #### Scenario B: Load existing annotations and apply custom color scheme
1366
+
1367
+ ```typescript
1368
+ async function loadAndColorCase(nrrdTools: Copper.NrrdTools, caseId: string) {
1369
+ // 1. Load existing NIfTI masks
1370
+ const masks = await fetchCaseMasks(caseId);
1371
+ const layerVoxels = new Map<string, Uint8Array>();
1372
+ for (const [layerId, data] of Object.entries(masks)) {
1373
+ layerVoxels.set(layerId, data);
1374
+ }
1375
+ nrrdTools.setMasksFromNIfTI(layerVoxels);
1376
+
1377
+ // 2. Apply per-layer color schemes
1378
+ nrrdTools.setChannelColors('layer1', {
1379
+ 1: { r: 0, g: 200, b: 80, a: 255 }, // Tumour core — green
1380
+ 2: { r: 255, g: 200, b: 0, a: 255 }, // Tumour ring — yellow
1381
+ });
1382
+
1383
+ nrrdTools.setChannelColors('layer2', {
1384
+ 1: { r: 255, g: 60, b: 60, a: 200 }, // Edema — semi-transparent red
1385
+ });
1386
+
1387
+ // 3. Set initial active state
1388
+ nrrdTools.setActiveLayer('layer1');
1389
+ nrrdTools.setActiveChannel(1);
1390
+ }
1391
+ ```
1392
+
1393
+ #### Scenario C: Switching cases — full reset
1394
+
1395
+ ```typescript
1396
+ async function switchCase(nrrdTools: Copper.NrrdTools, newCaseData: ICaseData) {
1397
+ // Reset annotation volumes
1398
+ nrrdTools.reset();
1399
+
1400
+ // Load new image slices (from Copper's scene loader result)
1401
+ nrrdTools.setAllSlices(newCaseData.slices);
1402
+
1403
+ // Reset colors to defaults
1404
+ nrrdTools.resetChannelColors();
1405
+
1406
+ // Make all layers and channels visible
1407
+ for (const layerId of ['layer1', 'layer2', 'layer3', 'layer4']) {
1408
+ nrrdTools.setLayerVisible(layerId, true);
1409
+ for (let ch = 1; ch <= 8; ch++) {
1410
+ nrrdTools.setChannelVisible(layerId, ch, true);
1411
+ }
1412
+ }
1413
+
1414
+ // Start fresh on layer1, channel1
1415
+ nrrdTools.setActiveLayer('layer1');
1416
+ nrrdTools.setActiveChannel(1);
1417
+
1418
+ // Load existing masks if available
1419
+ if (newCaseData.hasExistingMasks) {
1420
+ nrrdTools.setMasksFromNIfTI(newCaseData.layerVoxels);
1421
+ }
1422
+ }
1423
+ ```
1424
+
1425
+ #### Scenario D: Save workflow with dirty-layer detection
1426
+
1427
+ ```typescript
1428
+ async function onSave(nrrdTools: Copper.NrrdTools, caseId: string) {
1429
+ const layers = ['layer1', 'layer2', 'layer3', 'layer4'];
1430
+
1431
+ for (const layerId of layers) {
1432
+ if (!nrrdTools.hasLayerData(layerId)) {
1433
+ console.log(`${layerId} is empty — initializing blank NIfTI on backend`);
1434
+ await initBlankLayerOnBackend(caseId, layerId);
1435
+ } else {
1436
+ console.log(`${layerId} has data — saving...`);
1437
+ await saveLayerToBackend(caseId, layerId);
1438
+ }
1439
+ }
1440
+ }
1441
+ ```
1442
+
1443
+ #### Scenario E: AI segmentation result — write back to volume
1444
+
1445
+ After receiving a segmentation result from a backend AI model, write it directly into a layer:
1446
+
1447
+ ```typescript
1448
+ async function applyAIResult(nrrdTools: Copper.NrrdTools, layerId: string) {
1449
+ // Fetch AI-generated NIfTI from backend
1450
+ const response = await fetch(`/api/ai-result/${layerId}`);
1451
+ const buffer = await response.arrayBuffer();
1452
+ const voxels = new Uint8Array(buffer);
1453
+
1454
+ // Write directly into the target layer volume
1455
+ const layerVoxels = new Map<string, Uint8Array>([[layerId, voxels]]);
1456
+ nrrdTools.setMasksFromNIfTI(layerVoxels);
1457
+
1458
+ // Optionally switch to that layer so user sees the result
1459
+ nrrdTools.setActiveLayer(layerId);
1460
+ }
1461
+ ```
1462
+
1463
+ #### Scenario F: Dynamic keyboard remap from user settings
1464
+
1465
+ ```typescript
1466
+ interface UserPreferences {
1467
+ undoKey: string;
1468
+ redoKey: string;
1469
+ sliceScrollMode: 'zoom' | 'slice';
1470
+ }
1471
+
1472
+ function applyUserKeyboardPreferences(nrrdTools: Copper.NrrdTools, prefs: UserPreferences) {
1473
+ nrrdTools.setKeyboardSettings({
1474
+ undo: prefs.undoKey,
1475
+ redo: prefs.redoKey,
1476
+ mouseWheel: prefs.sliceScrollMode === 'slice' ? 'Scroll:Slice' : 'Scroll:Zoom',
1477
+ });
1478
+ }
1479
+
1480
+ // Example: Apply on preference change
1481
+ applyUserKeyboardPreferences(nrrdTools, {
1482
+ undoKey: 'u',
1483
+ redoKey: 'r',
1484
+ sliceScrollMode: 'slice',
1485
+ });
1486
+ ```
1487
+
1488
+ #### Scenario G: Read layer colors to build a color legend
1489
+
1490
+ ```typescript
1491
+ function buildColorLegend(nrrdTools: Copper.NrrdTools, layerId: string) {
1492
+ const legend = [];
1493
+ for (let ch = 1; ch <= 8; ch++) {
1494
+ legend.push({
1495
+ channel: ch,
1496
+ cssColor: nrrdTools.getChannelCssColor(layerId, ch),
1497
+ hexColor: nrrdTools.getChannelHexColor(layerId, ch),
1498
+ rgba: nrrdTools.getChannelColor(layerId, ch),
1499
+ });
1500
+ }
1501
+ return legend;
1502
+ }
1503
+
1504
+ // → [
1505
+ // { channel: 1, cssColor: 'rgba(16,185,129,1.00)', hexColor: '#10b981', rgba: { r:16, g:185, b:129, a:255 } },
1506
+ // { channel: 2, cssColor: 'rgba(244,63,94,1.00)', hexColor: '#f43f5e', rgba: { r:244, g:63, b:94, a:255 } },
1507
+ // ...
1508
+ // ]
1509
+ ```
1510
+
1511
+ #### Scenario H: Clearing annotations
1512
+
1513
+ There are different levels of clearing data depending on the use case:
1514
+
1515
+ ```typescript
1516
+ // 1. Clear ALL data across ALL layers comprehensively (typically used when switching cases)
1517
+ // This clears all volumes, undo histories, UI canvases, index parameters, and sphere data globally.
1518
+ nrrdTools.reset();
1519
+
1520
+ // 2. Clear all annotations on the currently active layer across its entire 3D volume
1521
+ // This clears the active layer's MaskVolume, clears its undo/redo history, and re-renders the canvas.
1522
+ // It also triggers the `onClearLayerVolume` callback so you can notify the backend.
1523
+ nrrdTools.clearActiveLayer();
1524
+
1525
+ // 3. Clear the mask ONLY on the currently viewed 2D slice for the active layer
1526
+ // This removes annotations specifically on the current slice index and orientation.
1527
+ // It records an undo operation to allow rollback.
1528
+ nrrdTools.clearActiveSlice();
1529
+ ```
1530
+
1531
+ ---
1532
+
1533
+ ### 13. Vue 3 Integration Pattern
1534
+
1535
+ The recommended pattern in Vue 3 is to distribute the `NrrdTools` instance via a Vue event emitter after NRRD loading completes, so any descendant component can access it.
1536
+
1537
+ #### LeftPanel (creator)
1538
+
1539
+ ```vue
1540
+ <script setup lang="ts">
1541
+ import * as Copper from 'copper3d';
1542
+ import emitter from '@/plugins/custom-emitter';
1543
+
1544
+ let nrrdTools: Copper.NrrdTools | undefined;
1545
+
1546
+ onMounted(() => {
1547
+ nrrdTools = new Copper.NrrdTools(canvasContainer.value as HTMLDivElement, {
1548
+ layers: ['layer1', 'layer2', 'layer3', 'layer4']
1549
+ });
1550
+ });
1551
+
1552
+ // After all NRRD files are loaded by the Copper scene:
1553
+ function onAllImagesLoaded(allSlices: any[]) {
1554
+ nrrdTools!.reset();
1555
+ nrrdTools!.setAllSlices(allSlices);
1556
+
1557
+ nrrdTools!.drag({ getSliceNum: (idx) => emit('sliceChanged', idx) });
1558
+
1559
+ nrrdTools!.draw({
1560
+ getMaskData: (sliceData, layerId, channelId, sliceIndex, axis, w, h, clearFlag) => {
1561
+ emit('maskDataUpdated', { sliceData, layerId, channelId, sliceIndex, axis, w, h, clearFlag });
1562
+ },
1563
+ onClearLayerVolume: (layerId) => emit('layerCleared', layerId),
1564
+ });
1565
+
1566
+ scene!.addPreRenderCallbackFunction(nrrdTools!.start);
1567
+
1568
+ // Broadcast to all other components
1569
+ emitter.emit('Core:NrrdTools', nrrdTools!);
1570
+ emitter.emit('Segmentation:FinishLoadAllCaseImages');
1571
+ }
1572
+ </script>
1573
+ ```
1574
+
1575
+ #### Annotation Control Panel (consumer)
1576
+
1577
+ ```vue
1578
+ <script setup lang="ts">
1579
+ import * as Copper from 'copper3d';
1580
+ import emitter from '@/plugins/custom-emitter';
1581
+
1582
+ const nrrdTools = ref<Copper.NrrdTools>();
1583
+
1584
+ onMounted(() => {
1585
+ emitter.on('Core:NrrdTools', (tools: Copper.NrrdTools) => {
1586
+ nrrdTools.value = tools;
1587
+ });
1588
+
1589
+ emitter.on('Segmentation:FinishLoadAllCaseImages', () => {
1590
+ // Safe to call all APIs now — MaskVolume is initialized
1591
+ syncStateFromTools();
1592
+ });
1593
+ });
1594
+
1595
+ function syncStateFromTools() {
1596
+ if (!nrrdTools.value) return;
1597
+ activeLayer.value = nrrdTools.value.getActiveLayer();
1598
+ activeChannel.value = nrrdTools.value.getActiveChannel();
1599
+ layerVisibility.value = nrrdTools.value.getLayerVisibility();
1600
+ channelVisibility.value = nrrdTools.value.getChannelVisibility();
1601
+ }
1602
+
1603
+ function onChannelColorPicked(hex: string) {
1604
+ if (!nrrdTools.value) return;
1605
+ const r = parseInt(hex.slice(1,3), 16);
1606
+ const g = parseInt(hex.slice(3,5), 16);
1607
+ const b = parseInt(hex.slice(5,7), 16);
1608
+ nrrdTools.value.setChannelColor(activeLayer.value, activeChannel.value, { r, g, b, a: 255 });
1609
+ refreshColors(); // bump colorVersion to re-trigger computed
1610
+ }
1611
+ </script>
1612
+ ```
1613
+
1614
+ ---
1615
+
1616
+ ### 14. Type Reference
1617
+
1618
+ ```typescript
1619
+ // Color type used by all channel color APIs
1620
+ interface RGBAColor {
1621
+ r: number; // 0-255
1622
+ g: number; // 0-255
1623
+ b: number; // 0-255
1624
+ a: number; // 0-255 (255 = fully opaque)
1625
+ }
1626
+
1627
+ // Batch color map for setChannelColors()
1628
+ type ChannelColorMap = Record<number, RGBAColor>; // key = channel number, 1-255
1629
+
1630
+ // draw() options
1631
+ interface IDrawOpts {
1632
+ getMaskData?: (
1633
+ sliceData: Uint8Array,
1634
+ layerId: string,
1635
+ channelId: number,
1636
+ sliceIndex: number,
1637
+ axis: 'x' | 'y' | 'z',
1638
+ width: number,
1639
+ height: number,
1640
+ clearFlag?: boolean
1641
+ ) => void;
1642
+ onClearLayerVolume?: (layerId: string) => void;
1643
+ getSphereData?: (sphereOrigin: number[], sphereRadius: number) => void;
1644
+ getCalculateSpherePositionsData?: (
1645
+ tumourOrigin: ICommXYZ | null,
1646
+ skinOrigin: ICommXYZ | null,
1647
+ ribOrigin: ICommXYZ | null,
1648
+ nippleOrigin: ICommXYZ | null,
1649
+ axis: 'x' | 'y' | 'z'
1650
+ ) => void;
1651
+ }
1652
+
1653
+ // drag() options
1654
+ interface IDragOpts {
1655
+ showNumber?: boolean;
1656
+ getSliceNum?: (sliceIndex: number, contrastIndex: number) => void;
1657
+ }
1658
+
1659
+ // Tool mode (used by setMode/getMode)
1660
+ type ToolMode = "pencil" | "brush" | "eraser" | "sphere" | "calculator" | "sphereBrush" | "sphereEraser";
1661
+
1662
+ // Mask render mode (used by setMaskRenderMode/getMaskRenderMode)
1663
+ type MaskRenderMode = "fill" | "outline";
1664
+
1665
+ // Keyboard settings
1666
+ interface IKeyBoardSettings {
1667
+ draw: string;
1668
+ undo: string;
1669
+ redo: string;
1670
+ contrast: string[]; // always an array, e.g. ["Control", "Meta"]
1671
+ crosshair: string;
1672
+ sphere: string;
1673
+ mouseWheel: 'Scroll:Zoom' | 'Scroll:Slice';
1674
+ }
1675
+
1676
+ // 3D coordinate (used in sphere position callbacks)
1677
+ interface ICommXYZ {
1678
+ x: number;
1679
+ y: number;
1680
+ z: number;
1681
+ }
1682
+ ```
1683
+
1684
+ #### Common type aliases
1685
+
1686
+ ```typescript
1687
+ type LayerId = 'layer1' | 'layer2' | 'layer3' | 'layer4'; // or any string
1688
+ type ChannelValue = number; // 0 = empty/erased, 1..MAX_ENGINE_CHANNEL (255)
1689
+ ```
1690
+
1691
+ ::: tip `ChannelValue` is a bare `number` since 3.10.2
1692
+ It used to be the union `1 | 2 | ... | 8`. That union cannot be written for 255 members, so
1693
+ the compile-time error on a bad literal is gone — you now get a `RangeError` from
1694
+ `MaskVolume` at runtime instead. That is a genuine loss and it is the price of the range:
1695
+ storage is one byte per voxel whose value *is* the label, so the engine has no standing to
1696
+ cap it below what the byte allows. Capping it lower is your product's call, not the engine's.
1697
+ :::
1698
+
1699
+ ---
1700
+
1701
+ ### API Summary
1702
+
1703
+ | Category | Method | Description |
1704
+ |----------|--------|-------------|
1705
+ | **Constructor** | `new NrrdTools(container, { layers })` | Create instance with optional layer config |
1706
+ | **Setup** | `drag(opts?)` | Enable slice-drag navigation |
1707
+ | | `draw(opts?)` | Bind annotation callbacks |
1708
+ | | `setupGUI(gui)` | Connect dat.GUI panel |
1709
+ | | `enableContrastDragEvents(cb)` | Enable Ctrl+drag windowing |
1710
+ | | `setDisplaySliceIndexPanel(el)` | Show slice index in a panel |
1711
+ | | `setBaseDrawDisplayCanvasesSize(n)` | Set canvas resolution multiplier (1-8) |
1712
+ | **Data** | `reset()` | Reset all volumes, undo histories, canvases, and sphere data |
1713
+ | | `clearActiveLayer()` | Clear annotations and undo history for the *currently active layer* |
1714
+ | | `clearActiveSlice()` | Clear annotations exclusively on the *currently viewed slice* of the active layer |
1715
+ | | `clearChannel(id, ch)` | Erase one channel across a whole layer, undoably. Throws on an unknown layer or a channel outside [1, 255] |
1716
+ | | `setAllSlices(slices)` | Load NRRD slices, init MaskVolumes |
1717
+ | | `setMasksFromNIfTI(map, bar?)` | Load saved NIfTI voxel data (each buffer must be registered via `registerNiftiMaskGrid` first, or it is refused) |
1718
+ | | `registerNiftiMaskGrid(data, dims)` | *(module export, not a method)* Record a mask buffer's NIfTI voxel grid so `setMasksFromNIfTI` can validate it |
1719
+ | | `notifyUser` | *(assignable property)* How engine messages reach the reader; defaults to a console write |
1720
+ | **Contrast Series** | `addSkip(index)` | Hide one contrast (index into the full contrast list) |
1721
+ | | `removeSkip(index)` | Show a previously hidden contrast |
1722
+ | | `setSkips(entries)` | Batched `addSkip`/`removeSkip` — one refresh for many changes |
1723
+ | | `setContrastIndex(index)` | Move to a contrast **within `displaySlices`**, without moving the slice |
1724
+ | | `commitSkipsAndContrast(entries, i)` | Batched `setSkips` + `setContrastIndex` — one refresh |
1725
+ | | `commitSeriesLoad(slices, entries, i)` | Case-load completion: swap series + reconcile skips + land on contrast, one refresh |
1726
+ | | `switchAllSlicesArrayData(slices)` | Swap the loaded series (resets slice index / zoom / pan) |
1727
+ | | `switchSlicesPreservingView(slices)` | Swap the loaded series, keeping slice index, zoom and pan |
1728
+ | **Render** | `start` | Frame callback — pass to render loop |
1729
+ | **Layer** | `setActiveLayer(id)` | Switch drawing target layer |
1730
+ | | `getActiveLayer()` | Read current layer |
1731
+ | | `setLayerVisible(id, bool)` | Toggle layer in composite view |
1732
+ | | `isLayerVisible(id)` | Query layer visibility |
1733
+ | | `getLayerVisibility()` | All layer visibility map |
1734
+ | | `hasLayerData(id)` | Check if layer has non-zero voxels |
1735
+ | | `getLayerVolume(id)` | A **copy** of the layer's voxel buffer, or `null` |
1736
+ | | `replaceLayerVolume(id, data, opts?)` | Replace the whole buffer; `{ undoable: true }` records one Ctrl+Z step |
1737
+ | | `copyLayerData(src, dst)` | Copy voxels between layers — **not** undoable; keeps the target's colour map |
1738
+ | | `setLayerOpacity(id, opacity)` | Set per-layer opacity (0.1–1.0), triggers re-render |
1739
+ | | `getLayerOpacity(id)` | Get opacity for a specific layer |
1740
+ | | `getLayerOpacityMap()` | Get all per-layer opacity values |
1741
+ | **Sphere** | `setActiveSphereType(type)` | Set active sphere type (`'tumour'`/`'skin'`/`'nipple'`/`'ribcage'`), updates brush color |
1742
+ | | `getActiveSphereType()` | Read current sphere type |
1743
+ | **Channel** | `setActiveChannel(ch)` | Switch drawing target channel |
1744
+ | | `getActiveChannel()` | Read current channel |
1745
+ | | `setChannelVisible(id, ch, bool)` | Toggle channel visibility in a layer |
1746
+ | | `isChannelVisible(id, ch)` | Query channel visibility |
1747
+ | | `getChannelVisibility()` | All channel visibility map |
1748
+ | **Color** | `setChannelColor(id, ch, rgba)` | Set one channel color in one layer |
1749
+ | | `setChannelColors(id, map)` | Batch-set colors in one layer |
1750
+ | | `setAllLayersChannelColor(ch, rgba)` | Set one channel color across all layers |
1751
+ | | `getChannelColor(id, ch)` | Read RGBA |
1752
+ | | `getChannelHexColor(id, ch)` | Read Hex string |
1753
+ | | `getChannelCssColor(id, ch)` | Read CSS rgba() string |
1754
+ | | `resetChannelColors(id?, ch?)` | Reset to defaults |
1755
+ | | `MAX_ENGINE_CHANNEL` | *(module export)* Highest storable label, `255` |
1756
+ | **Tool Mode** | `setMode(mode)` | Switch tool mode: `"pencil"` / `"brush"` / `"eraser"` / `"sphere"` / `"calculator"` / `"sphereBrush"` / `"sphereEraser"` |
1757
+ | | `getMode()` | Read current tool mode |
1758
+ | | `isCalculatorActive()` | Check if calculator (distance) mode is active |
1759
+ | | `setAnnotationSuspended(bool)` | Block all mask-writing input; scrubbing, zoom, pan and crosshair stay live |
1760
+ | | `isAnnotationSuspended()` | Query the suspension state |
1761
+ | **Sphere Brush** | `setSphereBrushRadius(radius)` | Set sphere brush/eraser radius [1, 50] |
1762
+ | | `getSphereBrushRadius()` | Read current sphere brush/eraser radius |
1763
+ | **Drawing** | `setOpacity(value)` | Set mask overlay opacity [0.1, 1] |
1764
+ | | `getOpacity()` | Read current opacity |
1765
+ | | `setMaskRenderMode(mode)` | `"fill"` or `"outline"` for every layer/channel; repaints immediately. Display only — the stored mask is unchanged |
1766
+ | | `getMaskRenderMode()` | Read the current render mode |
1767
+ | | `setBrushSize(size)` | Set brush/eraser size [5, 50], updates cursor |
1768
+ | | `getBrushSize()` | Read current brush size |
1769
+ | | `setPencilColor(hex)` | Set pencil stroke color (hex string) |
1770
+ | | `getPencilColor()` | Read current pencil color |
1771
+ | **Contrast** | `setWindowHigh(value)` | Set window high (image contrast), call `finishWindowAdjustment()` after drag |
1772
+ | | `setWindowLow(value)` | Set window low (image center) |
1773
+ | | `finishWindowAdjustment()` | Repaint all contrast slices after drag ends |
1774
+ | | `getSliderMeta(key)` | Get slider min/max/step/value for UI config (`"globalAlpha"`, `"layerAlpha"`, `"brushAndEraserSize"`, etc.) |
1775
+ | **Actions** | `executeAction(action)` | Run named action: `"undo"`, `"redo"`, `"clearActiveSliceMask"`, `"clearActiveLayerMask"`, `"resetZoom"`, `"downloadCurrentMask"`, `"gaussianSmooth"` |
1776
+ | **Gaussian Smoothing** | `GaussianSmoother.gaussianSmooth3D(volume, channel, sigma?, spacing?)` | Apply 3D Gaussian smoothing to a MaskVolume channel |
1777
+ | | `GaussianSmoother.generateKernel1D(sigma)` | Generate a normalized 1D Gaussian kernel |
1778
+ | **Navigation** | `setSliceOrientation(axis)` | Switch viewing axis `"x"` / `"y"` / `"z"`; extracts the plane on demand if the load skipped it |
1779
+ | | `setSliceMoving(step)` | Step the current slice by `step` (coalesced into one `requestAnimationFrame`) |
1780
+ | | `setMainAreaSize(factor)` | Set the main-area zoom factor [1, 8] and reposition the paint area |
1781
+ | | `setCalculateDistanceSphere(x, y, slice, type)` | Programmatically place a calculator sphere (simulates full click flow: record origin → draw → write to volume) |
1782
+ | **History** | `undo()` | Undo last stroke |
1783
+ | | `redo()` | Redo last undone stroke |
1784
+ | **Keyboard** | `setKeyboardSettings(partial)` | Remap shortcuts |
1785
+ | | `getKeyboardSettings()` | Read current bindings |
1786
+ | | `enterKeyboardConfig()` | Suppress all shortcuts |
1787
+ | | `exitKeyboardConfig()` | Restore shortcuts |
1788
+ | | `setContrastShortcutEnabled(bool)` | Enable/disable contrast key |
1789
+ | | `isContrastShortcutEnabled()` | Query contrast key state |
1790
+ | **Inspect** | `getCurrentImageDimension()` | `[w, h, d]` voxel dims |
1791
+ | | `getVoxelSpacing()` | Physical mm spacing |
1792
+ | | `getSpaceOrigin()` | World-space origin |
1793
+ | | `getMaxSliceNum()` | Max slice index per axis |
1794
+ | | `getCurrentSlicesNumAndContrastNum()` | Current slice & contrast index |
1795
+ | | `getMaskData()` | Raw `IMaskData` object |
1796
+ | | `getNrrdToolsSettings()` | Full `NrrdState` snapshot (grouped sub-objects: image, view, interaction, sphere, flags) |
1797
+ | | `getContainer()` | Host `HTMLElement` |
1798
+ | | `getDrawingCanvas()` | Top-layer `HTMLCanvasElement` |
1799
+
1800
+ ---
1801
+
1802
+ ### 15. Gaussian Smoothing
1803
+
1804
+ NrrdTools includes built-in 3D Gaussian smoothing for segmentation masks, used to smooth jagged edges and fill small holes in annotations.
1805
+
1806
+ #### How It Works
1807
+
1808
+ Applies a separable 3D Gaussian blur (X → Y → Z convolution) to a single label channel within a MaskVolume, then thresholds the result at 0.5 back to a binary mask.
1809
+
1810
+ #### Usage
1811
+
1812
+ Invoke via `executeAction`:
1813
+
1814
+ ```typescript
1815
+ // Use default sigma (1.0)
1816
+ nrrdTools.executeAction("gaussianSmooth");
1817
+
1818
+ // Specify sigma
1819
+ nrrdTools.executeAction("gaussianSmooth", { sigma: 2.0 });
1820
+ ```
1821
+
1822
+ **Parameters:**
1823
+ - `sigma` (optional, default `1.0`): Gaussian kernel standard deviation in voxel units. Higher values produce stronger smoothing.
1824
+
1825
+ #### Anisotropic Spacing Support
1826
+
1827
+ When NRRD images have non-uniform voxel spacing (e.g., `[0.488, 0.488, 1.0]`), smoothing automatically adjusts per-axis sigma to ensure isotropic smoothing in physical space:
1828
+
1829
+ ```
1830
+ per-axis sigma = sigma / spacing[axis]
1831
+ ```
1832
+
1833
+ Spacing is automatically read from `nrrd_states.image.voxelSpacing`.
1834
+
1835
+ #### Undo Support
1836
+
1837
+ Gaussian smoothing is **fully undoable**. Before execution, all Z-slices containing the target channel are snapshotted, and the deltas are pushed to the UndoManager stack after execution.
1838
+
1839
+ ```typescript
1840
+ // Apply smoothing
1841
+ nrrdTools.executeAction("gaussianSmooth", { sigma: 1.5 });
1842
+
1843
+ // Undo smoothing (restores all affected slices)
1844
+ nrrdTools.undo();
1845
+ ```
1846
+
1847
+ #### Backend Sync
1848
+
1849
+ After smoothing completes, `onMaskChanged` is automatically fired for every modified slice, notifying the backend to sync.
1850
+
1851
+ #### Vue Component Integration
1852
+
1853
+ In `OperationCtl.vue`, the "Smoothing: Gaussian" button and "Smooth Sigma" slider provide full UI control:
1854
+
1855
+ ```typescript
1856
+ // Usage in OperationCtl.vue
1857
+ emitter.emit("Segmentation:SwitchAnimationStatus", { status: "flex", text: "Smoothing: Gaussian..." });
1858
+ setTimeout(() => {
1859
+ try {
1860
+ nrrdTools.executeAction("gaussianSmooth", { sigma: smoothSigma.value });
1861
+ toast.success("Gaussian smoothing completed");
1862
+ } catch (e) {
1863
+ toast.error("Gaussian smoothing failed");
1864
+ } finally {
1865
+ emitter.emit("Segmentation:SwitchAnimationStatus", { status: "none" });
1866
+ }
1867
+ }, 50);
1868
+ ```
1869
+
1870
+ > **Note**: Since smoothing runs synchronously on the main thread, `setTimeout` with a 50ms delay allows the UI to render the loading animation first.
1871
+
1872
+ #### GaussianSmoother API
1873
+
1874
+ `GaussianSmoother` is a pure static utility class with no DOM/Canvas/GUI dependencies:
1875
+
1876
+ | Method | Signature | Description |
1877
+ |--------|-----------|-------------|
1878
+ | `gaussianSmooth3D` | `(volume: MaskVolume, channel: number, sigma?: number, spacing?: [number, number, number]): void` | Apply separable 3D Gaussian smoothing to the specified channel (modifies volume in-place) |
1879
+ | `generateKernel1D` | `(sigma: number): Float32Array` | Generate a normalized 1D Gaussian kernel, truncated at ±3σ |
1880
+
1881
+ #### Performance Optimizations
1882
+
1883
+ GaussianSmoother includes two key performance optimizations:
1884
+
1885
+ 1. **Direct array access**: The extract and write-back phases bypass `getVoxel()`/`setVoxel()` boundary checks and function call overhead, directly accessing the underlying `Uint8Array` via `volume.getRawData()` with inline index calculation using `volume.getBytesPerSlice()` and `volume.getChannels()`.
1886
+ 2. **Branch-free convolution**: The `convolve1D` inner loop is split into three segments — left boundary (with lower bound check), middle interior (no branching at all, handles ~95% of work), and right boundary (with upper bound check).
1887
+
1888
+ > **Impact scope**: Only `GaussianSmoother.ts` is modified. All other tools continue using `getVoxel`/`setVoxel` with full boundary checks.