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,1539 @@
1
+ # Segmentation Module Documentation
2
+
3
+ > Source: `src/Utils/segmentation/`
4
+
5
+ > ⚠️ **Note**: All line number references in this document are from historical versions. After multiple rounds of refactoring (State Management Refactor, NrrdTools God Class Split, inheritance → composition refactor), these references are outdated and provided for structural reference only. Always refer to the actual source code.
6
+
7
+ ## 1. Architecture Overview
8
+
9
+ ### 1.1 Class Composition
10
+
11
+ ```
12
+ NrrdTools (Facade)
13
+ ├── CanvasState ← Pure state container (nrrd_states, gui_states, protectedData, etc.)
14
+ ├── DrawToolCore ← Event orchestration, Undo/Redo, Tool initialization and delegation
15
+ │ ├── CanvasState (shared) ← References the same CanvasState instance
16
+ │ └── RenderingUtils ← Rendering / slice-buffer helpers
17
+ ├── LayerChannelManager ← Layer/Channel/SphereType management (211 lines)
18
+ ├── SliceRenderPipeline ← Slice rendering pipeline (453 lines)
19
+ └── DataLoader ← Data loading (222 lines)
20
+ ```
21
+
22
+ > **Inheritance → Composition Refactor (complete)**: The original three-level inheritance chain `NrrdTools → DrawToolCore → CommToolsData` has been fully replaced by composition. `CommToolsData` has been deleted. State is extracted into `CanvasState`, rendering methods into `RenderingUtils`.
23
+ >
24
+ > **DrawToolCore** is now a pure orchestration layer — all tool logic has been extracted into individual Tool classes.
25
+ > DrawToolCore permanently routes all pointer/wheel events via EventRouter, and dispatches each Tool's render methods in the `start()` render loop.
26
+ > There are no more manual `addEventListener`/`removeEventListener` calls (wheel behavior is dispatched via `activeWheelMode` state).
27
+ >
28
+ > **NrrdTools God Class Split (complete)**: NrrdTools was refactored across 4 phases from a 2007-line God Class into a Facade + 3 functional modules. The public API is unchanged; internals are decoupled via `ToolContext` + `ToolHost` `Pick<>` types.
29
+ >
30
+ > **Callback interface unification (complete)**: The original 10 separate `*Callbacks` interfaces have been unified into a single `ToolHost` interface (`tools/ToolHost.ts`). Each Tool selects its required host method subset via `Pick<ToolHost, ...>`.
31
+
32
+ - [CanvasState.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/CanvasState.ts) — Pure state container
33
+ - [RenderingUtils.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/RenderingUtils.ts) — Rendering utilities
34
+ - [DrawToolCore.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/DrawToolCore.ts) — Drawing core (composes CanvasState + RenderingUtils)
35
+ - [NrrdTools.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/NrrdTools.ts) — Public API Facade (composes CanvasState + DrawToolCore)
36
+ - [tools/LayerChannelManager.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/tools/LayerChannelManager.ts) — Layer/Channel management
37
+ - [tools/SliceRenderPipeline.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/tools/SliceRenderPipeline.ts) — Slice rendering pipeline
38
+ - [tools/DataLoader.ts](https://github.com/LinkunGao/copper3d_visualisation/blob/main/src/Utils/segmentation/tools/DataLoader.ts) — Data loading
39
+
40
+ ### 1.2 Canvas Layer Structure
41
+
42
+ There are **5 system canvases** + **N layer canvases** (3 layers by default).
43
+
44
+ ```
45
+ ┌──────────────────────────────────┐
46
+ │ drawingCanvas (top interaction) │ ← Captures mouse/pen events, real-time stroke rendering
47
+ ├──────────────────────────────────┤
48
+ │ drawingSphereCanvas │ ← Overlay for the 3D Sphere tool
49
+ ├──────────────────────────────────┤
50
+ │ drawingCanvasLayerMaster (composite) │ ← Result of compositing all visible layers
51
+ │ ├─ layerTargets[layer1].canvas │ ← Hidden per-layer canvas
52
+ │ ├─ layerTargets[layer2].canvas │
53
+ │ └─ layerTargets[layer3].canvas │
54
+ ├──────────────────────────────────┤
55
+ │ displayCanvas (background image) │ ← CT/MRI slice image
56
+ ├──────────────────────────────────┤
57
+ │ originCanvas (from Three.js) │ ← Cached original slice rendered by Three.js
58
+ ├──────────────────────────────────┤
59
+ │ emptyCanvas (temporary) │ ← Off-screen canvas for image processing and format conversion
60
+ └──────────────────────────────────┘
61
+ ```
62
+
63
+ **Canvas creation locations:**
64
+ - System canvases: `CanvasState.ts` → `generateSystemCanvases()`
65
+ - Layer canvases: `CanvasState.ts` → `generateLayerTargets(layerIds)`
66
+ - Canvas annotations: `CanvasState.ts` constructor
67
+
68
+ ### 1.3 NrrdTools Facade Internal Modules
69
+
70
+ NrrdTools passes shared state to each module via `ToolContext`, and declares host method dependencies via `Pick<ToolHost, ...>` type aliases:
71
+
72
+ ```
73
+ ToolContext = {
74
+ nrrd_states: NrrdState,
75
+ gui_states: GuiState,
76
+ protectedData: IProtected,
77
+ cursorPage: ICursorPage,
78
+ callbacks: IAnnotationCallbacks,
79
+ }
80
+ ```
81
+
82
+ | Module | File | Responsibility | HostDeps Type |
83
+ |--------|------|----------------|---------------|
84
+ | **LayerChannelManager** | `tools/LayerChannelManager.ts` | setActiveLayer/Channel/SphereType, visibility control, custom channel colors | `LayerChannelHostDeps` (3 methods) |
85
+ | **SliceRenderPipeline** | `tools/SliceRenderPipeline.ts` | Slice axis config, canvas rendering, mask reload, canvas flip, view/canvas helpers | `SliceRenderHostDeps` (10 methods) |
86
+ | **DataLoader** | `tools/DataLoader.ts` | NRRD slice loading, legacy mask loading, NIfTI voxel loading | `DataLoaderHostDeps` (7 methods) |
87
+
88
+ Delegation methods in NrrdTools are single-line calls (`this.layerChannelManager.xxx()`), containing no business logic.
89
+
90
+ ### 1.4 Layer and MaskVolume Correspondence
91
+
92
+ Each Layer maps to an independent `MaskVolume` instance:
93
+
94
+ ```
95
+ protectedData.maskData.volumes = {
96
+ "layer1": MaskVolume(width, height, depth, 1),
97
+ "layer2": MaskVolume(width, height, depth, 1),
98
+ "layer3": MaskVolume(width, height, depth, 1),
99
+ }
100
+ ```
101
+
102
+ - Initialized (1×1×1 placeholder): `CanvasState.ts` constructor
103
+ - Re-initialized with actual NRRD dimensions: `DataLoader.setAllSlices()` → `tools/DataLoader.ts`
104
+
105
+ ---
106
+
107
+ ## 2. NrrdTools Public API
108
+
109
+ > ⚠️ **Line numbers are outdated**. After the God Class Split refactor (1300 lines, 13 sections), method implementations have been migrated to the extracted modules (LayerChannelManager, SliceRenderPipeline, DataLoader). NrrdTools retains only single-line delegations. Line numbers are for historical reference only — always refer to the actual source code.
110
+ >
111
+ > Implementation locations: Layer/Channel methods → `tools/LayerChannelManager.ts`, rendering methods → `tools/SliceRenderPipeline.ts`, data loading → `tools/DataLoader.ts`.
112
+
113
+ ### 2.1 Layer & Channel Management
114
+
115
+ > **Implementation**: `tools/LayerChannelManager.ts`, single-line delegation in NrrdTools.
116
+
117
+ | Method | Signature | Description |
118
+ |--------|-----------|-------------|
119
+ | `setActiveLayer` | `(layerId: string): void` | Set the active Layer; also updates fillColor/brushColor |
120
+ | `setActiveChannel` | `(channel: ChannelValue): void` | Set the active Channel (1–`MAX_ENGINE_CHANNEL`); updates brush color |
121
+ | `clearChannel` | `(layerId: string, channel: number): void` | Erase one label across a whole layer, undoably. Throws on an unknown layer (deliberately not via `getVolumeForLayer`, whose fallback would erase a different layer) or a channel outside [1, 255] |
122
+ | `setCurrentLayer` | `(): { ctx, canvas } \| null` *(ToolHost)* | The layer canvas drawing should target. **Returns `null`** when the instance has no layers at all — `new NrrdTools(el, { layers: [] })`, a read-only reference viewer. Every caller must skip its work on `null` rather than dereference |
123
+ | `getLayerVolume` | `(layerId: string): Uint8Array \| null` | A **copy** of the layer's voxel buffer — not the live array, which a caller could mutate with nothing invalidating the slice cache. Delegates to `DrawToolCore.getLayerVolume` |
124
+ | `replaceLayerVolume` | `(layerId, data, opts?): void` | Replace the whole buffer. `{ undoable: true }` pushes one `VolumeSnapshot`. Does **not** fire `onLayerVolumeReplaced` itself — that fires only on a later undo/redo, when the backend holds the newer volume and must be told to fall back |
125
+ | `copyLayerData` | `(sourceLayerId, targetLayerId): void` | Direct buffer copy between layers, **not** undoable. Warns and returns if either volume is unresolvable or the lengths differ; preserves the target's colour map |
126
+ | `getActiveLayer` | `(): string` | Get the current Layer ID |
127
+ | `getActiveChannel` | `(): number` | Get the current Channel value |
128
+ | `setLayerVisible` | `(layerId, visible): void` | Set Layer visibility, triggers `reloadMasksFromVolume()` |
129
+ | `isLayerVisible` | `(layerId): boolean` | Check if a Layer is visible |
130
+ | `setChannelVisible` | `(layerId, channel, visible): void` | Set Channel visibility within a Layer, triggers re-render |
131
+ | `isChannelVisible` | `(layerId, channel): boolean` | Check if a Channel is visible |
132
+ | `getLayerVisibility` | `(): Record<string, boolean>` | Get a copy of all Layer visibility states |
133
+ | `getChannelVisibility` | `(): Record<string, Record<number, boolean>>` | Get a copy of all Channel visibility states |
134
+ | `hasLayerData` | `(layerId): boolean` | Check if a Layer has any non-zero data |
135
+ | `setLayerOpacity` | `(layerId: string, opacity: number): void` | Set per-layer opacity (0.1–1.0), triggers `reloadMasksFromVolume()` |
136
+ | `getLayerOpacity` | `(layerId: string): number` | Get opacity for a specific layer (defaults to 1.0) |
137
+ | `getLayerOpacityMap` | `(): Record<string, number>` | Get all per-layer opacity values |
138
+
139
+ ### 2.2 Custom Channel Color API
140
+
141
+ Per-layer custom channel colors. Each layer's MaskVolume has an independent `colorMap` — changes do not affect other layers.
142
+
143
+ | Method | Signature | Description |
144
+ |--------|-----------|-------------|
145
+ | `setChannelColor` | `(layerId: string, channel: number, color: RGBAColor): void` | Set color for a specific channel in a layer; triggers re-render and `onChannelColorChanged` callback |
146
+ | `getChannelColor` | `(layerId: string, channel: number): RGBAColor` | Get the RGBA color object |
147
+ | `getChannelHexColor` | `(layerId: string, channel: number): string` | Get Hex string (e.g. `#ff8000`) |
148
+ | `getChannelCssColor` | `(layerId: string, channel: number): string` | Get CSS rgba() string (e.g. `rgba(255,128,0,1.00)`) |
149
+ | `setChannelColors` | `(layerId: string, colorMap: Partial<ChannelColorMap>): void` | Batch-set multiple channel colors for one layer (single reload) |
150
+ | `setAllLayersChannelColor` | `(channel: number, color: RGBAColor): void` | Set the same channel color across all layers |
151
+ | `resetChannelColors` | `(layerId?: string, channel?: number): void` | Reset to `MASK_CHANNEL_COLORS` defaults |
152
+
153
+ **Internal mechanism:**
154
+ - `syncBrushColor()` — private method that dynamically reads the current layer's volume color to update `fillColor`/`brushColor`
155
+ - Called automatically in `setActiveLayer()`, `setActiveChannel()`, `setChannelColor()`, etc.
156
+
157
+ #### External Usage
158
+
159
+ **Prerequisite**: The `nrrdTools` instance must be created and `setAllSlices()` must have been called (i.e., image is loaded and MaskVolume is initialized).
160
+
161
+ ::: warning
162
+ Colors must be set **after** image loading is complete (`setAllSlices()` called). If `protectedData.maskData.volumes[layerId]` does not yet exist, the method silently fails — it hits the internal guard, emits `console.warn`, and returns immediately with no visual effect and no thrown exception.
163
+
164
+ **Common mistake**: calling `setChannelColor` inside `onFinishedCopperInit`. That callback fires when the Copper3D renderer is ready, but no NRRD images have been loaded yet — `volumes["layer1"]` is `undefined` at that point.
165
+
166
+ ```typescript
167
+ // ❌ WRONG — too early, MaskVolume does not exist yet
168
+ const onFinishedCopperInit = (data) => {
169
+ nrrdTools.value = data.nrrdTools;
170
+ nrrdTools.value.setChannelColor('layer1', 1, { r: 25, g: 0, b: 0, a: 255 }); // silent no-op
171
+ };
172
+
173
+ // ✅ CORRECT — call after images are loaded (setAllSlices() has already run)
174
+ const handleAllImagesLoaded = (res) => {
175
+ nrrdTools.value.setChannelColor('layer1', 1, { r: 25, g: 0, b: 0, a: 255 }); // works
176
+ };
177
+ ```
178
+ :::
179
+
180
+ ---
181
+
182
+ **Scenario 1: Set a custom color for a specific channel in a layer**
183
+
184
+ ```typescript
185
+ // Set layer2's channel 3 to orange
186
+ nrrdTools.setChannelColor('layer2', 3, { r: 255, g: 128, b: 0, a: 255 });
187
+ // Effect: all masks drawn with channel 3 on layer2 become orange
188
+ // layer1 and layer3's channel 3 colors are unaffected
189
+ ```
190
+
191
+ ---
192
+
193
+ **Scenario 2: Batch-set multiple channel colors in one layer (recommended — triggers a single re-render)**
194
+
195
+ ```typescript
196
+ nrrdTools.setChannelColors('layer1', {
197
+ 1: { r: 255, g: 0, b: 0, a: 255 }, // channel 1 → red
198
+ 2: { r: 0, g: 0, b: 255, a: 255 }, // channel 2 → blue
199
+ 3: { r: 255, g: 255, b: 0, a: 255 }, // channel 3 → yellow
200
+ });
201
+ // Triggers only one reloadMasksFromVolume() — more efficient than multiple setChannelColor() calls
202
+ ```
203
+
204
+ ---
205
+
206
+ **Scenario 3: Apply the same channel color across all layers**
207
+
208
+ ```typescript
209
+ // Set channel 1 to red across all layers
210
+ nrrdTools.setAllLayersChannelColor(1, { r: 255, g: 0, b: 0, a: 255 });
211
+ ```
212
+
213
+ ---
214
+
215
+ **Scenario 4: Read the current color**
216
+
217
+ ```typescript
218
+ const rgba = nrrdTools.getChannelColor('layer2', 3);
219
+ // → { r: 255, g: 128, b: 0, a: 255 }
220
+
221
+ const hex = nrrdTools.getChannelHexColor('layer2', 3);
222
+ // → "#ff8000" (suitable for canvas fillStyle or CSS color)
223
+
224
+ const css = nrrdTools.getChannelCssColor('layer2', 3);
225
+ // → "rgba(255,128,0,1.00)" (suitable for Vue style binding)
226
+ ```
227
+
228
+ ---
229
+
230
+ **Scenario 5: Reset colors**
231
+
232
+ ```typescript
233
+ // Reset channel 3 of layer2 to default
234
+ nrrdTools.resetChannelColors('layer2', 3);
235
+
236
+ // Reset all channels of layer2 to default
237
+ nrrdTools.resetChannelColors('layer2');
238
+
239
+ // Reset all channels of all layers to default
240
+ nrrdTools.resetChannelColors();
241
+ ```
242
+
243
+ ---
244
+
245
+ **Scenario 6: Notify Vue UI to refresh after setting colors**
246
+
247
+ After a color change, the canvas re-renders automatically (`reloadMasksFromVolume()` is called automatically). However, Vue UI components showing channel color swatches need a manual nudge:
248
+
249
+ ```typescript
250
+ // In a Vue component, get the refreshChannelColors function from the composable
251
+ const { refreshChannelColors } = useLayerChannel({ nrrdTools });
252
+
253
+ // After setting a color, call refresh to sync the Vue UI
254
+ nrrdTools.setChannelColor('layer2', 3, { r: 255, g: 128, b: 0, a: 255 });
255
+ refreshChannelColors(); // Increments colorVersion → triggers recomputation of dynamicChannelConfigs
256
+ ```
257
+
258
+ Or listen to the `onChannelColorChanged` callback for automatic refresh:
259
+
260
+ ```typescript
261
+ // ⚠️ onChannelColorChanged is currently attached to nrrd_states and cannot be set directly from outside
262
+ // Recommended: manually call refreshChannelColors() after setChannelColor()
263
+ ```
264
+
265
+ ---
266
+
267
+ **Scenario 7: Complete initialization + color setup example (in a Vue component)**
268
+
269
+ ```typescript
270
+ import emitter from '@/plugins/custom-emitter';
271
+
272
+ const nrrdTools = ref<Copper.NrrdTools>();
273
+
274
+ emitter.on('Core:NrrdTools', (tools) => {
275
+ nrrdTools.value = tools;
276
+ });
277
+
278
+ emitter.on('Segmentation:FinishLoadAllCaseImages', () => {
279
+ // At this point setAllSlices() is complete, MaskVolume is initialized
280
+ if (!nrrdTools.value) return;
281
+
282
+ nrrdTools.value.setChannelColors('layer1', {
283
+ 1: { r: 255, g: 80, b: 80, a: 255 }, // light red
284
+ 2: { r: 80, g: 180, b: 255, a: 255 }, // light blue
285
+ });
286
+ // layer2 keeps default colors — no action needed
287
+ });
288
+ ```
289
+
290
+ ---
291
+
292
+ **Color value range**
293
+
294
+ ```typescript
295
+ interface RGBAColor {
296
+ r: number; // 0-255
297
+ g: number; // 0-255
298
+ b: number; // 0-255
299
+ a: number; // 0-255 (255 = fully opaque, 0 = fully transparent)
300
+ }
301
+ ```
302
+
303
+ The `a` (alpha) field determines the base mask opacity. Usually set to `255`; actual rendering multiplies by `gui_states.drawing.globalAlpha` (default 0.6) and `gui_states.layerChannel.layerOpacity[layerId]` (default 1.0).
304
+
305
+ > **Per-Layer Alpha**: Final rendering opacity = `globalAlpha × layerOpacity[layerId]`. The global alpha controls all layers uniformly, while per-layer opacity allows independent control per layer.
306
+
307
+ ### 2.3 Keyboard & History
308
+
309
+ > **Implementation**: Directly in the NrrdTools Facade (section 4).
310
+
311
+ | Method | Signature | Description |
312
+ |--------|-----------|-------------|
313
+ | `undo` | `(): void` | Undo the last drawing operation |
314
+ | `redo` | `(): void` | Redo the last undone operation |
315
+ | `enterKeyboardConfig` | `(): void` | Suppress all shortcuts |
316
+ | `exitKeyboardConfig` | `(): void` | Restore shortcuts |
317
+ | `setContrastShortcutEnabled` | `(enabled: boolean): void` | Enable/disable the Contrast shortcut key |
318
+ | `isContrastShortcutEnabled` | `(): boolean` | Check if the Contrast shortcut is enabled |
319
+ | `setKeyboardSettings` | `(settings: Partial<IKeyBoardSettings>): void` | Update keyboard shortcut bindings |
320
+ | `getKeyboardSettings` | `(): IKeyBoardSettings` | Get a snapshot of current keyboard settings |
321
+
322
+ ### 2.4 Data Loading
323
+
324
+ > **Implementation**: `tools/DataLoader.ts`, single-line delegation in NrrdTools.
325
+
326
+ | Method | Signature | Description |
327
+ |--------|-----------|-------------|
328
+ | `setAllSlices` | `(allSlices: Array<nrrdSliceType>): void` | **Entry point**: Load NRRD slices and initialize all MaskVolumes to the correct dimensions |
329
+ | `initFromHeader` | `(header: NrrdHeaderLike): void` | Size image metadata and MaskVolumes from volume geometry alone, before any pixel data exists. `allSlicesArray` is untouched |
330
+ | `appendSlice` | `(slice: nrrdSliceType, order: number): void` | Append one already-loaded slice to the contrast series and refresh display slices / undo state |
331
+ | `setMasksData` | `(masksData, loadingBar?): void` | Legacy loading method (deprecated, pending removal) |
332
+ | `setMasksFromNIfTI` | `(layerVoxels: Map<string, Uint8Array>, loadingBar?): void` | Load mask data from NIfTI files into MaskVolume, validating each buffer's grid |
333
+ | `registerNiftiMaskGrid` | `(data: Uint8Array, dims: number[]): void` *(module export)* | Record a mask buffer's NIfTI voxel grid, keyed by buffer identity, for `setMasksFromNIfTI` to check |
334
+
335
+ #### Bulk vs. progressive loading
336
+
337
+ `setAllSlices` is the bulk path and is still what almost every caller wants. Internally it is
338
+ now a composition of two smaller pieces, which are also usable on their own:
339
+
340
+ ```
341
+ setAllSlices(allSlices)
342
+ │
343
+ ├─ initFromHeader(headerFromSlice(allSlices[0])) → image metadata + MaskVolume sizing
344
+ │ └─ headerFromSlice reads dimensions/spacing/space_origin off the shared Volume
345
+ │
346
+ ├─ allSlicesArray.length = 0 → replace, not append
347
+ └─ setContrastOrder(slice, i) for each slice → stamp contrastOrder on x/y/z
348
+ ```
349
+
350
+ The split exists so a progressive loader can size everything from a backend headers response
351
+ (`{ dimensions, spacing, space_origin }` as JSON — the same `NrrdHeaderLike` shape) and then
352
+ feed slices in one at a time with `appendSlice` as they arrive.
353
+
354
+ ::: warning `appendSlice` is not a loop-friendly substitute for `setAllSlices`
355
+ It calls `setDisplaySlicesBaseOnAxis()` per slice, which rebuilds the display-slice list from
356
+ a still-growing `allSlicesArray`, and whose `skipSlicesDic` bookkeeping assumes it is seeing
357
+ the final array. For N slices already in hand, use `setAllSlices`.
358
+ :::
359
+
360
+ **Why `nrrd_x_mm` is derivable without a canvas.** The mm extents used to be read off
361
+ `slice.z.canvas.width/height` and `slice.x.canvas.width` — the physical size of the plane
362
+ `VolumeSlice` extracted. Those canvases are always sized to `dimensions[axis] * spacing[axis]`
363
+ (`Volume.extractPerpendicularPlane` sets `planeWidth`/`planeHeight` to the voxel counts times
364
+ spacing), so the same values follow from dimensions and spacing alone. `canvas.width` is an
365
+ HTML `unsigned long`, so a non-integer product truncates (44.8 → 44); `initFromHeader`
366
+ reproduces that with `Math.floor`, which agrees with the DOM because spacing is a magnitude
367
+ and never negative.
368
+
369
+ **Narrowed-axes tolerance.** `headerFromSlice` and `setContrastOrder` read and stamp
370
+ `slice.x ?? slice.y ?? slice.z` rather than assuming `.x`, because a
371
+ [narrowed-axes load](./load-callbacks) may only have `z` extracted at this point. A plane
372
+ extracted later by `ensureAxisExtracted` inherits `contrastOrder` from its siblings, so it
373
+ ends up indistinguishable from one extracted at load time.
374
+
375
+ #### Mask grid validation
376
+
377
+ `setMasksFromNIfTI` used to truncate a longer buffer and zero-pad a shorter one, which
378
+ rendered a wrong-grid mask silently offset onto the wrong voxels. It now compares the
379
+ buffer's registered grid against `nrrd_states.image.dimensions` and refuses on mismatch:
380
+
381
+ ```
382
+ for each [layerId, rawData] of layerVoxels
383
+ ├─ volume missing? → console.warn, skip layer
384
+ ├─ maskGridByBuffer.get(rawData) → undefined, or dims !== image dims?
385
+ │ → console.error + notifyUser, skip layer (never truncate, never pad)
386
+ └─ volume.setRawData(rawData)
387
+ ```
388
+
389
+ `notifyUser(message, level)` is a `ToolHost` dependency backed by the public
390
+ `NrrdTools.notifyUser` property. It defaults to a console write: this engine has no UI of its
391
+ own, and importing the host application's is exactly what made the package unbuildable on its
392
+ own. A host with a toast or a banner assigns its own implementation after construction.
393
+
394
+ A buffer with **no** registered grid is refused rather than assumed to match. The registry is
395
+ a `WeakMap` keyed by buffer identity — not by layer id — so a caller may decode several layers
396
+ before `setMasksFromNIfTI` is consulted, and entries are collected with the buffers.
397
+
398
+ ### 2.5 Display & Rendering
399
+
400
+ > **Implementation**: `tools/SliceRenderPipeline.ts`, single-line delegation in NrrdTools.
401
+
402
+ | Method | Signature | Description |
403
+ |--------|-----------|-------------|
404
+ | `resizePaintArea` | `(factor: number): void` | Resize the canvas scale factor |
405
+ | `reloadMasksFromVolume` | `(): void` (private) | **Core re-render**: Re-renders all Layers from MaskVolume to Canvas |
406
+ | `flipDisplayImageByAxis` | `(): void` | Flip the CT image for correct display orientation |
407
+ | `redrawDisplayCanvas` | `(): void` | Redraw the contrast image onto the displayCanvas |
408
+ | `setEmptyCanvasSize` | `(axis?): void` | Set emptyCanvas dimensions based on the current axis |
409
+ | `setMaskRenderMode` | `(mode: MaskRenderMode): void` | Set `"fill"` / `"outline"` globally, then `reloadMasksFromVolume()`. Repaints immediately because nothing else would bring the change to screen |
410
+ | `getMaskRenderMode` | `(): MaskRenderMode` | Read the current mode |
411
+
412
+ #### Fill vs. outline rendering
413
+
414
+ Two render paths, one silhouette. `extractLabelPolygons` / `extractLabelContours` cover the
415
+ region; `extractLabelBoundarySegments` / `extractLabelOutline` trace its edge. Both walk the
416
+ same cells with the same sampling, the same out-of-bounds rule and the same `+0.5` shift, so
417
+ the mask ends in exactly the same place whichever you draw — the edge does not appear to move
418
+ when the mode is toggled.
419
+
420
+ ```
421
+ RenderingUtils
422
+ │
423
+ ├─ renderSliceToCanvas(...) → drawSlice(..., outline = maskRenderMode === "outline")
424
+ └─ renderSliceForBake(...) → drawSlice(..., outline = false) ◀ always filled
425
+ ```
426
+
427
+ **`renderSliceForBake` is not an optimisation, it is a correctness requirement.** For the
428
+ tools that bake (`syncLayerSliceData` — pencil and eraser) the layer canvas is not a picture
429
+ of the mask, it is the input the mask is rebuilt from: the bake replaces the whole slice in
430
+ `MaskVolume` with whatever pixels it finds. An outline is a *lossy* picture — it says where a
431
+ mask ends, not what it contains — so baking one back writes rings and erases every interior on
432
+ that slice, taking every other finding on the layer with it. One pencil stroke was enough.
433
+
434
+ It is a separate entry point rather than a flag threaded through the display path because a
435
+ render that is about to be read back has a different requirement from one that is about to be
436
+ looked at; the two only coincided while there was one way to draw a mask.
437
+
438
+ `DrawingTool` uses it in two places:
439
+
440
+ | Method | When | Why |
441
+ |--------|------|-----|
442
+ | `redrawPreviousImageToLayerCtx` | before a pencil fill | what lands here is about to be read straight back by `syncLayerSliceData` |
443
+ | `solidifyLayerForErase` | at pointer-down, if the eraser is active | the eraser removes pixels matching the active channel's colour; against an outline there is nothing to match *inside* a mask, so a drag over a lesion would erase nothing — and the bake that follows would write the ring back |
444
+
445
+ `solidifyLayerForErase` runs unconditionally rather than checking the display mode: in fill
446
+ mode it redraws what is already on screen, and a mode-dependent branch there is one more thing
447
+ that can fall out of step with the renderer. The display mode returns at pointer-up, via
448
+ `refreshLayerFromVolume`.
449
+
450
+ ##### Path cache
451
+
452
+ The render mode is **not** part of the cache key. Each entry holds two lazily-built maps:
453
+
454
+ ```ts
455
+ {
456
+ key: `${axis}:${sliceIndex}:${volume.getVersion()}`,
457
+ W, H,
458
+ labels: number[],
459
+ fills: Map<number, Path2D>, // built on first use of fill mode for this slice
460
+ outlines: Map<number, Path2D>, // built on first use of outline mode for this slice
461
+ }
462
+ ```
463
+
464
+ On a hit, `drawSlice` checks whether the map it needs is fully populated
465
+ (`size !== labels.length`) and builds it if not. So switching mode costs one extraction per
466
+ visible label the first time and is a pure cache hit after; a session that never leaves fill
467
+ mode never builds an outline. Building both eagerly would make every slice scrub pay for a
468
+ mode most sessions never turn on.
469
+
470
+ ##### Stroking on an untransformed context
471
+
472
+ Outline mode does **not** stroke under `ctx.scale(sx, sy)`. The voxel→display mapping is
473
+ carried in a `DOMMatrix` applied to the path (`display.addPath(path, matrix)`), and the
474
+ context is left untransformed, so `lineWidth` is measured in **screen pixels**
475
+ (`OUTLINE_WIDTH_PX = 1.5`).
476
+
477
+ Stroking under the scale gets two things wrong: the line thickens with the zoom — exactly when
478
+ the clinician has magnified the image to look at the boundary — and because voxels are rarely
479
+ isotropic (`sx !== sy`) it comes out thicker in one axis than the other.
480
+
481
+ The coronal (`axis === 'y'`) Z-flip is folded into the same matrix rather than applied to the
482
+ context.
483
+
484
+ ::: tip Why the segments are left unjoined
485
+ `extractLabelBoundarySegments` emits open two-point segments per cell and does not chain them
486
+ into polylines. Canvas rasterises a whole `Path2D` in one compositing pass, so segments meeting
487
+ at a shared endpoint produce no seam and no doubled alpha where their round caps overlap —
488
+ joining them would buy nothing and cost a chaining pass. `lineJoin` / `lineCap` are `'round'`
489
+ to close those joins.
490
+ :::
491
+
492
+ ### 2.6 Programmatic Sphere Placement
493
+
494
+ | Method | Signature | Description |
495
+ |--------|-----------|-------------|
496
+ | `setCalculateDistanceSphere` | `(x: number, y: number, sliceIndex: number, cal_position: SphereType): void` | Programmatically place a calculator sphere, simulating a full mouse click flow |
497
+
498
+ **Parameters:**
499
+ - `x`, `y` — Unscaled image-space coordinates (the method applies `sizeFactor` internally)
500
+ - `sliceIndex` — Target slice index
501
+ - `cal_position` — Sphere type: `"tumour"` / `"skin"` / `"nipple"` / `"ribcage"`
502
+
503
+ **Internal flow** (simulates `DrawToolCore.handleSphereClick` + `pointerup`):
504
+
505
+ ```
506
+ setCalculateDistanceSphere(x, y, sliceIndex, cal_position)
507
+ │
508
+ ├─ sphereRadius = 5
509
+ ├─ setSliceMoving(...) → navigate to target slice
510
+ │
511
+ ├─ --- simulate mouse-down ---
512
+ │ ├─ mouseX = x * sizeFactor
513
+ │ ├─ sphereOrigin[axis] = [mouseX, mouseY, sliceIndex]
514
+ │ ├─ crosshairTool.setUpSphereOrigins(...) → compute origins on all 3 axes
515
+ │ ├─ tumourSphereOrigin = deepCopy(sphereOrigin) → store by cal_position type
516
+ │ └─ drawCalculatorSphere(radius) → draw preview
517
+ │
518
+ └─ --- simulate mouse-up ---
519
+ ├─ sphereTool.writeAllCalculatorSpheresToVolume() → write to sphereMaskVolume
520
+ └─ sphereTool.refreshSphereCanvas() → re-render overlay
521
+ ```
522
+
523
+ **Typical usage** (called after backend returns sphere coordinates):
524
+
525
+ ```typescript
526
+ nrrdTools.setCalculateDistanceSphere(120, 95, 42, 'tumour');
527
+ nrrdTools.setCalculateDistanceSphere(200, 150, 42, 'skin');
528
+ ```
529
+
530
+ ### 2.7 Other APIs
531
+
532
+ > **Implementation**: Directly in the NrrdTools Facade (section 5 View Control, section 6 Data Getters).
533
+
534
+ | Method | Description |
535
+ |--------|-------------|
536
+ | `drag(opts?)` | Enable drag-to-scroll slice navigation |
537
+ | `setAnnotationSuspended(bool)` | Block every input that can write into a mask, at `DrawToolCore.onCanvasPointerDown`. Slice scrubbing, zoom, pan and the crosshair stay live (see 7.1) |
538
+ | `isAnnotationSuspended()` | Query the suspension state |
539
+ | `setSliceOrientation(axis)` | Switch viewing axis. Calls `ensureAxisExtracted` for every loaded contrast first, so a narrowed-axes load can still switch planes |
540
+ | `addSkip(index)` / `removeSkip(index)` | Hide / show one contrast. `index` addresses the **full** contrast list |
541
+ | `setSkips(entries)` | Batched `addSkip`/`removeSkip`: writes every `skipSlicesDic` entry, then one `resetDisplaySlicesStatus()` |
542
+ | `setContrastIndex(index)` | Move to a contrast **within `displaySlices`** (the selected subset), clamped to its bounds |
543
+ | `commitSkipsAndContrast(entries, i)` | `setSkips` + `setContrastIndex` in one refresh. `contrastNum` is written *before* the refresh so its callbacks paint the target contrast directly; the clamp runs after, against the rebuilt `displaySlices` |
544
+ | `commitSeriesLoad(slices, entries, i)` | Case-load completion: replaces `allSlicesArray`, then delegates to `commitSkipsAndContrast` — one refresh instead of three |
545
+ | `switchAllSlicesArrayData(slices)` | Swap the loaded series and rebuild the display (resets view state) |
546
+ | `switchSlicesPreservingView(slices)` | Swap the loaded series via `switchPreservingView()`, keeping slice index, zoom and pan |
547
+ | `setSliceMoving(step)` | Step the current slice; steps are accumulated and applied in one `requestAnimationFrame` |
548
+ | `setMainAreaSize(factor)` | Clamp the zoom factor to [1, 8], resize the paint area and reset its UI position |
549
+ | `setBaseDrawDisplayCanvasesSize(size)` | Set canvas base size multiplier (1–8) |
550
+ | `setupGUI(gui)` | Set up the dat.GUI panel |
551
+ | `enableContrastDragEvents(callback)` | Enable contrast drag (window/level) events |
552
+ | `getCurrentImageDimension()` | Get voxel dimensions `[w, h, d]` |
553
+ | `getVoxelSpacing()` | Get voxel spacing (mm) |
554
+ | `getSpaceOrigin()` | Get world-space origin |
555
+ | `getMaxSliceNum()` | Get max slice count per axis |
556
+ | `getCurrentSlicesNumAndContrastNum()` | Get current slice index and contrast index |
557
+ | `getMaskData()` | Get raw `IMaskData` structure |
558
+ | `getContainer()` | Get the internal main-area container element |
559
+ | `getDrawingCanvas()` | Get the top-level interactive canvas |
560
+ | `getNrrdToolsSettings()` | Get a full NrrdState snapshot (5 sub-objects) |
561
+ | `executeAction(action)` | Execute a named action: `"undo"`, `"redo"`, `"clearActiveSliceMask"`, `"clearActiveLayerMask"`, `"resetZoom"`, `"downloadCurrentMask"`, `"gaussianSmooth"`. `"gaussianSmooth"` accepts optional `opts?: { sigma?: number }` |
562
+
563
+ ---
564
+
565
+ ## 3. States
566
+
567
+ ### 3.1 nrrd_states (NrrdState)
568
+
569
+ **Type**: `NrrdState` class (defined in `coreTools/NrrdState.ts`)
570
+ **Interface**: `INrrdStates` extends `IImageMetadata`, `IViewState`, `IInteractionState`, `ISphereState`, `IInternalFlags` (defined in `core/types.ts`)
571
+
572
+ NrrdState groups 44 properties into 5 semantic sub-objects:
573
+
574
+ #### nrrd_states.image (IImageMetadata)
575
+
576
+ | Field | Type | Description |
577
+ |-------|------|-------------|
578
+ | `dimensions` | `[width, height, depth]` | Voxel dimensions |
579
+ | `nrrd_x_pixel` / `y` / `z` | `number` | Pixel count per axis |
580
+ | `voxelSpacing` | `number[]` | Voxel spacing |
581
+ | `spaceOrigin` | `number[]` | World-space origin |
582
+ | `layers` | `string[]` | List of Layer IDs |
583
+
584
+ #### nrrd_states.view (IViewState)
585
+
586
+ | Field | Type | Description |
587
+ |-------|------|-------------|
588
+ | `currentSliceIndex` | `number` | Current slice index |
589
+ | `maxIndex` / `minIndex` | `number` | Slice index range |
590
+ | `changedWidth` / `changedHeight` | `number` | Canvas display dimensions |
591
+ | `sizeFactor` | `number` | Scale factor |
592
+ | `originWidth` / `originHeight` | `number` | Original image dimensions |
593
+
594
+ #### nrrd_states.interaction (IInteractionState)
595
+
596
+ | Field | Type | Description |
597
+ |-------|------|-------------|
598
+ | `mouseOverX` / `mouseOverY` | `number` | Mouse position |
599
+ | `mouseOver` | `boolean` | Whether mouse is over the canvas |
600
+ | `cursorPageX` / `cursorPageY` | `number` | Cursor page coordinates |
601
+ | `drawStartPos` | `ICommXY` | Drawing start point |
602
+
603
+ #### nrrd_states.sphere (ISphereState)
604
+
605
+ | Field | Type | Description |
606
+ |-------|------|-------------|
607
+ | `sphereOrigin` / `skinSphereOrigin` etc. | `ICommXYZ \| null` | Origin for each sphere type |
608
+ | `sphereRadius` | `number` | Sphere radius |
609
+ | `sphereBrushRadius` | `number` | SphereBrush/SphereEraser radius (1-50) |
610
+ | `sphereMaskVolume` | `MaskVolume \| null` | Sphere volumetric data |
611
+
612
+ #### nrrd_states.flags (IInternalFlags)
613
+
614
+ | Field | Type | Description |
615
+ |-------|------|-------------|
616
+ | `stepClear` | `number` | Clear step (internal use) |
617
+ | `clearAllFlag` | `boolean` | Whether the current operation is a full-layer clear |
618
+ | `loadingMaskData` | `boolean` | Whether mask data is currently being loaded |
619
+
620
+ ::: warning
621
+ The `loadMaskByDefault` and `isCalcContrastByDrag` fields **no longer exist** — previous documentation was incorrect.
622
+
623
+ `INrrdStates` flat interface is kept for backward compatibility (extends all 5 sub-interfaces), but at runtime the `NrrdState` class instance is used, with properties accessed via `nrrd_states.image.xxx`, `nrrd_states.view.xxx`, etc.
624
+ :::
625
+
626
+ ### 3.2 gui_states (GuiState)
627
+
628
+ **Type**: `GuiState` class (defined in `coreTools/GuiState.ts`)
629
+ **Interface**: `IGUIStates` extends `IToolModeState`, `IDrawingConfig`, `IViewConfig`, `ILayerChannelState` (defined in `core/types.ts`)
630
+
631
+ GuiState groups 20 properties into 4 semantic sub-objects:
632
+
633
+ #### gui_states.mode (IToolModeState)
634
+
635
+ | Field | Type | Description |
636
+ |-------|------|-------------|
637
+ | `pencil` | `boolean` | Pencil tool active |
638
+ | `eraser` | `boolean` | Eraser tool active |
639
+ | `sphere` | `boolean` | Sphere tool active |
640
+ | `sphereBrush` | `boolean` | Sphere Brush tool active |
641
+ | `sphereEraser` | `boolean` | Sphere Eraser tool active |
642
+ | `activeSphereType` | `"tumour" \| "skin" \| "nipple" \| "ribcage"` | Current sphere type |
643
+
644
+ #### gui_states.drawing (IDrawingConfig)
645
+
646
+ | Field | Type | Description |
647
+ |-------|------|-------------|
648
+ | `globalAlpha` | `number` | Global opacity (default 0.6) |
649
+ | `lineWidth` | `number` | Line width |
650
+ | `color` / `fillColor` / `brushColor` | `string` | Brush color (Hex) |
651
+ | `brushAndEraserSize` | `number` | Brush/eraser size |
652
+ | `maskRenderMode` | `MaskRenderMode` | `"fill"` (default) or `"outline"`. Applies to every layer and channel at once; read only by the renderer, never by the write path |
653
+
654
+ #### gui_states.viewConfig (IViewConfig)
655
+
656
+ | Field | Type | Description |
657
+ |-------|------|-------------|
658
+ | `mainAreaSize` | `number` | Main area size |
659
+ | `dragSensitivity` | `number` | Drag sensitivity |
660
+ | `cursor` / `defaultPaintCursor` | `string` | Cursor style |
661
+ | `readyToUpdate` | `boolean` | Ready-to-update flag |
662
+
663
+ #### gui_states.layerChannel (ILayerChannelState)
664
+
665
+ | Field | Type | Description |
666
+ |-------|------|-------------|
667
+ | `layer` | `string` | Currently active Layer (default `"layer1"`) |
668
+ | `activeChannel` | `number` | Currently active Channel (1–255; 0 = empty/erased) |
669
+ | `layerVisibility` | `Record<string, boolean>` | Layer visibility map |
670
+ | `channelVisibility` | `Record<string, Record<number, boolean>>` | Channel visibility map |
671
+ | `layerOpacity` | `Record<string, number>` | Per-layer opacity map (0.1–1.0, default 1.0) |
672
+
673
+ ### 3.3 protectedData (IProtected)
674
+
675
+ Defined in `CanvasState.ts` constructor.
676
+
677
+ | Field | Description |
678
+ |-------|-------------|
679
+ | `axis` | Current viewing axis `"x"` / `"y"` / `"z"` |
680
+ | `maskData.volumes` | `Record<string, MaskVolume>` — 3D volume for each Layer |
681
+ | `layerTargets` | `Map<string, ILayerRenderTarget>` — canvas + ctx for each Layer |
682
+ | `canvases` | 5 system canvases |
683
+ | `ctxes` | Corresponding 2D contexts |
684
+ | `isDrawing` | Whether drawing is currently active |
685
+
686
+ ::: warning
687
+ `Is_Shift_Pressed` / `Is_Ctrl_Pressed` have been removed. Keyboard modifier key state is now managed internally by `EventRouter` and is no longer exposed through `protectedData`.
688
+ :::
689
+
690
+ ---
691
+
692
+ ## 4. Callbacks
693
+
694
+ ### 4.1 onMaskChanged / getMaskData (backend sync)
695
+
696
+ Storage location: `CanvasState.annotationCallbacks.onMaskChanged` (`IAnnotationCallbacks` interface)
697
+
698
+ ::: warning
699
+ The `nrrd_states.getMask` field referenced in previous documentation **no longer exists**. Register externally via `nrrdTools.draw({ getMaskData: ... })`, which maps internally to `annotationCallbacks.onMaskChanged`.
700
+ :::
701
+
702
+ ```ts
703
+ onMaskChanged: (
704
+ sliceData: Uint8Array, // Raw voxel data for the current slice
705
+ layerId: string, // Layer name
706
+ channelId: number, // Active channel
707
+ sliceIndex: number, // Slice index
708
+ axis: "x" | "y" | "z", // Current axis
709
+ width: number, // Slice width
710
+ height: number, // Slice height
711
+ clearFlag: boolean // Whether this is a clear operation
712
+ ) => void
713
+ ```
714
+
715
+ **Called**: After each completed drawing stroke (mouseup), and after undo/redo.
716
+
717
+ ### 4.2 onLayerVolumeCleared
718
+
719
+ Storage location: `CanvasState.annotationCallbacks.onLayerVolumeCleared`
720
+
721
+ ```ts
722
+ onLayerVolumeCleared: (layerId: string) => void
723
+ ```
724
+
725
+ ### 4.3 onChannelColorChanged
726
+
727
+ Storage location: `CanvasState.annotationCallbacks.onChannelColorChanged` (`IAnnotationCallbacks`, `core/types.ts`)
728
+
729
+ ::: warning
730
+ Previous documentation stated this was defined on `INrrdStates` — **that is incorrect**. This callback now belongs to `IAnnotationCallbacks`, stored in `CanvasState.annotationCallbacks`.
731
+ :::
732
+
733
+ ```ts
734
+ onChannelColorChanged: (layerId: string, channel: number, color: RGBAColor) => void
735
+ ```
736
+
737
+ **Called**: After `NrrdTools.setChannelColor()` modifies a color. Default is a no-op. Currently cannot be registered directly from outside — recommended approach: manually call `refreshChannelColors()` after `setChannelColor()`.
738
+
739
+ ### 4.4 onSphereChanged / onCalculatorPositionsChanged
740
+
741
+ Storage location: `CanvasState.annotationCallbacks` (`IAnnotationCallbacks`, registered externally via `draw()`)
742
+
743
+ **`onSphereChanged`** (`getSphereData` in `IDrawOpts`): Called when the left mouse button is released in sphere mode.
744
+
745
+ ```ts
746
+ onSphereChanged: (sphereOrigin: number[], sphereRadius: number) => void
747
+ // sphereOrigin = [mouseX, mouseY, sliceIndex] — z-axis view coordinates
748
+ // sphereRadius = radius in pixels (1–50)
749
+ ```
750
+
751
+ **`onCalculatorPositionsChanged`** (`getCalculateSpherePositionsData` in `IDrawOpts`): Called after a sphere is placed (applies to all sphere types).
752
+
753
+ ```ts
754
+ onCalculatorPositionsChanged: (
755
+ tumourSphereOrigin: ICommXYZ | null, // channel 1
756
+ skinSphereOrigin: ICommXYZ | null, // channel 4
757
+ ribSphereOrigin: ICommXYZ | null, // channel 3
758
+ nippleSphereOrigin: ICommXYZ | null, // channel 2
759
+ axis: "x" | "y" | "z"
760
+ ) => void
761
+ // Each origin is { x: [mx, my, slice], y: [...], z: [...] }
762
+ // null means that sphere type has not yet been placed
763
+ ```
764
+
765
+ **Channel mapping** (exported as `SPHERE_CHANNEL_MAP`):
766
+
767
+ | Sphere Type | Layer | Channel | Color |
768
+ |-------------|--------|---------|-------|
769
+ | tumour | layer1 | 1 | `#10b981` (Emerald) |
770
+ | nipple | layer1 | 2 | `#f43f5e` (Rose) |
771
+ | ribcage | layer1 | 3 | `#3b82f6` (Blue) |
772
+ | skin | layer1 | 4 | `#fbbf24` (Amber) |
773
+
774
+ ::: tip
775
+ Sphere data currently does not write to the layer MaskVolume — it is displayed as an overlay only. The channel mapping is reserved for future integration.
776
+ :::
777
+
778
+ ---
779
+
780
+ ## 5. MaskVolume Storage & Rendering
781
+
782
+ ### 5.1 Memory Layout
783
+
784
+ **File**: `core/MaskVolume.ts`
785
+
786
+ ```
787
+ Memory layout: [z][y][x][channel]
788
+ index = z * bytesPerSlice + y * width * channels + x * channels + channel
789
+ bytesPerSlice = width * height * channels
790
+ ```
791
+
792
+ Underlying data structure: a single contiguous `Uint8Array`
793
+
794
+ ### 5.2 Slice Dimensions per Axis
795
+
796
+ | Axis | Slice Width | Slice Height | Notes |
797
+ |------|-------------|--------------|-------|
798
+ | z (Axial) | width | height | Most common, contiguous memory |
799
+ | y (Coronal) | width | depth | Extracted row by row |
800
+ | x (Sagittal) | depth | height | Extracted pixel by pixel, slowest |
801
+
802
+ emptyCanvas size configuration: `SliceRenderPipeline.setEmptyCanvasSize()` → `tools/SliceRenderPipeline.ts`
803
+
804
+ ### 5.3 Slice Extraction (reading mask)
805
+
806
+ **`getSliceUint8(sliceIndex, axis)`**
807
+
808
+ Returns a raw `Uint8Array`, used for backend sync and Undo/Redo snapshots.
809
+
810
+ Per-axis implementation:
811
+ - **Z axis**: Contiguous memory `subarray` bulk copy (fastest)
812
+ - **Y axis**: Row-by-row iteration copy
813
+ - **X axis**: Pixel-by-pixel extraction (slowest)
814
+
815
+ ### 5.4 Slice Write
816
+
817
+ **`setSliceUint8(sliceIndex, data, axis)`** — Inverse of `getSliceUint8`, used for Undo/Redo restoration.
818
+
819
+ **`setSliceLabelsFromImageData(sliceIndex, imageData, axis, activeChannel, channelVisible?)`** — Canvas → Volume write: converts RGBA pixels into channel labels. Uses `ALPHA_THRESHOLD = 128` to avoid anti-aliasing edge artifacts.
820
+
821
+ An exact RGB match is resolved through `buildRgbToChannelMap()`. A pixel that matches nothing — an anti-aliased edge — falls through to a nearest-colour search, and **that search is restricted to candidate labels**: the labels already present on this slice, plus `activeChannel`. One cheap pass collects them.
822
+
823
+ Widening the search to all 255 would not merely be 255 distance computations per fringe pixel. It would be wrong: the more colours the guess can choose from, the more readily a fringe resolves to a label that is nowhere on the slice, which puts voxels into another finding's mask with nothing on screen to show for it.
824
+
825
+ **`clearChannel(channel)`** — Zero every voxel carrying one label, leaving the others in place. Label-based volumes only (`numChannels === 1`, i.e. the voxel value *is* the label); a multi-plane volume stores channels as separate planes and would need a different sweep. Throws `RangeError` outside [1, 255]. The `version` counter is bumped **only if a voxel actually changed** — every derived cache keyed on it (the contour cache above all) is invalidated by a bump, so bumping for a clear that found nothing would redraw the layer for no reason.
826
+
827
+ ### 5.5 Rendering to Canvas
828
+
829
+ **Core render method: `renderLabelSliceInto()`**
830
+
831
+ ```ts
832
+ renderLabelSliceInto(
833
+ sliceIndex: number,
834
+ axis: 'x' | 'y' | 'z',
835
+ target: ImageData,
836
+ channelVisible?: Record<number, boolean>,
837
+ opacity: number = 1.0
838
+ ): void
839
+ ```
840
+
841
+ Rendering logic:
842
+ 1. Read label value (0–255)
843
+ 2. `label === 0` → transparent (RGBA all zero)
844
+ 3. `channelVisible?.[label] === false` → hidden channel → transparent
845
+ 4. Otherwise → read color from volume's `colorMap` (supports per-layer custom colors), apply opacity
846
+
847
+ ::: tip
848
+ **Phase B change**: Color source changed from global `MASK_CHANNEL_COLORS` to each volume instance's `this.colorMap`. `buildRgbToChannelMap()` is also now an instance method, ensuring correct custom color mapping during canvas → volume write-back.
849
+ :::
850
+
851
+ ::: warning Two readback rules that changed with the 255-channel range
852
+ **`=== false`, not falsy** (step 3). `channelVisible` records what has been *hidden* and never
853
+ covers every label. `setSliceLabelsFromImageData` already read it that way; reading it as
854
+ falsy here made any label the map did not mention render as invisible — which was harmless
855
+ while eight channels were always listed, and is not once a label can be any of 255.
856
+
857
+ **`buildRgbToChannelMap()` covers every label the instance has a colour for**, not a fixed
858
+ 1–8. A pixel painted in channel 12's colour used to miss the table entirely and fall through
859
+ to the nearest-colour guess, which could only ever answer 1–8 — so a high channel could be
860
+ drawn and could never be read back. Size is not a cost: the map is built once per readback
861
+ and every lookup against it is O(1).
862
+ :::
863
+
864
+ ### 5.6 Full Rendering Pipeline
865
+
866
+ **Entry point: `reloadMasksFromVolume()`** — `SliceRenderPipeline.reloadMasksFromVolume()`
867
+
868
+ ```
869
+ reloadMasksFromVolume()
870
+ │
871
+ ├─ getOrCreateSliceBuffer(axis) → get/create reusable ImageData buffer
872
+ │ [RenderingUtils.ts]
873
+ │
874
+ ├─ FOR EACH layer:
875
+ │ ├─ target.ctx.clearRect(...) → clear layer canvas
876
+ │ └─ renderSliceToCanvas(layerId, axis, sliceIndex, buffer, target.ctx, w, h)
877
+ │ [RenderingUtils.ts] → drawSlice(..., outline = maskRenderMode === "outline")
878
+ │ │
879
+ │ ├─ cache miss? volume.getSliceUint8 → findLabelsInSlice → buildPaths
880
+ │ │ fill: extractLabelContours(...) → Path2D per label
881
+ │ │ outline: extractLabelOutline(...) → Path2D per label
882
+ │ │
883
+ │ └─ FOR EACH visible label: set fill/stroke from volume.getChannelColor(lbl)
884
+ │ fill: ctx.scale(sw/W, sh/H) then ctx.fill(path, 'nonzero')
885
+ │ outline: DOMMatrix on the PATH, ctx untransformed, ctx.stroke(...)
886
+ │ ⚠️ coronal view (axis='y') applies a scale(1,-1) vertical flip (see §6.2) —
887
+ │ on the context in fill mode, folded into the matrix in outline mode
888
+ │
889
+ └─ compositeAllLayers() → composite onto master canvas
890
+ ├─ masterCtx.clearRect(...)
891
+ └─ FOR EACH layer:
892
+ ├─ if !layerVisibility[layerId] → skip
893
+ ├─ masterCtx.save()
894
+ ├─ masterCtx.globalAlpha = layerOpacity[layerId] ← per-layer alpha
895
+ ├─ masterCtx.drawImage(layerCanvas)
896
+ └─ masterCtx.restore()
897
+ ```
898
+
899
+ > **Per-Layer Alpha in Rendering**: Each layer's canvas is composited with its individual `layerOpacity` value applied via `masterCtx.globalAlpha`. The existing `globalAlpha` (from `gui_states.drawing`) controls overall mask transparency, while `layerOpacity` provides independent per-layer control. Final alpha = `globalAlpha × layerOpacity[layerId]`.
900
+
901
+ ### 5.7 Marching Squares (`core/MarchingSquares.ts`)
902
+
903
+ The vector extraction behind both render modes. All four are exported from the package root.
904
+
905
+ | Function | Returns | Description |
906
+ |----------|---------|-------------|
907
+ | `findLabelsInSlice(labels, w, h, stride?, offset?, bbox?)` | `number[]` | Distinct non-zero labels present in the region |
908
+ | `extractLabelPolygons(...)` | `ContourPolygon[]` | Per-cell polygons covering the region |
909
+ | `extractLabelContours(...)` | `Path2D` | The above as a path — **fill** this |
910
+ | `extractLabelBoundarySegments(...)` | `ContourPolygon[]` | The region's edge, as open two-point segments |
911
+ | `extractLabelOutline(...)` | `Path2D` | The above as a path — **stroke** this |
912
+
913
+ All take `(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox?)`.
914
+
915
+ ::: danger Do not stroke the contour path
916
+ `extractLabelContours` is per-cell polygons whose *union* is the silhouette. Stroking it draws
917
+ every internal cell edge as well, covering the mask in a grid. Stroke `extractLabelOutline`.
918
+ :::
919
+
920
+ **How the two tables relate.** `CELL_SEGMENTS` has one entry per marching-squares case, and
921
+ each is the cut line of the corresponding `CELL_POLYGONS` entry — the one polygon edge that
922
+ does *not* lie on the cell border. Filling the polygons and stroking the segments therefore
923
+ describe the same silhouette, which is what lets the renderer swap fill for outline without
924
+ the mask's edge appearing to move. Endpoints are side midpoints in the same cell-local 0..1
925
+ space, so the caller adds `(i, j) + 0.5` identically for both.
926
+
927
+ Cases 0 and 15 emit no segments. **15 is why an outline is cheap**: solid interior has no
928
+ boundary, so the segment count follows the perimeter rather than the area.
929
+
930
+ Saddles (5 and 10) follow `CELL_POLYGONS`' convention — the two in-corners are disconnected
931
+ (4-connectivity) — because the other reading would run a boundary straight through mask the
932
+ fill considers solid.
933
+
934
+ ---
935
+
936
+ ## 6. Flip Mechanism
937
+
938
+ ### 6.1 Display Flip (CT/MRI image only)
939
+
940
+ **`flipDisplayImageByAxis()`** — `SliceRenderPipeline.flipDisplayImageByAxis()`
941
+
942
+ Because the slices rendered by Three.js are not in the correct 2D orientation, the displayCanvas must be flipped:
943
+
944
+ | Axis | Flip |
945
+ |------|------|
946
+ | x (Sagittal) | `scale(-1, -1)` + `translate(-w, -h)` |
947
+ | y (Coronal) | `scale(1, -1)` + `translate(0, -h)` |
948
+ | z (Axial) | `scale(1, -1)` + `translate(0, -h)` |
949
+
950
+ Called from: `SliceRenderPipeline.redrawDisplayCanvas()`
951
+
952
+ ### 6.2 Mask Flip (Coronal only)
953
+
954
+ **Important**: In `renderSliceToCanvas()` (RenderingUtils.ts), mask rendering **applies a vertical flip for the coronal view (axis='y')**:
955
+
956
+ ```ts
957
+ if (axis === 'y') {
958
+ targetCtx.save();
959
+ targetCtx.scale(1, -1);
960
+ targetCtx.translate(0, -scaledHeight);
961
+ }
962
+ targetCtx.drawImage(emptyCanvas, 0, 0, scaledWidth, scaledHeight);
963
+ if (axis === 'y') targetCtx.restore();
964
+ ```
965
+
966
+ | Axis | Mask Flip | Notes |
967
+ |------|-----------|-------|
968
+ | z (Axial) | **None** | Storage coordinates match Three.js slice |
969
+ | y (Coronal) | **Vertical flip** `scale(1,-1)` | Cancels out the flip in the write path, ensuring cross-axis display consistency |
970
+ | x (Sagittal) | **None** | Storage coordinates match Three.js slice |
971
+
972
+ ::: warning
973
+ Previous documentation stating "mask has no flip" is outdated. A Y-axis flip was introduced for the coronal view to fix a cross-axis slice alignment bug.
974
+ :::
975
+
976
+ ### 6.3 applyMaskFlipForAxis (helper method)
977
+
978
+ `RenderingUtils.applyMaskFlipForAxis()` — provides the same flip transform as `flipDisplayImageByAxis()`, available for scenarios requiring manual coordinate alignment.
979
+
980
+ ---
981
+
982
+ ## 7. Tools
983
+
984
+ Location: `src/Utils/segmentation/tools/`
985
+
986
+ All Tools / modules extend `BaseTool` (`tools/BaseTool.ts`):
987
+
988
+ ```ts
989
+ interface ToolContext {
990
+ nrrd_states: NrrdState;
991
+ gui_states: GuiState;
992
+ protectedData: IProtected;
993
+ cursorPage: ICursorPage;
994
+ callbacks: IAnnotationCallbacks;
995
+ }
996
+ abstract class BaseTool {
997
+ constructor(ctx: ToolContext)
998
+ setContext(ctx: ToolContext): void
999
+ }
1000
+ ```
1001
+
1002
+ ### 7.1 Tool List
1003
+
1004
+ ::: tip
1005
+ **ToolHost unified interface (complete)**: All Tool host method dependencies have been unified into the `ToolHost` interface in `tools/ToolHost.ts`. Each Tool selects its required method subset via `Pick<ToolHost, ...>`. The original 10 independent `*Callbacks` interfaces have been removed.
1006
+ :::
1007
+
1008
+ #### NrrdTools Extracted Modules (God Class Split)
1009
+
1010
+ | Module | File | Lines | HostDeps Type |
1011
+ |--------|------|-------|---------------|
1012
+ | **LayerChannelManager** | `tools/LayerChannelManager.ts` | 211 | `LayerChannelHostDeps` (3 methods) |
1013
+ | **SliceRenderPipeline** | `tools/SliceRenderPipeline.ts` | 453 | `SliceRenderHostDeps` (10 methods) |
1014
+ | **DataLoader** | `tools/DataLoader.ts` | 222 | `DataLoaderHostDeps` (7 methods) |
1015
+
1016
+ #### DrawToolCore-Managed Tools (event handling)
1017
+
1018
+ | Tool | File | Description |
1019
+ |------|------|-------------|
1020
+ | **SphereTool** | `tools/SphereTool.ts` | 3D sphere annotation; 4 types (tumour/skin/ribcage/nipple); click-to-place + release-to-confirm |
1021
+ | **CrosshairTool** | `tools/CrosshairTool.ts` | Crosshair position marker, coordinate conversion, crosshair rendering |
1022
+ | **ContrastTool** | `tools/ContrastTool.ts` | Window/Level (brightness/contrast) adjustment |
1023
+ | **ZoomTool** | `tools/ZoomTool.ts` | Zoom and pan |
1024
+ | **EraserTool** | `tools/EraserTool.ts` | Eraser |
1025
+ | **PanTool** | `tools/PanTool.ts` | Right-click drag to pan the canvas |
1026
+ | **DrawingTool** | `tools/DrawingTool.ts` | Pencil/brush/eraser drawing; brush hover tracking; circle preview |
1027
+ | **SphereBrushTool** | `tools/SphereBrushTool.ts` | 3D sphere volume painting (sphereBrush) and erasing (sphereEraser); drag-to-erase; grouped multi-slice undo |
1028
+ | **ImageStoreHelper** | `tools/ImageStoreHelper.ts` | Canvas ↔ Volume sync |
1029
+ | **DragSliceTool** | `tools/DragSliceTool.ts` | Drag to scroll through slices |
1030
+
1031
+ Tool initialization: `DrawToolCore.ts` → `initTools()`
1032
+
1033
+ #### Annotation suspension gate
1034
+
1035
+ `DrawToolCore.onCanvasPointerDown(e)` is the single point at which an input is allowed to
1036
+ modify a mask. It exists as a named method rather than an inline closure in `draw()` so the
1037
+ gate can be exercised directly in tests.
1038
+
1039
+ ```
1040
+ onCanvasPointerDown(e)
1041
+ │
1042
+ ├─ drawingTool.isActive || panTool.isActive? → closePath, return
1043
+ ├─ sync paintSliceIndex to the current slice
1044
+ ├─ mode === 'draw'? → activeWheelMode = 'none'
1045
+ │
1046
+ ├─ e.button === 0
1047
+ │ ├─ annotationSuspended && !crosshairEnabled? → return ◀ the gate
1048
+ │ ├─ mode 'aiAssist' → aiAssistTool.onPointerDown
1049
+ │ ├─ mode 'draw' → drawingTool.onPointerDown
1050
+ │ ├─ crosshair on → enableCrosshair (read-only, survives the gate)
1051
+ │ ├─ sphereBrush → sphereBrushTool.onSphereBrushClick
1052
+ │ ├─ sphereEraser → sphereBrushTool.onSphereEraserClick
1053
+ │ └─ sphere → handleSphereClick
1054
+ │
1055
+ └─ e.button === 2 → panTool.onPointerDown (pan survives the gate)
1056
+ ```
1057
+
1058
+ `handleOnDrawingMouseMove` carries the same early return, so a drag that began before
1059
+ suspension cannot continue painting through it.
1060
+
1061
+ ##### Pointer-up is gated too <Badge type="tip" text="3.11.1" />
1062
+
1063
+ `onCanvasPointerUp(e)` is the matching named method, extracted for the same reason — so the
1064
+ gate can be exercised directly. Its left-button condition is **not** simply "are we in draw
1065
+ mode":
1066
+
1067
+ ```ts
1068
+ if (
1069
+ this.drawingTool.painting ||
1070
+ (this.eventRouter.getMode() === 'draw' && !this.annotationSuspended)
1071
+ ) { this.drawingTool.onPointerUp(e); ... }
1072
+ ```
1073
+
1074
+ `getMode() === 'draw'` reports only that Shift is held with a drawing tool selected — it does
1075
+ not know whether a stroke began. On a suspended instance pointer-down is gated, so no stroke
1076
+ ever starts, yet holding Shift and releasing the mouse still reported `'draw'` and reached
1077
+ `drawingTool.onPointerUp`, which threw inside `setCurrentLayer` with no layer to target.
1078
+
1079
+ `drawingTool.painting` is the reliable signal: it is only ever true once a stroke has actually
1080
+ started. A suspended instance can never set it, so it never reaches `onPointerUp`; an
1081
+ in-progress stroke that outlives a mid-drag suspension still gets its proper release.
1082
+
1083
+ Two consequences of gating here rather than per tool:
1084
+
1085
+ - A tool added later is covered without being told about suspension.
1086
+ - The `!crosshairEnabled` escape applies only to a read-only probe. It cannot leak a stroke
1087
+ through, because `EventRouter` makes crosshair and `draw` mutually exclusive:
1088
+ `applyDrawKeyDown` refuses to enter `draw` while the crosshair is on, and `toggleCrosshair`
1089
+ refuses to turn it on while the mode is `draw`.
1090
+
1091
+ Exposed on the facade as `NrrdTools.setAnnotationSuspended()` / `isAnnotationSuspended()`.
1092
+
1093
+ ### 7.2 ImageStoreHelper (key tool)
1094
+
1095
+ **`storeAllImages(index, layer)`** — Canvas → Volume sync flow:
1096
+ 1. Draw the layer canvas onto emptyCanvas
1097
+ 2. Read ImageData from emptyCanvas
1098
+ 3. Call `volume.setSliceLabelsFromImageData()` to write to MaskVolume
1099
+ 4. Extract the slice and notify the backend
1100
+
1101
+ **`filterDrawedImage(axis, sliceIndex)`** — Volume → Canvas read: calls `volume.renderLabelSliceInto()`.
1102
+
1103
+ ### 7.3 SphereTool
1104
+
1105
+ **File**: `tools/SphereTool.ts`
1106
+
1107
+ ```ts
1108
+ type SphereType = 'tumour' | 'skin' | 'nipple' | 'ribcage';
1109
+
1110
+ const SPHERE_CHANNEL_MAP: Record<SphereType, { layer: string; channel: number }>;
1111
+ // SPHERE_COLORS removed — colors derived dynamically from each volume's colorMap
1112
+ const SPHERE_LABELS: Record<SphereType | 'default', number>;
1113
+ ```
1114
+
1115
+ **Interaction Methods:**
1116
+
1117
+ | Method | Description |
1118
+ |--------|-------------|
1119
+ | `onSphereClick(e)` | Left-click: record origin, store typed origin, enable crosshair, draw preview |
1120
+ | `onSpherePointerUp()` | Left-click release: write all spheres to volume, refresh overlay, fire callbacks |
1121
+
1122
+ **SphereHostDeps:**
1123
+
1124
+ ```ts
1125
+ type SphereHostDeps = Pick<ToolHost,
1126
+ 'setEmptyCanvasSize' | 'drawImageOnEmptyImage' | 'enableCrosshair' | 'setUpSphereOrigins'
1127
+ >;
1128
+ ```
1129
+
1130
+ **Interaction constraints when sphere mode is active:**
1131
+ - ❌ Shift key disabled (cannot enter draw mode)
1132
+ - ✅ Crosshair toggle available (S key)
1133
+ - ❌ Contrast mode blocked
1134
+
1135
+ **Interaction flow:**
1136
+
1137
+ ```
1138
+ Left mouse down → record origin for activeSphereType → activeWheelMode = 'sphere' → draw preview
1139
+ Scroll wheel (while held) → sphereRadius ±1 [1, 50] → redraw
1140
+ Left mouse up → write all spheres to volume → fire getSphere + getCalculateSpherePositions → activeWheelMode = 'zoom'
1141
+ ```
1142
+
1143
+ **SphereMaskVolume:** An independent `MaskVolume` (`nrrd_states.sphereMaskVolume`) stores sphere 3D data without polluting layer draw masks. Created in `setAllSlices()`, cleared in `reset()`.
1144
+
1145
+ ### 7.4 PanTool
1146
+
1147
+ **File**: `tools/PanTool.ts` — 124 lines. Handles all right-click drag pan logic.
1148
+
1149
+ ::: warning
1150
+ `getPanelOffset` / `setPanelOffset` callbacks no longer exist. PanTool reads offsets directly via `canvas.offsetLeft` / `canvas.offsetTop`.
1151
+ :::
1152
+
1153
+ ```ts
1154
+ type PanHostDeps = Pick<ToolHost, 'zoomActionAfterDrawSphere'>;
1155
+ ```
1156
+
1157
+ ### 7.5 SphereBrushTool
1158
+
1159
+ **File**: `tools/SphereBrushTool.ts` — 584 lines. Handles 3D sphere volume painting (SphereBrush mode) and 3D sphere volume erasing (SphereEraser mode), including drag-to-erase and grouped multi-slice undo.
1160
+
1161
+ Unlike the SphereTool (which writes to a separate `sphereMaskVolume` overlay), SphereBrushTool writes directly to the active layer's shared `MaskVolume`, making its output fully compatible with NIfTI/GLTF export.
1162
+
1163
+ #### SphereBrushHostDeps
1164
+
1165
+ ```ts
1166
+ type SphereBrushHostDeps = Pick<ToolHost,
1167
+ 'getVolumeForLayer' | 'compositeAllLayers' | 'pushUndoGroup'
1168
+ | 'renderSliceToCanvas' | 'getOrCreateSliceBuffer' | 'setEmptyCanvasSize'
1169
+ | 'reloadMasksFromVolume'
1170
+ >;
1171
+ ```
1172
+
1173
+ #### Key Methods
1174
+
1175
+ | Method | Description |
1176
+ |--------|-------------|
1177
+ | `onSphereBrushClick(e)` | Left-click: record center, draw preview, set active |
1178
+ | `onSphereBrushPointerUp()` | Release: write 3D sphere to volume, push undo group, fire onMaskChanged for all affected slices |
1179
+ | `onSphereEraserClick(e)` | Left-click: record center, capture before-snapshots for all affected Z-slices |
1180
+ | `onSphereEraserMove(e)` | Drag: continuously erase along path, lazily expand before-snapshots |
1181
+ | `onSphereEraserPointerUp()` | Release: finalize cumulative erase, push undo group, fire onMaskChanged for all affected slices |
1182
+ | `configSphereBrushWheel()` | Returns wheel handler that adjusts `sphereBrushRadius` ±1 [1, 50] |
1183
+ | `drawPreview(x, y, r, isEraser)` | Render sphere preview circle on sphereCanvas |
1184
+ | `clearPreview()` | Clear preview from sphereCanvas |
1185
+
1186
+ #### 3D Geometry
1187
+
1188
+ - **`canvasToVoxelCenter()`**: Converts canvas pixel coordinates to 3D voxel center `[cx, cy, cz]`
1189
+ - **`getVoxelRadii()`**: Computes per-axis voxel radii from mm radius and voxel spacing
1190
+ - **`computeBoundingBox()`**: Computes axis-aligned bounding box clamped to volume bounds
1191
+ - **Sphere equation**: `(dx/rx)² + (dy/ry)² + (dz/rz)² <= 1` (ellipsoid to handle anisotropic spacing)
1192
+
1193
+ #### Undo Mechanism
1194
+
1195
+ SphereBrush uses **grouped undo** (`pushUndoGroup(MaskDelta[])`) instead of single-delta undo:
1196
+
1197
+ ```
1198
+ SphereBrush:
1199
+ mousedown → capture before-snapshot for all Z-slices in bounding box
1200
+ mouseup → capture after-snapshot, diff → push MaskDelta[] group
1201
+
1202
+ SphereEraser (click-release):
1203
+ mousedown → capture before-snapshots (dragBeforeSnapshots)
1204
+ mouseup → diff before vs current → push MaskDelta[] group
1205
+
1206
+ SphereEraser (drag):
1207
+ mousedown → init dragBeforeSnapshots for initial bounding box
1208
+ mousemove → expandDragBeforeSnapshots for newly touched Z-slices
1209
+ mouseup → diff cumulative before vs current → push single MaskDelta[] group
1210
+ ```
1211
+
1212
+ #### Backend Sync
1213
+
1214
+ `refreshDisplay()` fires `onMaskChanged` for **every** affected Z-slice (not just the current viewing slice), ensuring correct NIfTI and GLTF export of the full 3D sphere.
1215
+
1216
+ ### 7.6 DrawingTool
1217
+
1218
+ **File**: `tools/DrawingTool.ts` — 284 lines. Handles pencil, brush, and eraser drawing logic including Undo snapshots.
1219
+
1220
+ ```ts
1221
+ type DrawingHostDeps = Pick<ToolHost,
1222
+ 'setCurrentLayer' | 'compositeAllLayers' | 'syncLayerSliceData'
1223
+ | 'filterDrawedImage' | 'getVolumeForLayer' | 'pushUndoDelta'
1224
+ | 'renderSliceToCanvas' | 'renderSliceForBake' | 'getOrCreateSliceBuffer'
1225
+ >;
1226
+ ```
1227
+
1228
+ **`onPointerLeave()` return value**: Returns `true` if the user was drawing when leaving the canvas, signaling DrawToolCore to restore `activeWheelMode = 'zoom'`.
1229
+
1230
+ **Undo snapshot mechanism:**
1231
+
1232
+ ```
1233
+ mousedown → capturePreDrawSnapshot()
1234
+ → volume.getSliceUint8(sliceIndex, axis) ← before operation
1235
+ → saved to preDrawSlice / preDrawAxis / preDrawSliceIndex
1236
+
1237
+ mouseup → pushUndoDelta()
1238
+ → volume.getSliceUint8(sliceIndex, axis) ← after operation
1239
+ → pushUndoDelta({ layerId, axis, sliceIndex, oldSlice: preDrawSlice, newSlice })
1240
+ ```
1241
+
1242
+ ---
1243
+
1244
+ ## 8. EventRouter
1245
+
1246
+ **File**: `eventRouter/EventRouter.ts`
1247
+
1248
+ ### 8.1 Interaction Modes
1249
+
1250
+ | Mode | Trigger | Description |
1251
+ |------|---------|-------------|
1252
+ | `idle` | Default | No interaction |
1253
+ | `draw` | Shift held | Drawing mode |
1254
+ | `drag` | Vertical drag | Slice navigation |
1255
+ | `contrast` | Ctrl/Meta held | Window/Level adjustment |
1256
+ | `crosshair` | S key | Crosshair mode |
1257
+
1258
+ ### 8.2 Permanent Event Routing
1259
+
1260
+ EventRouter permanently binds all pointer/keyboard/wheel events to the drawingCanvas in `bindAll()`. DrawToolCore registers handlers via `set*Handler()` — no more manual `addEventListener`/`removeEventListener`.
1261
+
1262
+ | Handler | Guard Condition |
1263
+ |---------|-----------------|
1264
+ | `setPointerDownHandler` | None |
1265
+ | `setPointerMoveHandler` | `drawingTool.isActive \|\| panTool.isActive` |
1266
+ | `setPointerUpHandler` | `drawingTool.isActive \|\| drawingTool.painting \|\| panTool.isActive \|\| sphere mode` |
1267
+ | `setPointerLeaveHandler` | None |
1268
+ | `setWheelHandler` | Dispatches based on `activeWheelMode` |
1269
+
1270
+ ::: warning
1271
+ **Guard conditions are essential**: Without them, idle mouse movement would prevent the Brush preview and Crosshair from rendering (DrawingTool.onPointerMove unconditionally sets `isDrawing=true`).
1272
+ :::
1273
+
1274
+ ### 8.3 Wheel Dispatcher (`activeWheelMode`)
1275
+
1276
+ | Mode | Trigger | Dispatch Target |
1277
+ |------|---------|-----------------|
1278
+ | `'zoom'` | Default / restored after mouseUp | `handleMouseZoomSliceWheel` |
1279
+ | `'sphere'` | Set by `handleSphereClick` | `handleSphereWheel` |
1280
+ | `'sphereBrush'` | Set by sphereBrush/sphereEraser mouseDown | `handleSphereBrushWheel` (adjusts `sphereBrushRadius`) |
1281
+ | `'none'` | Set by mouseDown in draw mode | No-op (wheel suppressed) |
1282
+
1283
+ ### 8.4 Default Keyboard Settings
1284
+
1285
+ ```ts
1286
+ IKeyBoardSettings = {
1287
+ draw: "Shift",
1288
+ undo: "z",
1289
+ redo: "y",
1290
+ contrast: ["Control", "Meta"],
1291
+ crosshair: "s",
1292
+ sphere: "q",
1293
+ mouseWheel: "Scroll:Zoom", // or "Scroll:Slice"
1294
+ }
1295
+
1296
+ // Additional global shortcuts (handled in DrawToolCore keydown, not configurable):
1297
+ // Ctrl+1 → switch to Scroll:Zoom
1298
+ // Ctrl+2 → switch to Scroll:Slice
1299
+ ```
1300
+
1301
+ ---
1302
+
1303
+ ## 9. Undo/Redo System
1304
+
1305
+ **File**: `core/UndoManager.ts`
1306
+
1307
+ ```ts
1308
+ interface MaskDelta {
1309
+ layerId: string;
1310
+ axis: "x" | "y" | "z";
1311
+ sliceIndex: number;
1312
+ oldSlice: Uint8Array; // Slice data before the operation
1313
+ newSlice: Uint8Array; // Slice data after the operation
1314
+ }
1315
+ ```
1316
+
1317
+ - Independent undo/redo stack per layer
1318
+ - `MAX_STACK_SIZE = 50`
1319
+
1320
+ **Stacks are created on demand** <Badge type="tip" text="3.10.4" />, keyed by layer id, so any
1321
+ layer name works. They used to be pre-created for exactly `layer1` / `layer2` / `layer3`, which
1322
+ broke in two different ways for any other id — and `NrrdTools`'s constructor has always taken
1323
+ `options.layers`, so any other id is reachable:
1324
+
1325
+ | Call | Old behaviour with a custom layer id |
1326
+ |------|--------------------------------------|
1327
+ | `pushGroup` / `pushVolumeSnapshot` | resolved with `?? get("layer1")` and silently appended to **another layer's** history, so a later undo popped a stroke the user never made there |
1328
+ | `undo` / `redo` | asserted non-null on the same lookup and **threw** |
1329
+
1330
+ `stackFor(stacks, layerId)` creates the entry on first use, which removes both. Nothing else
1331
+ needs to know which layers exist, and `clearAll()` now iterates the maps rather than a fixed
1332
+ id list.
1333
+
1334
+ **Undo flow:**
1335
+
1336
+ ```
1337
+ DrawToolCore.undoLastPainting()
1338
+ → UndoManager.undo() → MaskDelta
1339
+ → vol.setSliceUint8(delta.sliceIndex, delta.oldSlice, delta.axis)
1340
+ → applyUndoRedoToCanvas(layerId)
1341
+ → getOrCreateSliceBuffer(axis)
1342
+ → renderSliceToCanvas(...)
1343
+ → compositeAllLayers()
1344
+ → annotationCallbacks.onMaskChanged(...) → notify backend
1345
+ ```
1346
+
1347
+ ---
1348
+
1349
+ ## 10. DragOperator
1350
+
1351
+ **File**: `DragOperator.ts` — Responsible for drag-based slice navigation.
1352
+
1353
+ ::: warning
1354
+ **Event Lifecycle Refactor change**: DragOperator no longer manually manages wheel event listeners. Wheel events are now entirely managed by EventRouter's `activeWheelMode` dispatcher.
1355
+ :::
1356
+
1357
+ | Method | Description |
1358
+ |--------|-------------|
1359
+ | `drag(opts?)` | Enable drag mode |
1360
+ | `configDragMode()` | Bind drag event listeners |
1361
+ | `removeDragMode()` | Remove drag event listeners |
1362
+ | `updateIndex(move)` | Delegates to DragSliceTool |
1363
+ | `setEventRouter(eventRouter)` | Subscribe to mode changes |
1364
+
1365
+ ---
1366
+
1367
+ ## 11. Channel Color Definitions
1368
+
1369
+ **File**: `core/types.ts`
1370
+
1371
+ ### 11.1 Default Colors (global constants)
1372
+
1373
+ | Channel | Color | Hex | RGBA |
1374
+ |---------|-------|-----|------|
1375
+ | 0 | Transparent | `#000000` | `(0,0,0,0)` |
1376
+ | 1 | Emerald (Tumour) | `#10b981` | `(16,185,129,255)` |
1377
+ | 2 | Rose (Edema) | `#f43f5e` | `(244,63,94,255)` |
1378
+ | 3 | Blue (Necrosis) | `#3b82f6` | `(59,130,246,255)` |
1379
+ | 4 | Amber (Enhancement) | `#fbbf24` | `(251,191,36,255)` |
1380
+ | 5 | Fuchsia (Vessel) | `#d946ef` | `(217,70,239,255)` |
1381
+ | 6 | Cyan (Additional) | `#06b6d4` | `(6,182,212,255)` |
1382
+ | 7 | Orange (Auxiliary) | `#f97316` | `(249,115,22,255)` |
1383
+ | 8 | Violet (Extended) | `#8b5cf6` | `(139,92,246,255)` |
1384
+
1385
+ Exported as: `MASK_CHANNEL_COLORS` (RGBA), `MASK_CHANNEL_CSS_COLORS` (CSS), `CHANNEL_HEX_COLORS` (Hex)
1386
+
1387
+ #### Channels 9–255 (generated)
1388
+
1389
+ `MAX_ENGINE_CHANNEL = 255` — one byte per voxel, the value *is* the label, so 0 is empty and
1390
+ 1–255 are channels. The engine does not cap below what the byte allows; a smaller product
1391
+ limit is the product's business.
1392
+
1393
+ Each palette is built by `extendPalette(seed, from)`, which copies the 0–8 table verbatim and
1394
+ fills 9–255 from `generatedChannelColor(channel)`:
1395
+
1396
+ ```
1397
+ hue = ((channel - 8 - 1) * 137.508) % 360 // golden angle
1398
+ saturation = 0.68 // fixed
1399
+ lightness = 0.55 // fixed
1400
+ ```
1401
+
1402
+ Two decisions worth knowing:
1403
+
1404
+ - **Only hue varies.** These sit on greyscale MRI; a mask whose *brightness* changes between
1405
+ channels reads as a difference in the image rather than in the annotation.
1406
+ - **The seeds are not regenerated.** Delivered cases' chips, 3D overlay tints and printed
1407
+ report outlines are keyed on the eight literals, so a formula that happened to produce
1408
+ different values would silently recolour work already read and signed off.
1409
+
1410
+ Built eagerly rather than behind a `Proxy`: `applyLayerChannelColors` walks these with
1411
+ `Object.entries`, which a `Proxy`'s `get` trap would not serve.
1412
+
1413
+ ::: warning
1414
+ `CHANNEL_COLORS` is declared *after* the tables it aliases. It used to sit above them, which
1415
+ was fine while they were object literals and is a temporal-dead-zone error now that they are
1416
+ built.
1417
+ :::
1418
+
1419
+ ### 11.2 Color Conversion Utilities
1420
+
1421
+ | Function | Signature | Description |
1422
+ |----------|-----------|-------------|
1423
+ | `rgbaToHex` | `(color: RGBAColor) → string` | Convert to Hex, e.g. `#ff8000` |
1424
+ | `rgbaToCss` | `(color: RGBAColor) → string` | Convert to CSS rgba(), e.g. `rgba(255,128,0,1.00)` |
1425
+
1426
+ ### 11.3 Per-Layer Custom Colors
1427
+
1428
+ Each `MaskVolume` instance owns an independent `colorMap: ChannelColorMap`, deep-copied from `MASK_CHANNEL_COLORS` at construction. Modifying a layer's color does not affect other layers.
1429
+
1430
+ **Color flow path:**
1431
+
1432
+ ```
1433
+ volume.colorMap[channel]
1434
+ ↓ renderLabelSliceInto() → canvas rendering reads colorMap
1435
+ ↓ buildRgbToChannelMap() → canvas → volume write-back reads colorMap
1436
+ ↓ EraserTool.getChannelColor → eraser color matching reads colorMap
1437
+ ↓ syncBrushColor() → brush color reads colorMap
1438
+ ↓ getChannelCssColor() → Vue UI reads colorMap for display
1439
+ ```
1440
+
1441
+ ---
1442
+
1443
+ ## 12. GaussianSmoother
1444
+
1445
+ **File**: `core/GaussianSmoother.ts`
1446
+
1447
+ Pure stateless utility class for 3D Gaussian smoothing of segmentation masks. No DOM/Canvas/GUI dependencies. Includes performance optimizations for direct typed-array access and branch-free convolution.
1448
+
1449
+ ### 12.1 Algorithm
1450
+
1451
+ Applies separable 3D Gaussian blur to a single label channel within a MaskVolume:
1452
+
1453
+ 1. **Extract**: Create a Float32Array with 1.0 where voxel === channel, 0.0 elsewhere (direct `rawData[]` access)
1454
+ 2. **Blur**: Apply separable Gaussian convolution (X → Y → Z) using 1D kernels truncated at ±3σ (branch-free middle segment)
1455
+ 3. **Threshold**: Binarize at 0.5
1456
+ 4. **Write back**: Overwrite/erase voxels according to the thresholded result (direct `rawData[]` access)
1457
+
1458
+ ### 12.1.1 Performance Optimizations
1459
+
1460
+ Two key optimizations reduce execution time significantly:
1461
+
1462
+ 1. **Direct array access** — The extract and write-back phases bypass `getVoxel()`/`setVoxel()` (which perform 6 boundary checks + function call overhead per voxel). Instead, `volume.getRawData()` gives direct access to the underlying `Uint8Array`, and indices are computed inline using `volume.getBytesPerSlice()` and `volume.getChannels()`:
1463
+
1464
+ ```typescript
1465
+ const rawData = volume.getRawData();
1466
+ const channels = volume.getChannels();
1467
+ const bytesPerSlice = volume.getBytesPerSlice();
1468
+ const rowStride = width * channels;
1469
+ // Direct access: rawData[zOffset + yOffset + x * channels]
1470
+ ```
1471
+
1472
+ 2. **Branch-free convolution** — `convolve1D` splits the loop into three segments: left boundary (lower bound check), middle interior (no branching, ~95% of work), right boundary (upper bound check):
1473
+
1474
+ ```typescript
1475
+ // Middle segment — NO bounds check
1476
+ for (let i = midStart; i < midEnd; i++) {
1477
+ let sum = 0;
1478
+ const lineOffset = i - radius;
1479
+ for (let k = 0; k < kLen; k++) {
1480
+ sum += line[lineOffset + k] * kernel[k];
1481
+ }
1482
+ data[lineStart + i * stride] = sum;
1483
+ }
1484
+ ```
1485
+
1486
+ > **Impact scope**: Only `GaussianSmoother.ts` is modified. All other tools continue using `getVoxel`/`setVoxel` with full boundary checks — zero impact on existing code.
1487
+
1488
+ ### 12.2 Public API
1489
+
1490
+ | Method | Signature | Description |
1491
+ |--------|-----------|-------------|
1492
+ | `gaussianSmooth3D` | `(volume: MaskVolume, channel: number, sigma?: number, spacing?: [number, number, number]): void` | Smooth a single label channel in-place using separable 3D Gaussian blur |
1493
+ | `generateKernel1D` | `(sigma: number): Float32Array` | Generate a normalized 1D Gaussian kernel truncated at ±3σ |
1494
+
1495
+ ### 12.3 Anisotropic Spacing
1496
+
1497
+ When `spacing` is provided, per-axis sigma is computed as `sigma / spacing[axis]` to ensure isotropic physical smoothing:
1498
+
1499
+ ```typescript
1500
+ const sigmaX = spacing ? sigma / spacing[0] : sigma;
1501
+ const sigmaY = spacing ? sigma / spacing[1] : sigma;
1502
+ const sigmaZ = spacing ? sigma / spacing[2] : sigma;
1503
+ ```
1504
+
1505
+ ### 12.4 NrrdTools Integration
1506
+
1507
+ `executeAction("gaussianSmooth", { sigma })` in NrrdTools:
1508
+
1509
+ 1. Identifies the active layer and channel
1510
+ 2. Snapshots all Z-slices containing the target channel (undo support via `MaskDelta[]`)
1511
+ 3. Calls `GaussianSmoother.gaussianSmooth3D()` with voxel spacing from `nrrd_states.image.voxelSpacing`
1512
+ 4. Captures post-smoothing slice data and pushes undo group via `undoManager.pushGroup()`
1513
+ 5. Fires `onMaskChanged` callback for each modified slice (backend sync)
1514
+ 6. Calls `reloadMasksFromVolume()` to refresh canvas display
1515
+
1516
+ ```
1517
+ executeAction("gaussianSmooth", { sigma })
1518
+ │
1519
+ ├─ snapshot all affected Z-slices (oldSlice)
1520
+ │
1521
+ ├─ GaussianSmoother.gaussianSmooth3D(volume, channel, sigma, spacing)
1522
+ │
1523
+ ├─ capture newSlice for each delta
1524
+ │
1525
+ ├─ undoManager.pushGroup(deltas)
1526
+ │
1527
+ ├─ FOR EACH affected slice:
1528
+ │ └─ onMaskChanged(sliceData, layerId, channel, z, "z", width, height, false)
1529
+ │
1530
+ └─ reloadMasksFromVolume()
1531
+ ```
1532
+
1533
+ ### 12.5 Vue UI Integration
1534
+
1535
+ - **Button**: "Smoothing: Gaussian" in `OperationCtl.vue` (`commFuncBtnValues`)
1536
+ - **Slider**: "Smooth Sigma" radio in `commSliderRadioValues` (range 0.5–5.0, step 0.5, default 1.0)
1537
+ - **Loading animation**: Emits `Segmentation:SwitchAnimationStatus` event during execution
1538
+ - **Toast notification**: Success/failure toast via `useToast` composable
1539
+ - **Emitter event**: `Segmentation:SwitchAnimationStatus` (registered in `custom-emitter.ts` event whitelist)