copper3d 3.10.3 → 3.11.0

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