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,388 @@
|
|
|
1
|
+
# Copper3D Surface Annotation API — English
|
|
2
|
+
|
|
3
|
+
> Available since `copper3d_visualisation` v3.6.0-beta
|
|
4
|
+
> Module: `src/ts/Utils/surfaceAnnotation/`, exposed via `copperScene.createSurfaceAnnotator()`
|
|
5
|
+
|
|
6
|
+
## 1. Overview
|
|
7
|
+
|
|
8
|
+
Surface annotation lets you draw on the surface of **any 3D model**:
|
|
9
|
+
|
|
10
|
+
- Draw **contour lines**, in two modes:
|
|
11
|
+
- **Freehand**: hold the left mouse button and drag; the stroke is projected onto the surface in real time.
|
|
12
|
+
- **Geodesic**: click a few anchor points; the path is the shortest route along the mesh surface (hugs the terrain), smoothed for a clean curve. **Drag** an anchor to move it, **right-click** to delete, **click the line** to insert one; `Enter` finishes. A finished geodesic can be re-selected later to edit its anchors again.
|
|
13
|
+
- Drop **fiducial points**.
|
|
14
|
+
- Contours can be **closed into a loop** (the closing segment also follows the surface — it does not cut through the model).
|
|
15
|
+
- **Multiple annotations**, each with a color and label; select / rename / recolor / delete / undo / clear.
|
|
16
|
+
- **Export coordinates** as JSON, defaulting to **model-local coordinates** (reproducible, unaffected by camera or model placement).
|
|
17
|
+
|
|
18
|
+
**Format-agnostic**: the annotator operates on a `THREE.Mesh` and bundles no loader. OBJ / glTF / GLB / VTK / STL… anything you can load into a mesh works. You may also pass a `Group/Object3D` (the largest mesh is picked automatically).
|
|
19
|
+
|
|
20
|
+
**Non-destructive**: geodesics require geometry that is connected by surface position. The annotator internally welds a **position-only copy** of the geometry for pathfinding and **never modifies your mesh's normals / UVs / textures**.
|
|
21
|
+
|
|
22
|
+
## 2. Quick Start
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import * as Copper from "copper3d_visualisation";
|
|
26
|
+
|
|
27
|
+
const appRenderer = new Copper.copperRenderer(container, { guiOpen: false });
|
|
28
|
+
const scene = appRenderer.createScene("annot") as Copper.copperScene;
|
|
29
|
+
appRenderer.setCurrentScene(scene);
|
|
30
|
+
appRenderer.animate();
|
|
31
|
+
|
|
32
|
+
// Load a model with a copper loader, create the annotator in the callback
|
|
33
|
+
scene.loadOBJ("/models/heart.obj", (group) => {
|
|
34
|
+
const annotator = scene.createSurfaceAnnotator(group);
|
|
35
|
+
|
|
36
|
+
annotator.setMode("freehand"); // or "geodesic" / "point" / "navigate"
|
|
37
|
+
|
|
38
|
+
// Export (local coordinates by default)
|
|
39
|
+
// const data = annotator.exportJSON("heart.obj");
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
> **Framing & lighting are your responsibility.** The annotator only reuses the scene's camera/container/controls; it does not set the camera or add lights. Use `scene.loadViewUrl()`, set the camera yourself, or add your own lights.
|
|
44
|
+
|
|
45
|
+
## 3. API Reference
|
|
46
|
+
|
|
47
|
+
### 3.1 `copperScene.createSurfaceAnnotator(target, opts?)`
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
createSurfaceAnnotator(
|
|
51
|
+
target: THREE.Mesh | THREE.Object3D,
|
|
52
|
+
opts?: {
|
|
53
|
+
freehandColor?: string; // freehand color, default "#e5006e"
|
|
54
|
+
geodesicColor?: string; // geodesic color, default "#ffa24e"
|
|
55
|
+
pointColor?: string; // marker color, default "#ffd166"
|
|
56
|
+
lineWidth?: number; // line width (px), default 3
|
|
57
|
+
markerRadius?: number; // sphere radius, default bboxDiagonal * 0.0032
|
|
58
|
+
bboxDiagonal?: number; // size reference; auto-computed from geometry if omitted
|
|
59
|
+
onModeChange?: (mode: AnnotationMode) => void;
|
|
60
|
+
onChange?: (annotations: Annotation[]) => void; // fired on add/delete/undo/clear
|
|
61
|
+
onInteractionChange?: (s: InteractionState) => void; // fired when drawing/armed/lock/editing changes (see §4)
|
|
62
|
+
onSelectionChange?: (id: string | null) => void; // fired when the ENGINE changes the selection itself (delete, deselect-on-navigate) — mirror it into your list UI
|
|
63
|
+
}
|
|
64
|
+
): SurfaceAnnotator
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- If `target` is a `Mesh` it is used directly; if a `Group/Object3D`, the mesh with the most vertices is chosen. Throws if no mesh is found.
|
|
68
|
+
- Reuses `scene.camera / scene.container / scene.controls` — no need to pass them.
|
|
69
|
+
- Non-indexed geometry is handled internally (for pathfinding only; your mesh is untouched).
|
|
70
|
+
|
|
71
|
+
### 3.2 `copperScene.disposeSurfaceAnnotators()`
|
|
72
|
+
|
|
73
|
+
Disposes every annotator created by this scene (removes the global event listeners).
|
|
74
|
+
|
|
75
|
+
### 3.3 `SurfaceAnnotator` instance methods
|
|
76
|
+
|
|
77
|
+
| Method | Description |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `setMode(mode)` | Switch mode: `"navigate"` / `"freehand"` / `"geodesic"` / `"point"` |
|
|
80
|
+
| `getMode()` | Current mode |
|
|
81
|
+
| `getAnnotations()` | Snapshot of the current annotation list `Annotation[]` |
|
|
82
|
+
| `getStore()` | The underlying `AnnotationStore` (advanced: subscribe / rename / recolor) |
|
|
83
|
+
| `selectAnnotation(id \| null)` | Select one (highlight: thicker contour / larger point), or pass `null` to deselect. Selecting **switches to the tool that drew it** (points → `point`, contour → its `freehand`/`geodesic` mode); a geodesic then re-opens its anchor handles for editing |
|
|
84
|
+
| `refreshAnnotation(id)` | Re-render the 3D object after a color change (pairs with `store.setColor`) |
|
|
85
|
+
| `setVisible(id, visible)` | Show / hide a single annotation (its 3D object is toggled; data is kept) |
|
|
86
|
+
| `deleteAnnotation(id)` | Delete one. If it's the geodesic currently being edited, its anchor handles are torn down too (no orphans) |
|
|
87
|
+
| `undo()` | Undo the most recent add / delete. During a geodesic that is being drawn/edited, undoes the last anchor edit instead (add / move / remove / insert) |
|
|
88
|
+
| `clearAll()` | Clear everything |
|
|
89
|
+
| `importAnnotations(payload)` | Rebuild annotations from an exported payload (see §6). Returns the count imported. Missing normals are recovered from the mesh's nearest vertex; missing `visible` defaults to `true`. Each imported item is first-class (select / recolor / hide / delete / export) |
|
|
90
|
+
| `exportJSON(modelName, opts?)` | Export to a JS object, see §6 |
|
|
91
|
+
| `activate()` | *(multi-model)* Make this annotator the **live** one — (re)attaches its global listeners so `Space` / tools / pointer act on **this** model. Idempotent. Activate exactly one at a time (deactivate the previous first) |
|
|
92
|
+
| `deactivate()` | *(multi-model)* Put this annotator **dormant** — commits an in-progress geodesic (or discards an uncommitted one), resets draw-lock, un-gates the camera (`controls.enabled = true`), then detaches its listeners. Its committed lines/markers **stay in the scene, visible**; they just stop responding to input. Idempotent |
|
|
93
|
+
| `setAllVisible(visible)` | *(multi-model)* Show / hide **every** annotation of this model in one call (single reconcile) — backs a per-model "hide all annotations" toggle. Does not delete data |
|
|
94
|
+
| `dispose()` | Release (removes event listeners). Always call on teardown |
|
|
95
|
+
|
|
96
|
+
### 3.4 `getStore()` common methods (`AnnotationStore`)
|
|
97
|
+
|
|
98
|
+
| Method | Description |
|
|
99
|
+
|---|---|
|
|
100
|
+
| `subscribe(cb)` | Subscribe to list changes; returns an unsubscribe function |
|
|
101
|
+
| `list()` / `get(id)` | Get the list / a single item |
|
|
102
|
+
| `setLabel(id, label)` | Rename (UI refreshes automatically; no 3D re-render needed) |
|
|
103
|
+
| `setColor(id, color)` | Recolor (**then call `annotator.refreshAnnotation(id)` to update the 3D object**) |
|
|
104
|
+
| `setVisible(id, visible)` | Show / hide (also reachable via `annotator.setVisible`) |
|
|
105
|
+
|
|
106
|
+
### 3.5 Types
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
type AnnotationMode = "navigate" | "freehand" | "geodesic" | "point";
|
|
110
|
+
|
|
111
|
+
interface AnnotationVertex { // position and normal are in model-LOCAL space
|
|
112
|
+
x: number; y: number; z: number;
|
|
113
|
+
nx: number; ny: number; nz: number;
|
|
114
|
+
faceIndex: number;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface Annotation {
|
|
118
|
+
id: string;
|
|
119
|
+
type: "contour" | "points";
|
|
120
|
+
mode: "freehand" | "geodesic" | null; // null for points
|
|
121
|
+
label: string;
|
|
122
|
+
color: string; // hex
|
|
123
|
+
closed: boolean;
|
|
124
|
+
visible: boolean; // per-annotation show/hide (default true)
|
|
125
|
+
vertices: AnnotationVertex[];
|
|
126
|
+
anchors?: AnnotationVertex[]; // geodesic contours only: the control points, so a committed contour can be re-opened for editing (survives export/import)
|
|
127
|
+
object3D: THREE.Object3D | null; // render object reference
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface ExportOptions {
|
|
131
|
+
space?: "local" | "world"; // default "local"
|
|
132
|
+
includeNormals?: boolean; // when true, points are [x,y,z,nx,ny,nz]
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Live interaction state, emitted by onInteractionChange (see §4)
|
|
136
|
+
interface InteractionState {
|
|
137
|
+
drawing: boolean; // true while strokes/clicks draw (Space held or draw-lock on)
|
|
138
|
+
armed: AnnotationMode; // the tool that will draw — "freehand" | "geodesic" | "point"
|
|
139
|
+
locked: boolean; // draw-lock is on (toggled by tapping Space)
|
|
140
|
+
editing: boolean; // a geodesic is editable now (in-progress or a re-opened committed one) → its anchors can be dragged/deleted/inserted; use it to show an edit hint
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## 4. Interaction & Shortcuts
|
|
145
|
+
|
|
146
|
+
The annotator is **navigate-first**: choosing a drawing mode (`freehand` / `geodesic` / `point`) **arms** that tool but does **not** take over the mouse — camera rotate / zoom / pan stay active. You enter the **drawing** state explicitly with `Space`:
|
|
147
|
+
|
|
148
|
+
- **Hold `Space`** — momentary: draw while held; release returns to navigation.
|
|
149
|
+
- **Tap `Space`** (a quick press, < 250 ms) — toggles **draw-lock**: drawing stays on until you tap `Space` again.
|
|
150
|
+
|
|
151
|
+
Only while drawing does the annotator capture the left mouse button and disable camera rotation; otherwise the camera is free. The **armed tool** (not the menu mode) is what acts when you draw, so you can rotate the model, then hold/tap `Space` and immediately draw with the tool you picked. Shortcuts are bound on `window` (capture phase, so TrackballControls cannot intercept them), and are ignored while typing in an `<input>` / `<textarea>`.
|
|
152
|
+
|
|
153
|
+
| Action | Behavior |
|
|
154
|
+
|---|---|
|
|
155
|
+
| `1` / `2` / `3` / `4` | Arm navigate / freehand / geodesic / point |
|
|
156
|
+
| Hold `Space` | Momentary draw (release → navigate) |
|
|
157
|
+
| Tap `Space` (< 250 ms) | Toggle **draw-lock** (drawing stays on) |
|
|
158
|
+
| Left drag (Freehand, while drawing) | Draw along the surface |
|
|
159
|
+
| Left click on open surface (Geodesic, while drawing) | Add an anchor; adjacent anchors are connected by a smoothed geodesic |
|
|
160
|
+
| Left **drag** an anchor (Geodesic) | Move it; the connected segments re-flow live. Works whenever the geodesic is editable — even in the navigate sub-state — so you can rotate, then grab a point |
|
|
161
|
+
| **Right-click** an anchor (Geodesic) | Delete it (the OS context menu is suppressed over the canvas) |
|
|
162
|
+
| Left click **on the line** between two anchors (Geodesic) | Insert a new anchor there |
|
|
163
|
+
| Left click (Place point, while drawing) | Drop a fiducial marker |
|
|
164
|
+
| `Esc` | Two-stage: first clears the current selection / cancels an in-progress geodesic (staying in the tool); pressed again (nothing selected) returns to navigate |
|
|
165
|
+
| `Enter` | Close / finish the current contour. Editing a committed geodesic → finalizes the edit and hides the handles |
|
|
166
|
+
| `Ctrl + Z` | Undo. While a geodesic is being drawn/edited, undoes the last anchor edit (add / move / remove / insert) |
|
|
167
|
+
| `Delete` / `Backspace` | Delete the selected annotation |
|
|
168
|
+
|
|
169
|
+
**Anchor picking** uses a screen-space pixel tolerance, so you don't need to hit the tiny marker exactly. Anchor handles are drawn as a white-rim + tool-colored-core so they stand out against both the line and the surface; deletion is right-click (there is no per-anchor ✕ affordance).
|
|
170
|
+
|
|
171
|
+
**Editing a committed geodesic.** Select it (in the list or via `selectAnnotation`) — because selecting switches to the Geodesic tool, its anchors re-appear as draggable handles. Drag / right-click / insert edit it live; `Enter`, switching tool, selecting another, or `Esc` finalizes. Reducing it below 2 anchors deletes it. `Annotation.anchors` (and the exported `anchors`) are what make this re-editable across sessions.
|
|
172
|
+
|
|
173
|
+
Subscribe to `onInteractionChange({ drawing, armed, locked, editing })` to drive a live mode indicator and a geodesic edit hint (show it while `editing`). Subscribe to `onSelectionChange(id)` so engine-initiated selection changes (delete, deselect-on-navigate) stay mirrored in your list UI.
|
|
174
|
+
|
|
175
|
+
## 5. Coordinate Space (important)
|
|
176
|
+
|
|
177
|
+
- **Camera pan / zoom / rotate do not change coordinates** — they move the camera, not the model.
|
|
178
|
+
- If the **model** is moved / rotated / scaled (object transform or animation), only **local coordinates stay constant**.
|
|
179
|
+
- Therefore the annotator **stores coordinates in local space** and derives world coordinates for rendering.
|
|
180
|
+
- `exportJSON` **defaults to `space:"local"`** — reproducible and bound to the model's own coordinate frame. Pass `{ space:"world" }` when you need the actual scene position.
|
|
181
|
+
|
|
182
|
+
> Note: if you **bake** scale/translation into the geometry after loading (e.g. `geometry.scale()`), "local" lands in that transformed space. To keep local = original model-file coordinates, place the model with an **object transform** (`mesh.position/scale`) or via the camera, and **do not bake the geometry**.
|
|
183
|
+
|
|
184
|
+
## 6. Export Format
|
|
185
|
+
|
|
186
|
+
`annotator.exportJSON("heart.obj")` returns:
|
|
187
|
+
|
|
188
|
+
```json
|
|
189
|
+
{
|
|
190
|
+
"model": "heart.obj",
|
|
191
|
+
"exportedAt": "2026-06-21T...Z",
|
|
192
|
+
"space": "local",
|
|
193
|
+
"annotations": [
|
|
194
|
+
{
|
|
195
|
+
"id": "a1",
|
|
196
|
+
"type": "contour",
|
|
197
|
+
"mode": "geodesic",
|
|
198
|
+
"label": "LV outline",
|
|
199
|
+
"color": "#ffa24e",
|
|
200
|
+
"closed": true,
|
|
201
|
+
"visible": true,
|
|
202
|
+
"points": [[x, y, z], ["..."]],
|
|
203
|
+
"anchors": [[x, y, z], ["..."]]
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
"id": "a2",
|
|
207
|
+
"type": "points",
|
|
208
|
+
"mode": null,
|
|
209
|
+
"label": "Point 2",
|
|
210
|
+
"color": "#ffd166",
|
|
211
|
+
"closed": false,
|
|
212
|
+
"visible": true,
|
|
213
|
+
"points": [[x, y, z]]
|
|
214
|
+
}
|
|
215
|
+
]
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
With `includeNormals: true`, each point is `[x, y, z, nx, ny, nz]`. Each annotation carries its `visible` flag, so a round-trip through `exportJSON` → `importAnnotations` preserves show/hide state. **Geodesic contours** additionally carry `anchors` (their control points, same `[x,y,z]` / `[x,y,z,nx,ny,nz]` shape), so a re-imported geodesic stays editable; `importAnnotations` maps them back to the nearest graph vertices.
|
|
220
|
+
|
|
221
|
+
> **Round-trip with `importAnnotations`.** Feed the exported object straight back to rebuild the annotations on a freshly loaded model. Points should be in **local** space (the export default). `id` is reused only for single-point entries (so a round-trip keeps stable ids); every other item gets a fresh id to avoid collisions. If a point lacks normals (`[x,y,z]` only), the normal is recovered from the welded graph's nearest vertex.
|
|
222
|
+
|
|
223
|
+
## 7. Usage Examples
|
|
224
|
+
|
|
225
|
+
### Example 1 — Minimal (OBJ)
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
scene.loadOBJ("/models/heart.obj", (group) => {
|
|
229
|
+
const annotator = scene.createSurfaceAnnotator(group);
|
|
230
|
+
annotator.setMode("geodesic");
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### Example 2 — GLB + custom colors
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
scene.loadPureGLB("/models/heart.glb", (group) => {
|
|
238
|
+
const annotator = scene.createSurfaceAnnotator(group, {
|
|
239
|
+
freehandColor: "#00e5ff",
|
|
240
|
+
geodesicColor: "#ff3b6b",
|
|
241
|
+
pointColor: "#ffe066",
|
|
242
|
+
lineWidth: 4,
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### Example 3 — Drive a list UI with `onChange` + rename / recolor
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
let annotator;
|
|
251
|
+
scene.loadOBJ("/models/heart.obj", (group) => {
|
|
252
|
+
annotator = scene.createSurfaceAnnotator(group, {
|
|
253
|
+
onChange: (annotations) => renderList(annotations), // refresh your UI on change
|
|
254
|
+
onModeChange: (mode) => updateModeButtons(mode),
|
|
255
|
+
});
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
function onSelect(id) { annotator.selectAnnotation(id); }
|
|
259
|
+
function onRename(id, label) { annotator.getStore().setLabel(id, label); }
|
|
260
|
+
function onRecolor(id, color) {
|
|
261
|
+
annotator.getStore().setColor(id, color);
|
|
262
|
+
annotator.refreshAnnotation(id); // required to update the 3D color
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
### Example 4 — Export (local / world / with normals) + browser download
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
const local = annotator.exportJSON("heart.obj"); // local (default)
|
|
270
|
+
const world = annotator.exportJSON("heart.obj", { space: "world" }); // world space
|
|
271
|
+
const withN = annotator.exportJSON("heart.obj", { includeNormals: true });
|
|
272
|
+
|
|
273
|
+
// Trigger a download (note: the <a> must be in the DOM to fire in some browsers)
|
|
274
|
+
function download(obj, filename = "annotations.json") {
|
|
275
|
+
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: "application/json" });
|
|
276
|
+
const url = URL.createObjectURL(blob);
|
|
277
|
+
const a = document.createElement("a");
|
|
278
|
+
a.href = url; a.download = filename;
|
|
279
|
+
document.body.appendChild(a); a.click(); a.remove();
|
|
280
|
+
URL.revokeObjectURL(url);
|
|
281
|
+
}
|
|
282
|
+
download(local);
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### Example 5 — Import a saved file + per-annotation visibility
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
scene.loadOBJ("/models/heart.obj", (group) => {
|
|
289
|
+
const annotator = scene.createSurfaceAnnotator(group);
|
|
290
|
+
|
|
291
|
+
// Re-hydrate previously exported annotations (e.g. fetched from a backend)
|
|
292
|
+
const saved = await (await fetch("/api/annotations/heart.json")).json();
|
|
293
|
+
const n = annotator.importAnnotations(saved); // returns how many were rebuilt
|
|
294
|
+
|
|
295
|
+
// Hide / show a single annotation without deleting it
|
|
296
|
+
annotator.setVisible(saved.annotations[0].id, false);
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### Example 6 — Live mode indicator with `onInteractionChange`
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
scene.createSurfaceAnnotator(group, {
|
|
304
|
+
onInteractionChange: ({ drawing, armed, locked, editing }) => {
|
|
305
|
+
badge.textContent = drawing ? `Drawing — ${armed}${locked ? " (locked)" : ""}` : "Navigate";
|
|
306
|
+
editHint.hidden = !editing; // show "drag move · right-click delete · click line insert" while editing a geodesic
|
|
307
|
+
},
|
|
308
|
+
onSelectionChange: (id) => refreshListHighlight(id), // engine may deselect on its own (delete / navigate)
|
|
309
|
+
});
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
### Example 7 — Teardown
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
// on component unmount / model switch
|
|
316
|
+
annotator.dispose(); // or scene.disposeSurfaceAnnotators();
|
|
317
|
+
appRenderer.dispose();
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### Example 8 — Multiple models in one scene (activate / deactivate)
|
|
321
|
+
|
|
322
|
+
```ts
|
|
323
|
+
// Load several models of the same case into ONE scene. Each gets its own
|
|
324
|
+
// annotator; only one is "active" (editable) at a time. Dormant models keep
|
|
325
|
+
// their contours visible but ignore input.
|
|
326
|
+
const annotators = new Map<string, Copper.SurfaceAnnotator>();
|
|
327
|
+
let activeId: string | null = null;
|
|
328
|
+
|
|
329
|
+
function addModel(id: string, group: THREE.Object3D) {
|
|
330
|
+
const a = scene.createSurfaceAnnotator(group);
|
|
331
|
+
a.deactivate(); // dormant on load — no camera/lighting/framing here (that's yours)
|
|
332
|
+
annotators.set(id, a);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function setActive(id: string) {
|
|
336
|
+
if (activeId) annotators.get(activeId)?.deactivate(); // commits/cleans up the old one
|
|
337
|
+
annotators.get(id)?.activate(); // this model now owns Space / tools
|
|
338
|
+
activeId = id;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Per-model "hide all annotations" toggle (distinct from hiding the surface mesh)
|
|
342
|
+
function hideAllAnnotations(id: string, hidden: boolean) {
|
|
343
|
+
annotators.get(id)?.setAllVisible(!hidden);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Teardown one model, or the whole case
|
|
347
|
+
function removeModel(id: string) {
|
|
348
|
+
annotators.get(id)?.dispose(); // removes its contours + listeners
|
|
349
|
+
annotators.delete(id);
|
|
350
|
+
if (activeId === id) activeId = null;
|
|
351
|
+
}
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
> The engine does not choose which model is "primary" or frame the camera — that's the host app's call (e.g. the Surface Annotator app frames the largest-bounding-box model). The annotator only reuses the scene's existing camera/controls.
|
|
355
|
+
|
|
356
|
+
## 8. Caveats
|
|
357
|
+
|
|
358
|
+
- **Framing / lighting / loading are yours.** The annotator touches none of them — add lights and set the camera for each new model.
|
|
359
|
+
- **After a color change you must call `refreshAnnotation(id)`.** `store.setColor` only updates data; the 3D object's color is updated by `refreshAnnotation`. `setLabel` needs no re-render.
|
|
360
|
+
- **Shortcuts are global (window-level).** `1/2/3/4`, `Enter`, `Delete`, `Ctrl+Z`, `Space` are all listened for. If your page uses these keys elsewhere, conflicts are possible — call `dispose()` when you are done to unbind.
|
|
361
|
+
- **Exactly one *active* annotator at a time — but many may coexist.** Events are on the window capture phase, so two *active* instances would both respond to `Space` / tools / pointer. For multiple models in one scene, create an annotator per model and immediately `deactivate()` all but one; call `activate()` on the model you want to edit (and `deactivate()` the previous). Dormant annotators keep their contours in the scene but ignore input, so you no longer have to `dispose()` and reload to switch models. A freshly constructed annotator is **active by default** (backward-compatible), so single-model callers need no changes.
|
|
362
|
+
- **Geodesic connectivity.** If the model consists of **several disconnected shells**, a geodesic (or closing segment) across shells falls back to a straight line. A single connected mesh works best.
|
|
363
|
+
- **Geodesic performance.** Heap Dijkstra; ~30k vertices is < 100ms per click. **Very large meshes** (hundreds of thousands of vertices) may lag (nearest-vertex lookup is O(V)).
|
|
364
|
+
- **Your mesh is not modified.** Pathfinding uses a position-only welded copy; your mesh's normals/UVs/textures are untouched. The geometry must have a `position` attribute.
|
|
365
|
+
- **Export returns an object; it does not download for you.** The browser download / UI trigger is up to you (see the `appendChild` gotcha in Example 4).
|
|
366
|
+
- **Closing follows the surface.** `Enter` connects the last point back to the first via a geodesic, not a straight chord, so it never cuts through the model.
|
|
367
|
+
- **Freehand is a screen-stroke projection.** Consecutive samples are joined by straight segments (unlike Geodesic, which strictly follows the surface). When the stroke grazes a cleft or silhouette edge, samples that jump to a far/back face are **dropped automatically** (distance-spike + normal-flip test) to avoid a segment cutting through the model; for strict surface hugging, use **Geodesic** mode.
|
|
368
|
+
- **Camera gating (navigate-first).** The annotator toggles `scene.controls.enabled`: **enabled by default** (you can always orbit), and **disabled only while drawing** — i.e. while `Space` is held or draw-lock is on. Coordinate with any other code that controls it.
|
|
369
|
+
- **Contours & markers sit on the surface, occluded by the model.** Contour lines are lifted along the normal by `epsilon` and depth-tested (with a polygon-offset "decal" bias on the surface triangles), so they read cleanly on rough / voxelised meshes without z-fighting, yet are correctly hidden when on the model's far side (no see-through). Point and geodesic-anchor markers are lifted spheres, likewise depth-tested. Geodesic anchor **handles** are drawn as a white rim around a tool-colored core and lifted a touch more, so they stand out against both the line and the surface.
|
|
370
|
+
|
|
371
|
+
## 9. Exports
|
|
372
|
+
|
|
373
|
+
From the package root:
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import {
|
|
377
|
+
SurfaceAnnotator, // value (for instanceof / typing)
|
|
378
|
+
} from "copper3d_visualisation";
|
|
379
|
+
import type {
|
|
380
|
+
SurfaceAnnotatorOptions,
|
|
381
|
+
Annotation,
|
|
382
|
+
AnnotationMode,
|
|
383
|
+
ExportOptions,
|
|
384
|
+
InteractionState,
|
|
385
|
+
} from "copper3d_visualisation";
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
`createSurfaceAnnotator` is a method on `copperScene`, called on a scene instance.
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# copper3d — Volume Slice Display
|
|
2
|
+
|
|
3
|
+
Two functions for the greyscale a volume slice actually comes out as: one that makes
|
|
4
|
+
scrubbing cheap, one that makes dark studies readable.
|
|
5
|
+
|
|
6
|
+
Both are exported from the package entry (`copper3d`).
|
|
7
|
+
Both are **opt-in** — `loadNrrd` does not call either, so existing code is unaffected.
|
|
8
|
+
|
|
9
|
+
::: tip New in 3.8.0
|
|
10
|
+
Additive only. Nothing about the existing loader or `VolumeSlice` behaviour changed.
|
|
11
|
+
:::
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 1. `installFastSliceRepaint()`
|
|
16
|
+
|
|
17
|
+
Replaces one `VolumeSlice`'s `repaint` method with an equivalent that does not rebuild
|
|
18
|
+
the world on every scrub step.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
installFastSliceRepaint(slice: unknown, exposure?: number): Promise<void>
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
| parameter | type | default | meaning |
|
|
25
|
+
|---|---|---|---|
|
|
26
|
+
| `slice` | `VolumeSlice` | — | The slice to patch, e.g. `nrrdSlices.z`. |
|
|
27
|
+
| `exposure` | `number` | `1` | Gamma exponent, normally from [`exposureExponent()`](#_2-exposureexponent). `1` leaves greyscale exactly as the original produced it. |
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
scene.loadNrrd(url, bar, true, async (volume, meshes, slices) => {
|
|
31
|
+
scene.addObject(meshes.z);
|
|
32
|
+
await installFastSliceRepaint(slices.z);
|
|
33
|
+
slices.z.repaint.call(slices.z);
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Why
|
|
38
|
+
|
|
39
|
+
Setting `slice.index` sets `geometryNeedsUpdate`, so the next `repaint()` runs
|
|
40
|
+
`updateGeometry()` first. That method unconditionally:
|
|
41
|
+
|
|
42
|
+
- assigns `canvas.width` / `canvas.height` and the same on `canvasBuffer` — assigning
|
|
43
|
+
either **resets the whole 2D backing store**, even when the value is unchanged;
|
|
44
|
+
- re-fetches both 2D contexts;
|
|
45
|
+
- calls `geometry.dispose()` and builds a `new PlaneGeometry(...)`, i.e. deletes and
|
|
46
|
+
recreates GPU buffers, **every frame**.
|
|
47
|
+
|
|
48
|
+
Then `repaint()` calls `ctx.getImageData(...)`, a full canvas read-back that allocates a
|
|
49
|
+
fresh `Uint8ClampedArray` — every pixel of which is overwritten by the loop immediately
|
|
50
|
+
below it, so the read is pure waste.
|
|
51
|
+
|
|
52
|
+
Within one volume and one axis, `planeWidth`, `planeHeight`, `iLength` and `jLength` are
|
|
53
|
+
the same for every slice; only `sliceAccess` and `matrix` differ. So all of the above is
|
|
54
|
+
redundant on every scrub step but the first.
|
|
55
|
+
|
|
56
|
+
Measured in a real browser while dragging a slice plane: **59 long tasks (>50 ms) in ~2 s
|
|
57
|
+
and a p90 frame time of 61 ms**, against **zero** long tasks for the same drag on a scene
|
|
58
|
+
that rotates but never repaints. Cost is plain JS, not the renderer.
|
|
59
|
+
|
|
60
|
+
`VolumeSlice` comes from three.js rather than from this library and exposes no option for
|
|
61
|
+
any of it, so replacing the method per instance is the available lever.
|
|
62
|
+
|
|
63
|
+
### Fidelity
|
|
64
|
+
|
|
65
|
+
The pixel loop is copied from the original, byte for byte in its arithmetic — threshold
|
|
66
|
+
and window-level handling included. The differences are cached `ImageData`, geometry work
|
|
67
|
+
skipped while the plane dimensions are unchanged, and the optional exposure LUT.
|
|
68
|
+
|
|
69
|
+
`label` volumes are handed back to the original implementation untouched.
|
|
70
|
+
|
|
71
|
+
### Notes
|
|
72
|
+
|
|
73
|
+
- **Idempotent.** Patching an already-patched slice is a no-op, so the `exposure` of the
|
|
74
|
+
first call wins.
|
|
75
|
+
- **Call it before the first paint.** The LUT lives inside the patched method, so painting
|
|
76
|
+
first draws one un-lifted frame and corrects it on the reader's first scrub — a visible
|
|
77
|
+
colour change.
|
|
78
|
+
- `async` only because `PlaneGeometry` is imported on demand.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## 2. `exposureExponent()`
|
|
83
|
+
|
|
84
|
+
Solves for the gamma exponent that puts a volume's median tissue voxel at a target
|
|
85
|
+
greyscale.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
exposureExponent(volume: ExposureVolume, targetGrey?: number): number
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
| parameter | type | default | meaning |
|
|
92
|
+
|---|---|---|---|
|
|
93
|
+
| `volume` | `ExposureVolume` | — | `{ data, min, max }` — a loaded NRRD volume satisfies this. |
|
|
94
|
+
| `targetGrey` | `number` | `DEFAULT_TARGET_GREY` (75) | Where the median tissue voxel should land on the 0–255 greyscale. |
|
|
95
|
+
|
|
96
|
+
Returns `1` when the volume needs no lift, or cannot be measured (empty data, or
|
|
97
|
+
`max <= min`). It **only ever brightens** — a volume already at or past the target is
|
|
98
|
+
left alone.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const exposure = exposureExponent(volume);
|
|
102
|
+
await installFastSliceRepaint(slices.z, exposure);
|
|
103
|
+
slices.z.repaint.call(slices.z);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Why a gamma curve and not a narrower window
|
|
107
|
+
|
|
108
|
+
A slice is painted with `(raw - windowLow) * 255 / (windowHigh - windowLow)`, and the
|
|
109
|
+
NRRD loader sets that window to the volume's own `min`/`max`. When the max is a handful
|
|
110
|
+
of bright outliers — normal on a contrast-enhanced MRI — the tissue ends up in the bottom
|
|
111
|
+
of the range and the image reads as dark. Measured across nine clinical volumes, the
|
|
112
|
+
median tissue voxel landed at **grey 31–55 of 255**.
|
|
113
|
+
|
|
114
|
+
Narrowing the window is the obvious fix and it does not work. **Any linear window bright
|
|
115
|
+
enough to lift the tissue saturates the top of the range, and on a contrast-enhanced study
|
|
116
|
+
the lesion _is_ the top of the range.** Two attempts were rejected for exactly this: the
|
|
117
|
+
tumour and the white bounding box drawn over it both disappeared into white. No value of
|
|
118
|
+
the parameter escapes that.
|
|
119
|
+
|
|
120
|
+
`out = 255 * (in / 255) ** exponent` is monotonic and fixes both ends — 0 stays 0, 255
|
|
121
|
+
stays 255 — so nothing can clip however far the middle is raised. The lesion keeps its
|
|
122
|
+
separation from the tissue around it.
|
|
123
|
+
|
|
124
|
+
### Why Otsu
|
|
125
|
+
|
|
126
|
+
Air and tissue are separated with [Otsu's method](https://en.wikipedia.org/wiki/Otsu%27s_method)
|
|
127
|
+
rather than a fraction of the range. The range is the one thing volumes disagree on —
|
|
128
|
+
maxima two orders of magnitude apart are ordinary (246 to 27014 across the nine measured)
|
|
129
|
+
— so any threshold derived from `max` lands somewhere different in each of them. Otsu
|
|
130
|
+
picks the split from the histogram's own shape, which is what makes the same target
|
|
131
|
+
produce comparable images across a whole catalogue.
|
|
132
|
+
|
|
133
|
+
The histogram is built from a uniform stride of at most 4 million voxels: a full pass over
|
|
134
|
+
a 35M-voxel volume costs ~100 ms, and a uniform stride is unbiased for the intensity
|
|
135
|
+
distribution.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## 3. `addVolumeBoundingBox()` <Badge type="tip" text="3.9.0" />
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
addVolumeBoundingBox(
|
|
143
|
+
scene: BoundingBoxHost,
|
|
144
|
+
rasDimensions: ArrayLike<number>,
|
|
145
|
+
opts?: { color?: ColorRepresentation; name?: string }
|
|
146
|
+
): THREE.BoxHelper | undefined
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
The wireframe box around a volume. It is the only thing that gives a lone slice
|
|
150
|
+
plane spatial context — without it the plane floats in an unbounded void and
|
|
151
|
+
nothing tells the reader how far through the volume they have scrubbed.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
scene.loadNrrd(url, loadingBar, false, (volume, meshes) => {
|
|
155
|
+
scene.addObject(meshes.z);
|
|
156
|
+
Copper.addVolumeBoundingBox(scene, volume.RASDimensions, { color: 0x8a7f84 });
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Returns the helper so you can hide, move or dispose it, and `undefined` for a
|
|
161
|
+
degenerate volume — a zero extent on any axis would produce a flat helper
|
|
162
|
+
rather than a box. It is named `"volume-bounds"` by default, so a later
|
|
163
|
+
children sweep can find and dispose it like anything else in the scene.
|
|
164
|
+
|
|
165
|
+
`color` defaults to white, which is what reads against a dark viewer. Pass a
|
|
166
|
+
darker tone for a light background, where white lines vanish.
|
|
167
|
+
|
|
168
|
+
### It replaces `addBoxHelper()`
|
|
169
|
+
|
|
170
|
+
`addBoxHelper` is **deprecated** as of 3.9.0 and unchanged — a caller passing
|
|
171
|
+
its optional third argument gets working behaviour from it. The two-argument
|
|
172
|
+
form does not work, and never did:
|
|
173
|
+
|
|
174
|
+
- Without `boxCube` it wraps a module-level `cube` that `copperNrrdLoader`
|
|
175
|
+
declares and never assigns, i.e. `new THREE.BoxHelper(undefined)`.
|
|
176
|
+
- It is typed to take a `copperScene`, so `copperSceneOnDemond` — a sibling
|
|
177
|
+
subclass, not a descendant — does not type-check even though it has the
|
|
178
|
+
`addObject` this needs.
|
|
179
|
+
- It sizes the box from `volume.matrix` rather than the volume's RAS
|
|
180
|
+
dimensions, which is not the box a reader expects around the data.
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Types
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
interface ExposureVolume {
|
|
188
|
+
data: ArrayLike<number>;
|
|
189
|
+
min: number;
|
|
190
|
+
max: number;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const DEFAULT_TARGET_GREY = 75;
|
|
194
|
+
```
|