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