copper3d 3.10.3 → 3.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +162 -4
  2. package/ai-index/guides/4D-MRI-LV-rendering.md +580 -0
  3. package/ai-index/guides/ai-assist-api.md +382 -0
  4. package/ai-index/guides/camera-framing.md +238 -0
  5. package/ai-index/guides/control-axes.md +124 -0
  6. package/ai-index/guides/copper3d-4D-API.md +219 -0
  7. package/ai-index/guides/copper3d-rendering-optimization.md +155 -0
  8. package/ai-index/guides/gltf-decoders.md +105 -0
  9. package/ai-index/guides/heart-sensor.md +137 -0
  10. package/ai-index/guides/load-callbacks.md +244 -0
  11. package/ai-index/guides/nrrd-tools.md +1868 -0
  12. package/ai-index/guides/on-demand-controls.md +154 -0
  13. package/ai-index/guides/rotation-pivot.md +197 -0
  14. package/ai-index/guides/scene-resources.md +227 -0
  15. package/ai-index/guides/segmentation-module.md +1516 -0
  16. package/ai-index/guides/surface-annotation-api.md +388 -0
  17. package/ai-index/guides/volume-display.md +194 -0
  18. package/ai-index/manifest.json +136 -0
  19. package/ai-index/symbols.json +1 -0
  20. package/dist/Utils/segmentation/DrawToolCore.d.ts +8 -0
  21. package/dist/Utils/segmentation/DrawToolCore.js +11 -0
  22. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  23. package/dist/Utils/segmentation/NrrdTools.d.ts +8 -0
  24. package/dist/Utils/segmentation/NrrdTools.js +10 -0
  25. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  26. package/dist/Utils/segmentation/core/UndoManager.d.ts +12 -1
  27. package/dist/Utils/segmentation/core/UndoManager.js +33 -17
  28. package/dist/Utils/segmentation/core/UndoManager.js.map +1 -1
  29. package/dist/bundle.esm.js +57 -20
  30. package/dist/bundle.umd.js +57 -20
  31. package/dist/types/Utils/segmentation/DrawToolCore.d.ts +8 -0
  32. package/dist/types/Utils/segmentation/NrrdTools.d.ts +8 -0
  33. package/dist/types/Utils/segmentation/core/UndoManager.d.ts +12 -1
  34. package/package.json +7 -4
@@ -0,0 +1,580 @@
1
+ # 4D Heart (MRI + LV Surfaces) Aligned Rendering — Deep Dive
2
+
3
+ > Using `src/pages/example15_mri_lv_4d.vue` as the worked example, this explains how "32 MRI images + 64 VTK models" are loaded, aligned, and played back together on a single cardiac clock.
4
+ >
5
+ > Core files:
6
+ > - `src/pages/example15_mri_lv_4d.vue` — entry point
7
+ > - `src/ts/Scene/copperScene.ts` — `loadAligned4D()` and `Aligned4DController`
8
+ > - `src/ts/Utils/texture2d.ts` — `createTexture2D_Array` / `buildAlignedQuad`
9
+ > - `src/ts/Loader/copperDicomLoader.ts` — DICOM parsing, geometry tags, LUT
10
+ > - `src/ts/Utils/getVOILUT.ts` — window width/center mapping function
11
+ > - `src/ts/lib/shader/texture2d_frag.glsl` — fragment shader
12
+ > - `src/ts/Renderer/copperRenderer.ts` / `src/ts/Scene/commonSceneMethod.ts` — render loop and tick callbacks
13
+
14
+ ---
15
+
16
+ ## Table of Contents
17
+
18
+ 1. [Overall architecture & data flow](#1-overall-architecture--data-flow)
19
+ 2. [How 32 MRI frames become "1 mesh"](#2-how-32-mri-frames-become-1-mesh)
20
+ 3. [How 64 VTK files become "2 meshes"](#3-how-64-vtk-files-become-2-meshes)
21
+ 4. [Animation: one clock driving three meshes](#4-animation-one-clock-driving-three-meshes)
22
+ 5. [Alignment: the DICOM patient coordinate system](#5-alignment-the-dicom-patient-coordinate-system)
23
+ 6. [Windowing / LUT grayscale mapping](#6-windowing--lut-grayscale-mapping)
24
+ 7. [The three.js animation loop & tick callbacks](#7-the-threejs-animation-loop--tick-callbacks)
25
+ 8. [Build it from scratch: the minimal skeleton](#8-build-it-from-scratch-the-minimal-skeleton)
26
+ 9. [Key principles cheat-sheet](#9-key-principles-cheat-sheet)
27
+
28
+ ---
29
+
30
+ ## 1. Overall architecture & data flow
31
+
32
+ The entry `example15_mri_lv_4d.vue` calls `scene.loadAligned4D()`, passing 32 `.dcm` URLs plus two `.vtk` sequences (endo / epi, 32 each). The real implementation lives in `loadAligned4D()` in `copperScene.ts`.
33
+
34
+ ```
35
+ loadAligned4D
36
+ ├─ loadDicomStack() // 32 dcm → 1 DataArrayTexture
37
+ ├─ loadSurfaceSequence×2 // 32+32 vtk → 2 geometry arrays
38
+ └─ once Promise.all resolves:
39
+ ├─ create 1 plane mesh (textured with the array texture)
40
+ ├─ create 2 surface meshes (start on frame-0 geometry)
41
+ └─ register one tick callback into the render loop → animation
42
+ ```
43
+
44
+ **Correcting the intuition.** A common guess is: "load everything into memory → create only 3 meshes → render simultaneously → aligned animation." That is mostly right, but the nuances matter:
45
+
46
+ - ✅ All 32 dcm + 64 vtk are **loaded into memory up front**.
47
+ - ⚠️ It really is **3 meshes**, but they work in completely different ways:
48
+ - **1 plane mesh** shows all 32 MRI frames — by **swapping the texture layer**, not the mesh.
49
+ - **2 surface meshes** (endo / epi) show all 64 vtk — by **swapping the geometry reference**.
50
+ - ✅ A **single shared `frameIndex`** + one tick clock drives all three, so their phases are always in sync.
51
+ - ❗ **Alignment is not computed at render time.** It is established **at load time** by placing everything into the same "patient coordinate system" using the DICOM geometry tags, and by **never calling `center()` / `scale()`**.
52
+
53
+ ---
54
+
55
+ ## 2. How 32 MRI frames become "1 mesh"
56
+
57
+ The key trick is the **WebGL2 `DataArrayTexture` (`sampler2DArray` in GLSL)**: stack the 32 frames into an "array texture," keep the plane mesh fixed forever, and change a single integer uniform `depth` to switch frames.
58
+
59
+ ### Loading (`copperScene.ts` `loadDicomStack`)
60
+
61
+ ```ts
62
+ // each of 32 dcm decodes to one grayscale frame; sort by cardiac phase,
63
+ // then flatten/concatenate into one big array uint8[frameSize * 32]
64
+ volumes.sort((a, b) => a.order - b.order); // order by TriggerTime / SliceLocation
65
+ const frameSize = w * h;
66
+ const uint8 = new Uint8ClampedArray(frameSize * 32);
67
+ volumes.forEach((v, i) => uint8.set(v.uint8, i * frameSize)); // frame i → slot i
68
+ ```
69
+
70
+ `order` comes from DICOM tags (`copperDicomLoader.ts`): prefer `x00181060` (TriggerTime, cardiac trigger time), else `x00201041` (SliceLocation). This guarantees the 32 frames are ordered by **cardiac systole/diastole time**, not by filename.
71
+
72
+ ### Building the texture (`texture2d.ts` `createTexture2D_Array`)
73
+
74
+ ```ts
75
+ const texture = new THREE.DataArrayTexture(uint8, width, height, depth /*=32*/);
76
+ texture.format = THREE.RedFormat; // single-channel grayscale
77
+ ```
78
+
79
+ ### Switching frames (`texture2d.ts` `setFrame`)
80
+
81
+ ```ts
82
+ function setFrame(i) { material.uniforms.depth.value = i; } // change one int
83
+ ```
84
+
85
+ Fragment shader (`texture2d_frag.glsl`):
86
+
87
+ ```glsl
88
+ vec4 color = texture(diffuse, vec3(vUv, depth)); // 3rd component depth = which frame
89
+ outColor = vec4(color.rrr * uBrightness, uOpacity); // uBrightness defaults to 1.5
90
+ ```
91
+
92
+ > **Key point:** all 32 frames live in GPU memory; switching a frame costs one uniform write. That is orders of magnitude faster than rebuilding/re-uploading a texture each frame, which is why cine playback is smooth.
93
+
94
+ ---
95
+
96
+ ## 3. How 64 VTK files become "2 meshes"
97
+
98
+ Surfaces use a different trick: **decode all geometries up front, and each frame only swap the `mesh.geometry` reference**.
99
+
100
+ ### Loading (`copperScene.ts` `loadSurfaceSequence`)
101
+
102
+ ```ts
103
+ // each sequence of 32 vtk decodes to 32 BufferGeometry, stored in an array
104
+ loader.load(url, (geometry) => {
105
+ geometry.computeVertexNormals(); // note: NO center(), NO scale()!
106
+ geometries[index] = geometry; // keep original world coordinates
107
+ });
108
+ ```
109
+
110
+ ### Building the mesh (`copperScene.ts`)
111
+
112
+ One mesh per sequence, starting at frame 0:
113
+
114
+ ```ts
115
+ const { vtkmaterial } = copperMultipleVtk(def.opts);
116
+ const mesh = new THREE.Mesh(geometries[0], vtkmaterial);
117
+ seqs.push({ mesh, geometries, offset: def.offset ?? 0 });
118
+ ```
119
+
120
+ ### Switching frames (`copperScene.ts` `applyFrame`)
121
+
122
+ ```ts
123
+ const applyFrame = () => {
124
+ tex.setFrame(frameIndex); // MRI layer
125
+ for (const s of seqs) {
126
+ const i = (frameIndex + s.offset + s.geometries.length) % s.geometries.length;
127
+ s.mesh.geometry = s.geometries[i]; // surface geometry reference
128
+ }
129
+ };
130
+ ```
131
+
132
+ > endo and epi are **two independent meshes** (different materials: endo red/opaque, epi blue/translucent), but they share the same `frameIndex`, so endocardium and epicardium are always at the same cardiac phase — that is why they stay aligned to each other too.
133
+
134
+ ---
135
+
136
+ ## 4. Animation: one clock driving three meshes
137
+
138
+ The heart of "aligned animation" is that there is **only one `frameIndex`**, and all three meshes read from it (`copperScene.ts`):
139
+
140
+ ```ts
141
+ const dtBase = cycleMs / frameCount; // 1012ms / 32 ≈ 31.6ms per frame
142
+ const tick = () => {
143
+ if (disposed || !playing) return;
144
+ const now = performance.now();
145
+ if (now - lastStep >= dtBase / speed) { // wall-clock controls frame rate, decoupled from refresh
146
+ lastStep = now;
147
+ frameIndex = (frameIndex + 1) % frameCount; // the single frame counter
148
+ applyFrame(); // sync all meshes at once
149
+ }
150
+ };
151
+ this.addPreRenderCallbackFunction(tick); // hook into the render loop
152
+ ```
153
+
154
+ It accumulates real wall-clock time via `performance.now()` to decide "should we advance a frame," rather than +1 on every render frame — so whether the display is 60Hz or 144Hz the **heartbeat speed is identical**, and the `speed` slider controls it precisely.
155
+
156
+ `frameOffset` (the slider in the example) adds a phase offset to surfaces, used to manually fine-tune any phase mismatch between surfaces and the MRI.
157
+
158
+ ---
159
+
160
+ ## 5. Alignment: the DICOM patient coordinate system
161
+
162
+ > **Alignment is not done at render time** — it is established by placing everything into the same world coordinate system. The rule: both the MRI plane and the VTK surfaces use their original "patient coordinate system" millimeter coordinates, and nobody centers or scales.
163
+
164
+ ### 5.1 The patient coordinate system (DICOM Patient Coordinate System / LPS)
165
+
166
+ All DICOM spatial tags live in a fixed physical coordinate system, in millimeters, called **LPS**:
167
+
168
+ | Axis | Direction | Meaning |
169
+ |---|---|---|
170
+ | +X | **L**eft | toward the patient's left hand |
171
+ | +Y | **P**osterior | toward the patient's back |
172
+ | +Z | **S**uperior | toward the top of the head |
173
+
174
+ It has nothing to do with "which image, which pixel row/column" — it is **the physical space of the patient's body**. As long as the MRI slice and the VTK model both use LPS millimeter coordinates, they refer to the same physical point in the same physical space — this is the foundation of automatic alignment.
175
+
176
+ > three.js itself is a right-handed Y-up system, different from LPS. This project does **no conversion** — it feeds LPS millimeter values straight into three.js positions. Because the MRI plane and the surfaces share the same LPS numbers, their relative relationship is exact, and the camera can orbit freely while everything stays aligned.
177
+
178
+ ### 5.2 The three key tags (`copperDicomLoader.ts`)
179
+
180
+ ```ts
181
+ const ipp = parseDS(dataSet.string("x00200032")); // ImagePositionPatient
182
+ const iop = parseDS(dataSet.string("x00200037")); // ImageOrientationPatient
183
+ const spacing = parseDS(dataSet.string("x00280030")); // PixelSpacing
184
+ ```
185
+
186
+ - **ImagePositionPatient (0020,0032)** — 3 numbers: the LPS millimeter coordinate of the **center of pixel (0,0)** (the top-left pixel), i.e. the anchor `O`.
187
+ - **ImageOrientationPatient (0020,0037)** — 6 numbers: two unit vectors describing the orientation of the image's "row direction" and "column direction" in LPS; these determine the plane's **tilt/pose**.
188
+ - **PixelSpacing (0028,0030)** — 2 numbers: `[row spacing, column spacing]`, the physical millimeter size of each pixel.
189
+
190
+ `parseDS` splits a DICOM `"a\b\c"` multi-value string (DS type uses backslash delimiters) into a number array.
191
+
192
+ ### 5.3 The corner formula (`computeImagePlaneCorners`)
193
+
194
+ ```ts
195
+ const row = new THREE.Vector3(iop[0], iop[1], iop[2]); // +column-index dir (move across a row)
196
+ const col = new THREE.Vector3(iop[3], iop[4], iop[5]); // +row-index dir (move down columns)
197
+ const sc = spacing[1]; // column spacing (mm per step along row)
198
+ const sr = spacing[0]; // row spacing (mm per step along col)
199
+ const O = new THREE.Vector3(ipp[0], ipp[1], ipp[2]); // center of pixel (0,0)
200
+ const p = (a, b) => O.clone()
201
+ .addScaledVector(row, a * sc)
202
+ .addScaledVector(col, b * sr);
203
+ return {
204
+ tl: p(-0.5, -0.5),
205
+ tr: p(cols-0.5, -0.5),
206
+ bl: p(-0.5, rows-0.5),
207
+ br: p(cols-0.5, rows-0.5),
208
+ };
209
+ ```
210
+
211
+ **One formula captures everything:**
212
+
213
+ ```
214
+ world coordinate of pixel(column a, row b) = O + a·sc·row⃗ + b·sr·col⃗
215
+ ```
216
+
217
+ - `O` (IPP) gives **position**
218
+ - `row⃗ / col⃗` (IOP) give **orientation**
219
+ - `sc / sr` (PixelSpacing) give **physical size**
220
+
221
+ Why `-0.5` and `cols-0.5`: IPP points at the pixel **center**, so to get the **outer edge** corner, the top-left moves out half a pixel from the center → `-0.5`; the right edge is pixel `cols-1` pushed out another half → `cols-0.5`.
222
+
223
+ > Gotcha #1: IOP's first vector is the "move right along a row (column index increasing)" direction — think of it as "the image's +u axis orientation in physical space."
224
+ > Gotcha #2: PixelSpacing is `[row, col]` order, but row spacing corresponds to the step "down columns (col vector)," which is why the code pairs `sc=spacing[1]` with `row` and `sr=spacing[0]` with `col`.
225
+
226
+ ### 5.4 How the VTK surfaces line up
227
+
228
+ The vertex coordinates in the VTK files **are already in the same patient coordinate system, in millimeters** (guaranteed by the data producer). That is why the comment in the code is the whole point:
229
+
230
+ ```ts
231
+ // keep world coordinates — no center()/scale()
232
+ ```
233
+
234
+ The plane is placed into world coordinates via the DICOM geometry tags; the surfaces keep their original world coordinates — so both naturally land in the same coordinate system and are **automatically aligned**, with no registration computation required.
235
+
236
+ > This is the most elegant part of the whole approach: **alignment is achieved by respecting the original coordinate systems, not by a registration algorithm.** As long as you never center/scale/translate, the MRI slice passes exactly through the heart model.
237
+
238
+ The final `scene.loadViewUrl(VIEW)` merely loads a preset camera viewpoint JSON so the initial camera frames the heart — unrelated to alignment itself.
239
+
240
+ ---
241
+
242
+ ## 6. Windowing / LUT grayscale mapping
243
+
244
+ ### 6.1 Why windowing is needed
245
+
246
+ DICOM pixels are **16-bit** (`uint16`, 0–65535; CT may even be signed HU values), while a screen only displays **8-bit** (0–255). A naive linear squeeze makes everything washed-out gray. **Windowing (window width/center)** stretches only the value range you care about into 0–255, with everything outside clamped to black or white.
247
+
248
+ - **Window Center (WC)**: the center brightness of interest.
249
+ - **Window Width (WW)**: the value span of interest.
250
+
251
+ ### 6.2 ⚠️ Key architecture: this project does windowing on the CPU, not in the shader
252
+
253
+ The fragment shader (`texture2d_frag.glsl`) merely samples and applies a gain — **no window width/center**:
254
+
255
+ ```glsl
256
+ vec4 color = texture(diffuse, vec3(vUv, depth));
257
+ outColor = vec4(color.rrr * uBrightness, uOpacity); // uBrightness defaults to 1.5
258
+ ```
259
+
260
+ (That gain cannot fix a washed-out image; see [6.6](#66--the-gotcha-a-window-whose-lower-bound-is-below-zero).)
261
+
262
+ The actual windowing happens in a **CPU loop at load time** (`copperDicomLoader.ts`):
263
+
264
+ ```ts
265
+ let lut = getLut(uint16, windowWidth, windowCenter, invert, voiLUT);
266
+ let uint8 = new Uint8ClampedArray(uint16.length);
267
+ for (let i = 0; i < uint16.length; i++) {
268
+ uint8[i] = lut.lutArray[uint16[i]]; // 16-bit raw → table lookup → 8-bit
269
+ }
270
+ ```
271
+
272
+ > This means `ctrl.setWindow()` **recomputes the entire LUT and re-maps every pixel** (`updateTexture` in `texture2d.ts`), then sets `texture.needsUpdate = true` to re-upload. For 32 frames this is non-trivial — it is the trade-off this design accepts in exchange for a minimal shader.
273
+
274
+ ### 6.3 Building the LUT (`copperDicomLoader.ts` `getLut`)
275
+
276
+ ```ts
277
+ // ① scan once to find the actual min/max pixel value (table only covers the real range, saves memory)
278
+ for (...) { minPixelValue = min; maxPixelValue = max; }
279
+
280
+ let offset = Math.min(minPixelValue, 0); // handle signed (negative) pixels
281
+ let lutArray = new Uint8ClampedArray(maxPixelValue - offset + 1);
282
+ const vlutfn = getVOILUT(windowWidth, windowCenter, voiLUT, true);
283
+
284
+ // ② precompute the output for every possible input value in range
285
+ for (let v = minPixelValue; v <= maxPixelValue; v++) {
286
+ lutArray[v + -offset] = invert ? 255 - vlutfn(v) : vlutfn(v);
287
+ }
288
+ ```
289
+
290
+ Engineering details:
291
+ - **`offset`**: pixel values may be negative (signed CT); offset shifts the index to avoid negative subscripts.
292
+ - **`Uint8ClampedArray`**: auto-clamps out-of-range values to 0–255, which exactly implements "outside-window black/white" — no manual clamp needed.
293
+ - **MONOCHROME1 inversion**: some DICOM specify "larger value = darker"; use `255 - vlutfn(v)` to flip. Ordinary MONOCHROME2 is "larger value = brighter."
294
+
295
+ ### 6.4 The linear mapping formula (`getVOILUT.ts`)
296
+
297
+ ```ts
298
+ function generateLinearVOILUT(windowWidth, windowCenter) {
299
+ return (v) => ((v - windowCenter) / windowWidth + 0.5) * 255.0;
300
+ }
301
+ ```
302
+
303
+ Decomposing `output = ((v - WC) / WW + 0.5) × 255`:
304
+
305
+ | input v | output | meaning |
306
+ |---|---|---|
307
+ | `WC - WW/2` (lower edge) | 0 | pure black |
308
+ | `WC` (center) | 127.5 | mid gray |
309
+ | `WC + WW/2` (upper edge) | 255 | pure white |
310
+ | `< WC - WW/2` | clamped to 0 | all black |
311
+ | `> WC + WW/2` | clamped to 255 | all white |
312
+
313
+ That is the standard DICOM linear VOI LUT: "linear stretch inside the window, saturate outside."
314
+
315
+ ### 6.5 The full pipeline
316
+
317
+ ```
318
+ .dcm file
319
+ │ parsed by dicom-parser
320
+ ▼
321
+ uint16[] (16-bit raw pixels)
322
+ │ getLut(WW, WC): precompute input→8bit lookup table
323
+ ▼
324
+ lutArray[] (LUT, length = pixel value range)
325
+ │ for each pixel: uint8[i] = lutArray[uint16[i]]
326
+ ▼
327
+ uint8[] (8-bit grayscale, window baked in)
328
+ │ concatenate 32 frames → DataArrayTexture
329
+ ▼
330
+ GPU texture → shader sample × uBrightness + uOpacity → screen
331
+ ```
332
+
333
+ The raw `uint16` data is **kept** in `copperVolume` precisely so later `setWindow` can recompute — recomputation must start from `uint16`, never from the already-lossy `uint8`.
334
+
335
+ ### 6.6 ⚠️ The gotcha: a window whose lower bound is below zero
336
+
337
+ **Symptom:** what should be black background renders as dark grey, and the whole image looks washed out.
338
+
339
+ It is tempting to blame the shader. `texture2d_frag.glsl` used to hard-code a gain:
340
+
341
+ ```glsl
342
+ outColor = vec4( color.rrr * 1.5, uOpacity ); // "lighten a bit"
343
+ ```
344
+
345
+ **That gain is not what greys out the blacks.** `0 × 1.5` is still `0`. A multiplicative gain can never lift true black — it only clips the top of the range.
346
+
347
+ The real cause is arithmetic inside the window. This series declares:
348
+
349
+ ```
350
+ WindowCenter = 226 WindowWidth = 537
351
+ lower bound = 226 − 537/2 = −42.5
352
+ ```
353
+
354
+ MR pixel values are **never negative**. So the darkest sample the scanner can produce, `0`, maps to
355
+
356
+ ```
357
+ (0 − (−42.5)) / 537 × 255 ≈ 20
358
+ ```
359
+
360
+ Raw black lands at **20/255**, and no pixel in the image can ever reach 0. Measured on frame 1 of this series:
361
+
362
+ | window / gain | lower bound | % pure black | % clipped white | mean |
363
+ |---|---|---|---|---|
364
+ | DICOM's own (226 / 537), ×1.5 | −42.5 | **0.0 %** | 1.3 % | 84.1 |
365
+ | DICOM's own (226 / 537), ×1.0 | −42.5 | **0.0 %** | 0.0 % | 56.5 |
366
+ | re-floored (247 / 494), ×1.0 | 0 | **2.8 %** | 0.0 % | 39.5 |
367
+ | re-floored (247 / 494), ×1.5 | 0 | **2.8 %** | 1.0 % | 58.7 |
368
+
369
+ **The fix is to floor the window at zero**, keeping the same ceiling (`WC + WW/2 = 494.5`):
370
+
371
+ ```ts
372
+ scene.loadAligned4D({
373
+ dicomUrls,
374
+ window: { center: 247, width: 494 }, // lower bound = 0
375
+ surfaces: [...],
376
+ });
377
+ ```
378
+
379
+ Note the last row: once the floor is at 0, blacks stay black **even with the ×1.5 gain**, because the gain cannot lift 0. The gain is still worth controlling — at 1.5 it clips ~1 % of pixels to pure white — so it is now a uniform instead of a magic number:
380
+
381
+ ```glsl
382
+ uniform float uBrightness; // defaults to 1.5, the historical hard-coded value
383
+ outColor = vec4( color.rrr * uBrightness, uOpacity );
384
+ ```
385
+
386
+ reachable at runtime:
387
+
388
+ ```ts
389
+ ctrl.setPlaneBrightness(1.0); // faithful; 1.5 is the historical default
390
+ ctrl.setWindow(247, 494); // recomputes the LUT from the retained uint16
391
+ ```
392
+
393
+ **The lesson generalises:** when a medical image refuses to go black, check `WC − WW/2` before you touch the shader. A DICOM's declared window is a *display suggestion*, not a promise that it maps the sensor's floor to zero.
394
+
395
+ ### 6.7 If you want real-time window dragging (GPU version)
396
+
397
+ Pass the raw 16-bit into the shader and do windowing on the GPU:
398
+
399
+ ```glsl
400
+ uniform sampler2DArray diffuse; // store raw values as R16/R32F, do NOT pre-squeeze to 8-bit
401
+ uniform int depth;
402
+ uniform float windowCenter;
403
+ uniform float windowWidth;
404
+
405
+ void main() {
406
+ float v = texture(diffuse, vec3(vUv, depth)).r;
407
+ float g = clamp((v - windowCenter) / windowWidth + 0.5, 0.0, 1.0);
408
+ outColor = vec4(vec3(g), uOpacity);
409
+ }
410
+ ```
411
+
412
+ Dragging only changes two uniforms — zero texture re-uploads, smooth even at 32 frames; the cost is doubled VRAM. This is the classic "CPU-precomputed LUT" vs "GPU real-time" trade-off: static / low-frame → former (simple); interactive windowing / large data → latter.
413
+
414
+ ---
415
+
416
+ ## 7. The three.js animation loop & tick callbacks
417
+
418
+ ### 7.1 What animation really is
419
+
420
+ A screen has no "continuous motion" — animation is **drawing ~60 slightly different still images per second**. three.js does not animate anything for you — you must write the loop yourself and, every frame, **change data → redraw**.
421
+
422
+ ### 7.2 The browser's heartbeat: requestAnimationFrame
423
+
424
+ `requestAnimationFrame(fn)` means "call `fn` once, just before the next screen refresh." It fires only once; to loop, the function must **call itself again**:
425
+
426
+ ```js
427
+ function animate() {
428
+ requestAnimationFrame(animate); // schedule next frame → infinite loop
429
+ // change data
430
+ renderer.render(scene, camera); // draw one frame
431
+ }
432
+ animate(); // start
433
+ ```
434
+
435
+ Versus `setInterval`, rAF syncs to the display refresh and auto-pauses when the tab is backgrounded.
436
+
437
+ ### 7.3 This project's loop (`copperRenderer.ts`)
438
+
439
+ ```ts
440
+ animate = (time?) => {
441
+ if (!this.running) return;
442
+ requestAnimationFrame(this.animate); // self-scheduling
443
+ this.delta += this.renderClock.getDelta();
444
+ if (this.delta > this.interval) { // only draw once enough time has accumulated (frame-rate cap)
445
+ this.render();
446
+ }
447
+ };
448
+
449
+ render() {
450
+ this.currentScene.render(); // ① draw the current scene
451
+ this.preRenderCallbackFunctions.forEach((item) => {
452
+ item.call(null); // ② run every registered callback
453
+ });
454
+ }
455
+ ```
456
+
457
+ `appRenderer.animate()` in `example15` is the "kick that starts the heartbeat."
458
+
459
+ ### 7.4 What "register a tick callback" means
460
+
461
+ The framework maintains a registry `preRenderCallbackFunctions`, and every frame it iterates its `cache` and calls each function once. **"Registering a tick callback" = adding your function to that per-frame registry.** Once in, your function automatically gains the ability to run "every frame."
462
+
463
+ ```ts
464
+ addPreRenderCallbackFunction(callbackFunction) {
465
+ return this.preRenderCallbackFunctions.add(callbackFunction); // returns the id
466
+ }
467
+ ```
468
+
469
+ In the 4D code:
470
+
471
+ ```ts
472
+ const tick = () => { /* advance frameIndex, switch layer, swap geometry */ };
473
+ const clockId = this.addPreRenderCallbackFunction(tick); // register, keep the id
474
+ // on dispose: this.removePreRenderCallbackFunction(clockId); // unregister
475
+ ```
476
+
477
+ #### ⚠️ An id is not an array index
478
+
479
+ The registry (`Scene/preRenderRegistry.ts`) hands out ids from a **monotonic counter** and keeps them in an array parallel to `cache`. That distinction matters, and the earlier implementation got it wrong in three compounding ways:
480
+
481
+ 1. its `index` was never incremented, so `addPreRenderCallbackFunction` **always returned `0`**;
482
+ 2. `add` guarded with `if (!fn.id)` while the very first id was `0` — falsy — so the first callback looked unregistered forever;
483
+ 3. `remove(id)` spliced `cache` at the raw id, **treating the id as an array index**, so removing one callback shifted every later one and silently invalidated its owner's id.
484
+
485
+ This was not theoretical. `example13` registers the segmentation tool's tick first (id `0`), then a second callback `a`. Registration returned `0` for `a`, so removing `a` deleted **the segmentation tool's** callback instead. `loadAligned4D` had quietly worked around it by reading a private `(tick as any).id` that `add` stamped onto the function.
486
+
487
+ Ids are now stable across removals, never reused, and `remove` of an unknown id is a no-op — behaviour pinned by unit tests in `Scene/preRenderRegistry.test.ts`.
488
+
489
+ **Rule of thumb:** if a handle is returned to a caller who may hold it across other mutations, it must not be a positional index into a mutable array.
490
+
491
+ **Core insight:** the tick itself **does not draw** — it only **changes data** (frameIndex+1, switch texture layer, swap geometry); the actual drawing is `scene.render()`. Both happen in order within the same frame — change the data, draw it, and it moves.
492
+
493
+ ### 7.5 Why the "callback array" design
494
+
495
+ For **decoupling**: a generic loop should not know about a specific business like "cardiac 4D." Via the registration mechanism: add behavior → push into array; stop behavior → remove from array (which is exactly what `dispose()` does); multiple animations coexist without interfering. This is the "hook / pub-sub" pattern applied to the render loop — React Three Fiber's `useFrame` and a game engine's `Update()` are fundamentally the same thing.
496
+
497
+ ### 7.6 The three-element self-test
498
+
499
+ ```js
500
+ function animate() {
501
+ requestAnimationFrame(animate); // ① loop
502
+ tickCallbacks.forEach((fn) => fn()); // ② change data
503
+ renderer.render(scene, camera); // ③ draw
504
+ }
505
+ ```
506
+
507
+ - Remove ① → only one frame is drawn, no motion (loop broken).
508
+ - Remove ② → no motion (nobody changes data; every frame is identical).
509
+ - Remove ③ → data changes but the screen never updates (nobody draws).
510
+
511
+ All three are required. The 4D heart simply swaps "rotate a cube" for "switch MRI layer + swap heart geometry."
512
+
513
+ ---
514
+
515
+ ## 8. Build it from scratch: the minimal skeleton
516
+
517
+ For any "image sequence + model sequence + aligned animation" problem, follow this recipe:
518
+
519
+ ```ts
520
+ // ── Step 1: stack the image sequence into one DataArrayTexture ──────────────
521
+ const frameSize = width * height;
522
+ const big = new Uint8ClampedArray(frameSize * N);
523
+ frames
524
+ .sort((a, b) => a.time - b.time) // ★ sort by temporal phase, NOT filename
525
+ .forEach((f, i) => big.set(f.data, i * frameSize));
526
+
527
+ const tex = new THREE.DataArrayTexture(big, width, height, N);
528
+ tex.format = THREE.RedFormat;
529
+ tex.needsUpdate = true;
530
+
531
+ const planeMat = new THREE.ShaderMaterial({
532
+ glslVersion: THREE.GLSL3,
533
+ uniforms: { diffuse: { value: tex }, depth: { value: 0 } },
534
+ vertexShader: /* pass uv through */,
535
+ fragmentShader: `
536
+ precision highp sampler2DArray;
537
+ uniform sampler2DArray diffuse; uniform int depth; in vec2 vUv; out vec4 o;
538
+ void main(){ o = texture(diffuse, vec3(vUv, depth)); }`,
539
+ });
540
+
541
+ // ── Step 2: place the plane in REAL world coordinates, not the origin ─────────
542
+ const g = new THREE.BufferGeometry();
543
+ g.setAttribute("position", new THREE.BufferAttribute(
544
+ new Float32Array([...tl, ...bl, ...tr, ...tr, ...bl, ...br]), 3));
545
+ g.setAttribute("uv", new THREE.BufferAttribute(
546
+ new Float32Array([0,1, 0,0, 1,1, 1,1, 0,0, 1,0]), 2));
547
+ const plane = new THREE.Mesh(g, planeMat);
548
+ scene.add(plane);
549
+
550
+ // ── Step 3: model sequence — 1 mesh per group, prestore all geometries ──
551
+ const geos = await Promise.all(urls.map(loadGeometryKeepWorldCoords)); // ★ no center/scale
552
+ const surf = new THREE.Mesh(geos[0], surfMat);
553
+ scene.add(surf);
554
+
555
+ // ── Step 4: one clock drives everything ────────────────────────────
556
+ let frame = 0, last = performance.now();
557
+ const dt = cycleMs / N;
558
+ function tick() {
559
+ const now = performance.now();
560
+ if (now - last >= dt) {
561
+ last = now;
562
+ frame = (frame + 1) % N;
563
+ planeMat.uniforms.depth.value = frame; // image layer
564
+ surf.geometry = geos[frame]; // model reference swap
565
+ }
566
+ requestAnimationFrame(tick);
567
+ }
568
+ tick();
569
+ ```
570
+
571
+ ---
572
+
573
+ ## 9. Key principles cheat-sheet
574
+
575
+ 1. **Image sequence → DataArrayTexture; switch frames by changing only the `depth` uniform** (never re-upload the texture each frame).
576
+ 2. **Model sequence → decode all geometries up front; switch frames by swapping the `mesh.geometry` reference** (never rebuild the mesh each frame).
577
+ 3. **Alignment = use original world coordinates throughout; never `center()` / `scale()`** (the image is placed via DICOM geometry tags; the model uses raw vertices).
578
+ 4. **One shared `frameIndex` + a `performance.now()`-based clock** keeps everything in phase and decouples speed from refresh rate.
579
+ 5. **The three elements of three.js animation**: loop (rAF) + change data (tick callback) + draw (render) — all three required.
580
+ 6. **Windowing trade-off**: CPU-precomputed LUT (simple, low frame count) vs GPU real-time (smooth, doubled VRAM).