dicom-three 0.0.0-stage → 0.1.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 (59) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +94 -2
  4. package/THIRD_PARTY_NOTICES.md +32 -0
  5. package/dist/THIRD_PARTY_LICENSES.txt +209 -0
  6. package/dist/assets/decodeDicomSeries-Cuz_Ucce.js +72556 -0
  7. package/dist/assets/dicom.worker-_n6H46nx.js +60 -0
  8. package/dist/assets/index-BFX7TgQR.js +16 -0
  9. package/dist/assets/index-Cg7QXfcH.js +8 -0
  10. package/dist/dicom3.js +2416 -0
  11. package/dist/dicom3.umd.cjs +427 -0
  12. package/dist/types/index.d.ts +5 -0
  13. package/dist/types/libs/index.d.ts +1 -0
  14. package/dist/types/libs/typedArrayConstructor.d.ts +9 -0
  15. package/dist/types/loaders/dicomLoader.d.ts +38 -0
  16. package/dist/types/loaders/dicomPreloader.d.ts +28 -0
  17. package/dist/types/loaders/dicomWorkerLoader.d.ts +32 -0
  18. package/dist/types/loaders/index.d.ts +3 -0
  19. package/dist/types/parsers/dicomDataSet.d.ts +43 -0
  20. package/dist/types/parsers/dicomParser.d.ts +194 -0
  21. package/dist/types/parsers/index.d.ts +2 -0
  22. package/dist/types/stack/assembleStackData.d.ts +5 -0
  23. package/dist/types/stack/extractPixelData.d.ts +10 -0
  24. package/dist/types/stack/extractPreprocessParams.d.ts +10 -0
  25. package/dist/types/stack/getTypedArrayForDicom.d.ts +8 -0
  26. package/dist/types/stack/index.d.ts +2 -0
  27. package/dist/types/stack/preprocessParams.d.ts +8 -0
  28. package/dist/types/stack/seriesGeometry.d.ts +36 -0
  29. package/dist/types/stack/seriesOrder.d.ts +15 -0
  30. package/dist/types/stack/stack.d.ts +46 -0
  31. package/dist/types/stack/stackData.d.ts +24 -0
  32. package/dist/types/stack/textureConfig.d.ts +8 -0
  33. package/dist/types/stack/textureFactory.d.ts +9 -0
  34. package/dist/types/stack/validateParsers.d.ts +9 -0
  35. package/dist/types/utils/index.d.ts +2 -0
  36. package/dist/types/utils/slicePlane.d.ts +30 -0
  37. package/dist/types/utils/stackGeometry.d.ts +14 -0
  38. package/dist/types/viewers/index.d.ts +4 -0
  39. package/dist/types/viewers/obliqueSlice/geometry.d.ts +30 -0
  40. package/dist/types/viewers/obliqueSlice/index.d.ts +1 -0
  41. package/dist/types/viewers/obliqueSlice/obliqueSlice.d.ts +46 -0
  42. package/dist/types/viewers/obliqueSlice/shaders/generateFragment.d.ts +2 -0
  43. package/dist/types/viewers/orthoSlicer/orthoSlicer.d.ts +41 -0
  44. package/dist/types/viewers/orthoSlicer/shaders/generateFragment.d.ts +6 -0
  45. package/dist/types/viewers/shared/fn.d.ts +4 -0
  46. package/dist/types/viewers/shared/lifecycle.d.ts +5 -0
  47. package/dist/types/viewers/shared/sliceWindow.d.ts +19 -0
  48. package/dist/types/viewers/shared/voxelCoordinates.d.ts +2 -0
  49. package/dist/types/viewers/slice/index.d.ts +1 -0
  50. package/dist/types/viewers/slice/slice.d.ts +40 -0
  51. package/dist/types/viewers/volume/index.d.ts +3 -0
  52. package/dist/types/viewers/volume/presets.d.ts +203 -0
  53. package/dist/types/viewers/volume/shaders/generateFragment.d.ts +6 -0
  54. package/dist/types/viewers/volume/types.d.ts +30 -0
  55. package/dist/types/viewers/volume/volumeRaycaster.d.ts +70 -0
  56. package/docs/architecture.md +272 -0
  57. package/docs/integration.md +215 -0
  58. package/docs/release.md +19 -0
  59. package/package.json +71 -5
package/dist/dicom3.js ADDED
@@ -0,0 +1,2416 @@
1
+ var ve = Object.defineProperty;
2
+ var Se = (i, t, e) => t in i ? ve(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
+ var a = (i, t, e) => Se(i, typeof t != "symbol" ? t + "" : t, e);
4
+ import _e from "@cornerstonejs/dicom-codec";
5
+ import le from "dicom-parser";
6
+ import * as u from "three";
7
+ import { Vector3 as T, Box3 as be, Matrix3 as Pe } from "three";
8
+ class K {
9
+ constructor(t) {
10
+ a(this, "_dataSet");
11
+ a(this, "_arrayBuffer");
12
+ this._arrayBuffer = t.buffer;
13
+ try {
14
+ const e = new Uint8Array(this._arrayBuffer);
15
+ this._dataSet = le.parseDicom(e);
16
+ } catch (e) {
17
+ throw console.log(e), new Error("parsers.dicom could not parse the file");
18
+ }
19
+ }
20
+ /**
21
+ * Series instance UID (0020,000e)
22
+ *
23
+ */
24
+ get seriesInstanceUID() {
25
+ return this._dataSet.string("x0020000e") ?? null;
26
+ }
27
+ get frameOfReferenceUID() {
28
+ return this._dataSet.string("x00200052") ?? null;
29
+ }
30
+ temporalPosition(t = 0) {
31
+ var e;
32
+ return ((e = this._findInGroupSequence("x52009230", "x00209111", t)) == null ? void 0 : e.uint32("x00209128")) ?? this._dataSet.intString("x00200100") ?? null;
33
+ }
34
+ stackId(t = 0) {
35
+ var e;
36
+ return ((e = this._findInGroupSequence("x52009230", "x00209111", t)) == null ? void 0 : e.string("x00209056")) ?? null;
37
+ }
38
+ /**
39
+ * Study instance UID (0020,000d)
40
+ */
41
+ get studyInstanceUID() {
42
+ return this._dataSet.string("x0020000d") ?? null;
43
+ }
44
+ /**
45
+ * Get modality (0008,0060)
46
+ */
47
+ get modality() {
48
+ return this._dataSet.string("x00080060") ?? null;
49
+ }
50
+ /**
51
+ * Segmentation type (0062,0001)
52
+ */
53
+ get segmentationType() {
54
+ return this._dataSet.string("x00620001") ?? null;
55
+ }
56
+ /**
57
+ * Segmentation segments
58
+ * -> Sequence of segments (0062,0002)
59
+ * -> Recommended Display CIELab
60
+ * -> Segmentation Code
61
+ * -> Segment Number (0062,0004)
62
+ * -> Segment Label (0062,0005)
63
+ * -> Algorithm Type (0062,0008)
64
+ *
65
+ */
66
+ get segmentationSegments() {
67
+ const t = [], e = this._dataSet.elements.x00620002;
68
+ if (!e || !e.items) return t;
69
+ for (const n of e.items) {
70
+ if (!n.dataSet) continue;
71
+ const r = this._recommendedDisplayCIELab({
72
+ dataSet: n.dataSet
73
+ }), o = this._segmentationCode({ dataSet: n.dataSet }), s = n.dataSet.uint16("x00620004"), l = n.dataSet.string("x00620005"), c = n.dataSet.string("x00620008");
74
+ t.push({
75
+ recommendedDisplayCIELab: r,
76
+ segmentationCodeDesignator: o.segmentationCodeDesignator,
77
+ segmentationCodeValue: o.segmentationCodeValue,
78
+ segmentationCodeMeaning: o.segmentationCodeMeaning,
79
+ segmentNumber: s || null,
80
+ segmentLabel: l || null,
81
+ segmentAlgorithmType: c || null
82
+ });
83
+ }
84
+ return t;
85
+ }
86
+ /**
87
+ * Segmentation code
88
+ * -> Code designator (0008,0102)
89
+ * -> Code value (0008,0200)
90
+ * -> Code Meaning Type (0008,0104)
91
+ */
92
+ _segmentationCode(t) {
93
+ const e = t.dataSet.elements.x00082218;
94
+ if (e && e.items && e.items.length > 0) {
95
+ const n = e.items[0].dataSet;
96
+ if (n)
97
+ return {
98
+ segmentationCodeDesignator: n.string("x00080102") || "unknown",
99
+ segmentationCodeValue: n.string("x00080100") || "unknown",
100
+ segmentationCodeMeaning: n.string("x00080104") || "unknown"
101
+ };
102
+ }
103
+ return {
104
+ segmentationCodeDesignator: "unknown",
105
+ segmentationCodeValue: "unknown",
106
+ segmentationCodeMeaning: "unknown"
107
+ };
108
+ }
109
+ /**
110
+ * Recommended display CIELab
111
+ */
112
+ _recommendedDisplayCIELab(t) {
113
+ if (!t.dataSet.elements.x0062000d)
114
+ return null;
115
+ let e = t.dataSet.elements.x0062000d.dataOffset, n = t.dataSet.elements.x0062000d.length, r = t.dataSet.byteArray.slice(e, e + n), o = new Uint16Array(n / 2);
116
+ for (let l = 0; l < n / 2; l++)
117
+ o[l] = (r[2 * l + 1] << 8) + r[2 * l];
118
+ return [
119
+ o[0] / 65535 * 100,
120
+ o[1] / 65535 * 255 - 128,
121
+ o[2] / 65535 * 255 - 128
122
+ ];
123
+ }
124
+ /**
125
+ * Raw dataset
126
+ */
127
+ get rawHeader() {
128
+ return this._dataSet;
129
+ }
130
+ /**
131
+ * SOP Instance UID
132
+ */
133
+ sopInstanceUID(t = 0) {
134
+ return this._findStringEverywhere("x2005140f", "x00080018", t);
135
+ }
136
+ /**
137
+ * Transfer syntax UID
138
+ */
139
+ get transferSyntaxUID() {
140
+ return this._dataSet.string("x00020010") ?? null;
141
+ }
142
+ /**
143
+ * Study date
144
+ */
145
+ get studyDate() {
146
+ return this._dataSet.string("x00080020") ?? null;
147
+ }
148
+ /**
149
+ * Study description
150
+ */
151
+ get studyDescription() {
152
+ return this._dataSet.string("x00081030") ?? null;
153
+ }
154
+ /**
155
+ * Series date
156
+ */
157
+ get seriesDate() {
158
+ return this._dataSet.string("x00080021") ?? null;
159
+ }
160
+ /**
161
+ * Series description
162
+ */
163
+ get seriesDescription() {
164
+ return this._dataSet.string("x0008103e") ?? null;
165
+ }
166
+ /**
167
+ * Patient name
168
+ */
169
+ get patientName() {
170
+ return this._dataSet.string("x00100010") ?? null;
171
+ }
172
+ /**
173
+ * Patient ID
174
+ */
175
+ get patientID() {
176
+ return this._dataSet.string("x00100020") ?? null;
177
+ }
178
+ /**
179
+ * Patient birthdate
180
+ */
181
+ get patientBirthdate() {
182
+ return this._dataSet.string("x00100030") ?? null;
183
+ }
184
+ /**
185
+ * Patient sex
186
+ */
187
+ get patientSex() {
188
+ return this._dataSet.string("x00100040") ?? null;
189
+ }
190
+ /**
191
+ * Patient age
192
+ */
193
+ get patientAge() {
194
+ return this._dataSet.string("x00101010") ?? null;
195
+ }
196
+ /**
197
+ * Photometric interpretation
198
+ */
199
+ get photometricInterpretation() {
200
+ return this._dataSet.string("x00280004") ?? null;
201
+ }
202
+ get planarConfiguration() {
203
+ return this._dataSet.uint16("x00280006") ?? null;
204
+ }
205
+ get samplesPerPixel() {
206
+ return this._dataSet.uint16("x00280002") ?? null;
207
+ }
208
+ get numberOfFrames() {
209
+ return this._dataSet.intString("x00280008");
210
+ }
211
+ get numberOfChannels() {
212
+ let t = 1, e = this.photometricInterpretation;
213
+ return e !== "RGB" && e !== "PALETTE COLOR" && e !== "YBR_FULL" && e !== "YBR_FULL_422" && e !== "YBR_PARTIAL_422" && e !== "YBR_PARTIAL_420" && e !== "YBR_RCT" || (t = 3), t;
214
+ }
215
+ invert() {
216
+ return this.photometricInterpretation === "MONOCHROME1";
217
+ }
218
+ imageOrientation(t = 0) {
219
+ const e = this._findStringEverywhere("x00209116", "x00200037", t);
220
+ return e ? e.split("\\").map(parseFloat) : null;
221
+ }
222
+ referencedSegmentNumber(t = 0) {
223
+ let e = this._findInGroupSequence("x52009230", "x0062000a", t);
224
+ return e ? e.uint16("x0062000b") : -1;
225
+ }
226
+ get pixelAspectRatio() {
227
+ const t = [this._dataSet.intString("x00280034", 0), this._dataSet.intString("x00280034", 1)];
228
+ if (!(typeof t[0] > "u"))
229
+ return t;
230
+ }
231
+ imagePosition(t = 0) {
232
+ const e = this._findStringEverywhere("x00209113", "x00200032", t);
233
+ return e ? e.split("\\").map(parseFloat) : null;
234
+ }
235
+ hasPerFrameImagePosition(t = 0) {
236
+ var e;
237
+ return ((e = this._findInGroupSequence("x52009230", "x00209113", t)) == null ? void 0 : e.string("x00200032")) !== void 0;
238
+ }
239
+ instanceNumber(t = 0) {
240
+ var r, o;
241
+ let e = null;
242
+ const n = this._dataSet.elements.x52009230;
243
+ if (n != null && n.items && ((r = n.items[t]) != null && r.dataSet)) {
244
+ const s = n.items[t].dataSet.elements.x2005140f;
245
+ s != null && s.items && ((o = s.items[0]) != null && o.dataSet) ? e = s.items[0].dataSet.intString("x00200013") ?? null : e = this._dataSet.intString("x00200013") ?? null;
246
+ } else
247
+ e = this._dataSet.intString("x00200013") ?? null;
248
+ return e;
249
+ }
250
+ pixelSpacing(t = 0) {
251
+ const e = this._findStringEverywhere("x00289110", "x00280030", t), n = this._dataSet.string("x00181164"), r = e || n || null;
252
+ if (r) {
253
+ const o = r.split("\\");
254
+ return o.length !== 2 ? (console.error(`DICOM spacing format is not supported (could not split string on "\\"): ${r}`), null) : o.map(parseFloat);
255
+ }
256
+ return null;
257
+ }
258
+ ultrasoundRegions(t = 0) {
259
+ const e = this._dataSet.elements.x00186011;
260
+ if (!(e != null && e.items))
261
+ return [];
262
+ const n = [];
263
+ return e.items.forEach((r) => {
264
+ r.dataSet && n.push({
265
+ x0: r.dataSet.uint32("x00186018") ?? null,
266
+ y0: r.dataSet.uint32("x0018601a") ?? null,
267
+ x1: r.dataSet.uint32("x0018601c") ?? null,
268
+ y1: r.dataSet.uint32("x0018601e") ?? null,
269
+ axisX: r.dataSet.int32("x00186020") ?? null,
270
+ axisY: r.dataSet.int32("x00186022") ?? null,
271
+ unitsX: this._getUnitsName(r.dataSet.uint16("x00186024") ?? 0),
272
+ unitsY: this._getUnitsName(r.dataSet.uint16("x00186026") ?? 0),
273
+ deltaX: r.dataSet.double("x0018602c") ?? null,
274
+ deltaY: r.dataSet.double("x0018602e") ?? null
275
+ });
276
+ }), n;
277
+ }
278
+ get frameTime() {
279
+ const t = this._dataSet.uint16("x00280009", 1);
280
+ let e = this._dataSet.intString("x00082144");
281
+ if (typeof t == "number") {
282
+ const n = t.toString(16), r = this._dataSet.floatString("x0018" + n);
283
+ if (r !== void 0)
284
+ return r;
285
+ }
286
+ if (typeof e == "number")
287
+ return 1e3 / e;
288
+ }
289
+ get rows() {
290
+ return this._dataSet.uint16("x00280010");
291
+ }
292
+ get columns() {
293
+ return this._dataSet.uint16("x00280011");
294
+ }
295
+ get pixelType() {
296
+ return 0;
297
+ }
298
+ get pixelRepresentation() {
299
+ return this._dataSet.uint16("x00280103");
300
+ }
301
+ get pixelPaddingValue() {
302
+ return this._dataSet.int16("x00280120");
303
+ }
304
+ get bitsAllocated() {
305
+ return this._dataSet.uint16("x00280100");
306
+ }
307
+ get highBit() {
308
+ return this._dataSet.uint16("x00280102");
309
+ }
310
+ rescaleIntercept(t = 0) {
311
+ return this._findFloatStringInFrameGroupSequence("x00289145", "x00281052", t);
312
+ }
313
+ rescaleSlope(t = 0) {
314
+ return this._findFloatStringInFrameGroupSequence("x00289145", "x00281053", t);
315
+ }
316
+ windowCenter(t = 0) {
317
+ return this._findFloatStringInFrameGroupSequence("x00289132", "x00281050", t);
318
+ }
319
+ windowWidth(t = 0) {
320
+ return this._findFloatStringInFrameGroupSequence("x00289132", "x00281051", t);
321
+ }
322
+ sliceThickness(t = 0) {
323
+ return this._findFloatStringInFrameGroupSequence("x00289110", "x00180050", t);
324
+ }
325
+ spacingBetweenSlices(t = 0) {
326
+ return this._findFloatStringInFrameGroupSequence("x00289110", "x00180088", t);
327
+ }
328
+ dimensionIndexValues(t = 0) {
329
+ var r, o;
330
+ let e = null;
331
+ const n = this._dataSet.elements.x52009230;
332
+ if (n != null && n.items && ((r = n.items[t]) != null && r.dataSet)) {
333
+ const s = n.items[t].dataSet.elements.x00209111;
334
+ if (s != null && s.items && ((o = s.items[0]) != null && o.dataSet)) {
335
+ const l = s.items[0].dataSet.elements.x00209157;
336
+ if (l) {
337
+ const c = l.length / 4;
338
+ e = [];
339
+ for (let m = 0; m < c; m++)
340
+ e.push(s.items[0].dataSet.uint32("x00209157", m) ?? 0);
341
+ }
342
+ }
343
+ }
344
+ return e;
345
+ }
346
+ inStackPositionNumber(t = 0) {
347
+ var r, o;
348
+ let e = null;
349
+ const n = this._dataSet.elements.x52009230;
350
+ if (n != null && n.items && ((r = n.items[t]) != null && r.dataSet)) {
351
+ const s = n.items[t].dataSet.elements.x00209111;
352
+ s != null && s.items && ((o = s.items[0]) != null && o.dataSet) && (e = s.items[0].dataSet.uint32("x00209057") ?? null);
353
+ }
354
+ return e;
355
+ }
356
+ stackID(t = 0) {
357
+ var r, o, s;
358
+ let e = null;
359
+ const n = this._dataSet.elements.x52009230;
360
+ if (n != null && n.items && ((r = n.items[t]) != null && r.dataSet)) {
361
+ const l = n.items[t].dataSet.elements.x00209111;
362
+ l != null && l.items && ((o = l.items[0]) != null && o.dataSet) && (e = ((s = l.items[0].dataSet.intString("x00209056")) == null ? void 0 : s.toString()) ?? null);
363
+ }
364
+ return e;
365
+ }
366
+ get distanceSourceToDetector() {
367
+ return this._dataSet.floatString("x00181110");
368
+ }
369
+ get distanceSourceToPatient() {
370
+ return this._dataSet.floatString("x00181111");
371
+ }
372
+ /**
373
+ * @returns Rotate angle from tag `PositionerPrimaryAngle`in degrees
374
+ */
375
+ get positionerPrimaryAngle() {
376
+ return this._dataSet.floatString("x00181510");
377
+ }
378
+ /**
379
+ * @returns Rotate angle from tag `PositionerSecondaryAngle`in degrees
380
+ */
381
+ get positionerSecondaryAngle() {
382
+ return this._dataSet.floatString("x00181511");
383
+ }
384
+ async extractPixelData() {
385
+ return await this._decodePixelData();
386
+ }
387
+ _findInGroupSequence(t, e, n) {
388
+ var o, s;
389
+ const r = this._dataSet.elements[t];
390
+ if (r != null && r.items && ((o = r.items[n]) != null && o.dataSet)) {
391
+ const l = r.items[n].dataSet.elements[e];
392
+ if (l != null && l.items && ((s = l.items[0]) != null && s.dataSet))
393
+ return l.items[0].dataSet;
394
+ }
395
+ return null;
396
+ }
397
+ _findStringInGroupSequence(t, e, n, r) {
398
+ const o = this._findInGroupSequence(t, e, r);
399
+ return (o == null ? void 0 : o.string(n)) ?? null;
400
+ }
401
+ _findStringInFrameGroupSequence(t, e, n) {
402
+ return this._findStringInGroupSequence("x52009230", t, e, n) ?? this._findStringInGroupSequence("x52009229", t, e, 0);
403
+ }
404
+ _findStringEverywhere(t, e, n) {
405
+ let r = this._findStringInFrameGroupSequence(t, e, n);
406
+ return r || (r = this._findStringInSequence("x00540022", e)), r || (r = this._dataSet.string(e) ?? null), r;
407
+ }
408
+ _findStringInSequence(t, e) {
409
+ var r;
410
+ const n = this._dataSet.elements[t];
411
+ return n != null && n.items && ((r = n.items[0]) != null && r.dataSet) ? n.items[0].dataSet.string(e) ?? null : null;
412
+ }
413
+ _findFloatStringInFrameGroupSequence(t, e, n) {
414
+ var r, o;
415
+ return ((r = this._findInGroupSequence("x52009230", t, n)) == null ? void 0 : r.floatString(e)) ?? ((o = this._findInGroupSequence("x52009229", t, 0)) == null ? void 0 : o.floatString(e)) ?? this._dataSet.floatString(e) ?? null;
416
+ }
417
+ async _decodePixelData() {
418
+ const t = this.transferSyntaxUID, e = this._dataSet.elements.x7fe00010, n = new Uint8Array(this._dataSet.byteArray.buffer, e.dataOffset, e.length), r = this.bitsAllocated, o = this.columns, s = this.rows, l = this.samplesPerPixel, c = this.pixelRepresentation === 1;
419
+ return await _e.decode(n, { rows: s, columns: o, bitsAllocated: r, samplesPerPixel: l, signed: c }, t);
420
+ }
421
+ _interpretAsRGB(t) {
422
+ return ["RGB", "YBR_RCT", "YBR_ICT", "YBR_FULL_422"].indexOf(t) !== -1;
423
+ }
424
+ _convertColorSpace(t) {
425
+ let e = null;
426
+ const n = this.photometricInterpretation;
427
+ let r = this.planarConfiguration;
428
+ r === null && (r = 0, window.console.log("Planar Configuration was not set and was defaulted to 0"));
429
+ const o = n ? this._interpretAsRGB(n) : !1;
430
+ if (o && r === 0)
431
+ e = t;
432
+ else if (o && r === 1) {
433
+ if (t instanceof Int8Array)
434
+ e = new Int8Array(t.length);
435
+ else if (t instanceof Uint8Array)
436
+ e = new Uint8Array(t.length);
437
+ else if (t instanceof Int16Array)
438
+ e = new Int16Array(t.length);
439
+ else if (t instanceof Uint16Array)
440
+ e = new Uint16Array(t.length);
441
+ else
442
+ throw new Error(`Unsupported typed array: ${t}`);
443
+ let s = t.length / 3, l = 0, c = 0, m = s, d = s * 2;
444
+ for (let f = 0; f < s; f++)
445
+ e[l++] = t[c++], e[l++] = t[m++], e[l++] = t[d++];
446
+ } else if (n === "YBR_FULL") {
447
+ if (t instanceof Int8Array)
448
+ e = new Int8Array(t.length);
449
+ else if (t instanceof Uint8Array)
450
+ e = new Uint8Array(t.length);
451
+ else if (t instanceof Int16Array)
452
+ e = new Int16Array(t.length);
453
+ else if (t instanceof Uint16Array)
454
+ e = new Uint16Array(t.length);
455
+ else
456
+ throw new Error(`unsuported typed array: ${t}`);
457
+ let s = t.length / 3, l = 0, c = 0;
458
+ for (let m = 0; m < s; m++) {
459
+ let d = t[l++], f = t[l++], g = t[l++];
460
+ e[c++] = d + 1.402 * (g - 128), e[c++] = d - 0.34414 * (f - 128) - 0.71414 * (g - 128), e[c++] = d + 1.772 * (f - 128);
461
+ }
462
+ } else
463
+ throw new Error(`photometric interpolation not supported: ${n}`);
464
+ return e;
465
+ }
466
+ // used if OpenJPEG library isn't loaded (OHIF/image-JPEG2000 isn't supported and can't parse some images)
467
+ // from cornerstone
468
+ _getUnitsName(t) {
469
+ return {
470
+ 0: "none",
471
+ 1: "percent",
472
+ 2: "dB",
473
+ 3: "cm",
474
+ 4: "seconds",
475
+ 5: "hertz",
476
+ 6: "dB/seconds",
477
+ 7: "cm/sec",
478
+ 8: "cm2",
479
+ 9: "cm2/sec",
480
+ 10: "cm3",
481
+ 11: "cm3/sec",
482
+ 12: "degrees"
483
+ }[t] ?? "none";
484
+ }
485
+ }
486
+ class it extends u.Loader {
487
+ constructor(t) {
488
+ super(t);
489
+ }
490
+ /**
491
+ * Load dicom file
492
+ * @param url url
493
+ * @param onLoad Коллбэк при успешной загрузке (получает DicomParser)
494
+ * @param onProgress Коллбэк прогресса загрузки
495
+ * @param onError Коллбэк ошибки загрузки
496
+ */
497
+ load(t, e, n, r) {
498
+ const o = new u.FileLoader(this.manager);
499
+ o.setResponseType("arraybuffer"), o.load(
500
+ t,
501
+ (s) => {
502
+ try {
503
+ const l = new K({ buffer: s });
504
+ e == null || e(l);
505
+ } catch (l) {
506
+ console.error("Ошибка парсинга DICOM:", l), r == null || r(l);
507
+ }
508
+ },
509
+ n,
510
+ r
511
+ );
512
+ }
513
+ /**
514
+ * Load dicom file async
515
+ * @param url URL DICOM-файла.
516
+ * @returns Промис с объектом DicomParser.
517
+ */
518
+ async loadAsync(t) {
519
+ const e = new u.FileLoader(this.manager);
520
+ return e.setResponseType("arraybuffer"), new Promise((n, r) => {
521
+ e.load(
522
+ t,
523
+ (o) => {
524
+ try {
525
+ n(new K({ buffer: o }));
526
+ } catch (s) {
527
+ r(s);
528
+ }
529
+ },
530
+ void 0,
531
+ r
532
+ );
533
+ });
534
+ }
535
+ /**
536
+ * Загружает несколько DICOM-файлов асинхронно.
537
+ * @param files dicom file array
538
+ * @returns Промис с массивом объектов DicomParser.
539
+ */
540
+ async loadMultipleAsync(t) {
541
+ const e = t.map(async (r) => {
542
+ const o = URL.createObjectURL(r);
543
+ try {
544
+ const s = await this.loadAsync(o);
545
+ return console.log(`✅ DICOM загружен: ${r.name}`), s;
546
+ } catch (s) {
547
+ return console.error(`❌ Ошибка загрузки файла ${r.name}:`, s), null;
548
+ } finally {
549
+ URL.revokeObjectURL(o);
550
+ }
551
+ });
552
+ return (await Promise.all(e)).filter((r) => r !== null);
553
+ }
554
+ /**
555
+ * Загружает несколько серий DICOM-файлов асинхронно.
556
+ * @param series Массив серий DICOM (каждая серия - массив файлов).
557
+ * @returns Промис с массивом массивов объектов DicomParser (соответствует входным сериям).
558
+ */
559
+ async loadMultipleSeriesAsync(t) {
560
+ const e = t.map(async (r) => {
561
+ const o = r.dicomFiles.map((s) => s.file);
562
+ return this.loadMultipleAsync(o);
563
+ });
564
+ return (await Promise.all(e)).filter((r) => r.length > 0);
565
+ }
566
+ }
567
+ const R = 1e-4;
568
+ function A(i) {
569
+ if (i.length !== 6 || !i.every(Number.isFinite)) throw new Error("Invalid ImageOrientationPatient");
570
+ const t = Math.hypot(...i.slice(0, 3)), e = Math.hypot(...i.slice(3));
571
+ if (Math.abs(t - 1) > R || Math.abs(e - 1) > R || Math.abs(i[0] * i[3] + i[1] * i[4] + i[2] * i[5]) > R)
572
+ throw new Error("ImageOrientationPatient must contain orthonormal direction cosines");
573
+ return i.map((n, r) => n / (r < 3 ? t : e));
574
+ }
575
+ function ce(i) {
576
+ const t = [i[1] * i[5] - i[2] * i[4], i[2] * i[3] - i[0] * i[5], i[0] * i[4] - i[1] * i[3]], e = Math.hypot(...t);
577
+ return t.map((n) => n / e);
578
+ }
579
+ function W(i, t) {
580
+ return i[0] * t[0] + i[1] * t[1] + i[2] * t[2];
581
+ }
582
+ function j(i, t = !0) {
583
+ let e;
584
+ if (t && i.length && i.every((r) => {
585
+ var o;
586
+ return ((o = r.imagePosition) == null ? void 0 : o.length) === 3 && r.imagePosition.every(Number.isFinite) && r.imageOrientation;
587
+ }))
588
+ try {
589
+ const r = i.reduce((s, l) => s.id < l.id ? s : l), o = A(r.imageOrientation);
590
+ i.every((s) => A(s.imageOrientation).every((l, c) => Math.abs(l - o[c]) <= R)) && (e = ce(o));
591
+ } catch {
592
+ }
593
+ const n = e ? (r) => W(r.imagePosition, e) : i.every((r) => Number.isFinite(r.instanceNumber)) ? (r) => r.instanceNumber : i.every((r) => Number.isFinite(r.sliceLocation)) ? (r) => r.sliceLocation : () => 0;
594
+ return [...i].sort((r, o) => n(r) - n(o) || (r.id < o.id ? -1 : r.id > o.id ? 1 : 0));
595
+ }
596
+ const Te = (i) => {
597
+ const t = i.every((e) => {
598
+ var n;
599
+ return ((n = e.modality) == null ? void 0 : n.toUpperCase()) !== "XA" && e.numberOfFrames === 1;
600
+ });
601
+ return j(i.map((e) => ({ ...e, id: `${e.SOPInstanceUID}:${e.file.name}` })), t).map(({ id: e, ...n }) => n);
602
+ };
603
+ function Q(i, t, e) {
604
+ var n, r, o, s, l, c, m;
605
+ for (const d of ["x52009230", "x52009229"]) {
606
+ const f = (o = (r = (n = i.elements[d]) == null ? void 0 : n.items) == null ? void 0 : r[0]) == null ? void 0 : o.dataSet, g = (m = (c = (l = (s = f == null ? void 0 : f.elements[t]) == null ? void 0 : s.items) == null ? void 0 : l[0]) == null ? void 0 : c.dataSet) == null ? void 0 : m.string(e);
607
+ if (g !== void 0) return g;
608
+ }
609
+ return i.string(e);
610
+ }
611
+ const nt = async (i) => {
612
+ var n, r, o;
613
+ const t = /* @__PURE__ */ new Map();
614
+ for (const s of Array.from(i))
615
+ try {
616
+ const l = await s.arrayBuffer(), c = le.parseDicom(new Uint8Array(l), { untilTag: "x7fe00010" }), m = c.string("x0020000e") || "unknown", d = c.string("x00080018") || "unknown", f = c.floatString("x00201041"), g = (n = Q(c, "x00209113", "x00200032")) == null ? void 0 : n.split("\\").map(parseFloat), v = (r = Q(c, "x00209116", "x00200037")) == null ? void 0 : r.split("\\").map(parseFloat), w = g == null ? void 0 : g[2], y = c.intString("x00200013"), b = c.uint16("x00280010") ?? -1, P = c.uint16("x00280011") ?? -1;
617
+ if (b <= 0 || P <= 0)
618
+ throw new Error(`Invalid DICOM dimensions: rows=${b}, columns=${P}`);
619
+ const I = {
620
+ file: s,
621
+ SOPInstanceUID: d,
622
+ rows: b,
623
+ columns: P,
624
+ numberOfFrames: c.intString("x00280008") ?? 1,
625
+ bitsAllocated: c.uint16("x00280100") ?? 16,
626
+ pixelRepresentation: c.uint16("x00280103") ?? 0,
627
+ samplesPerPixel: c.uint16("x00280002") ?? 1,
628
+ sliceLocation: f,
629
+ imagePositionZ: w,
630
+ imagePosition: g,
631
+ imageOrientation: v,
632
+ modality: c.string("x00080060"),
633
+ instanceNumber: y
634
+ };
635
+ t.has(m) || t.set(m, []), (o = t.get(m)) == null || o.push(I);
636
+ } catch (l) {
637
+ console.error(`Error parsing DICOM file: ${s.name}`, l);
638
+ }
639
+ const e = [];
640
+ return t.forEach((s, l) => {
641
+ const c = Te(s);
642
+ e.push({ seriesInstanceUID: l, dicomFiles: c });
643
+ }), e;
644
+ };
645
+ function ee() {
646
+ const i = new Error("DICOM loading was aborted");
647
+ return i.name = "AbortError", i;
648
+ }
649
+ class rt {
650
+ constructor(t = {}) {
651
+ a(this, "workerFactory");
652
+ a(this, "worker");
653
+ a(this, "activeRequest");
654
+ a(this, "nextRequestId", 1);
655
+ a(this, "disposed", !1);
656
+ a(this, "handleMessage", (t) => {
657
+ var o;
658
+ const e = t.data, n = this.activeRequest;
659
+ if (!n || e.requestId !== n.requestId)
660
+ return;
661
+ if (e.type === "progress") {
662
+ (o = n.onProgress) == null || o.call(n, {
663
+ completed: e.completed,
664
+ total: e.total,
665
+ fileName: e.fileName
666
+ });
667
+ return;
668
+ }
669
+ if (this.clearActiveRequest(), e.type === "success") {
670
+ n.resolve(e.data);
671
+ return;
672
+ }
673
+ const r = new Error(e.error.message);
674
+ r.name = e.error.name, r.stack = e.error.stack, n.reject(r);
675
+ });
676
+ a(this, "handleWorkerError", (t) => {
677
+ this.rejectActiveRequest(t.error instanceof Error ? t.error : new Error(t.message)), this.terminateWorker();
678
+ });
679
+ a(this, "handleMessageError", () => {
680
+ this.rejectActiveRequest(new Error("Failed to deserialize a message from the DICOM worker")), this.terminateWorker();
681
+ });
682
+ this.workerFactory = t.workerFactory ?? (() => new Worker(new URL("./assets/dicom.worker-_n6H46nx.js", import.meta.url), { type: "module" }));
683
+ }
684
+ loadSeries(t, e = {}) {
685
+ var o;
686
+ if (this.disposed)
687
+ return Promise.reject(new Error("DicomWorkerLoader has been disposed"));
688
+ if (this.activeRequest)
689
+ return Promise.reject(new Error("DicomWorkerLoader is already loading a series"));
690
+ if (t.dicomFiles.length === 0)
691
+ return Promise.reject(new Error("Cannot load an empty DICOM series"));
692
+ if ((o = e.signal) != null && o.aborted)
693
+ return Promise.reject(ee());
694
+ const n = this.getWorker(), r = this.nextRequestId++;
695
+ return new Promise((s, l) => {
696
+ const c = {
697
+ requestId: r,
698
+ resolve: s,
699
+ reject: l,
700
+ onProgress: e.onProgress,
701
+ signal: e.signal
702
+ };
703
+ e.signal && (c.abortHandler = () => this.abortActiveRequest(), e.signal.addEventListener("abort", c.abortHandler, { once: !0 })), this.activeRequest = c;
704
+ const m = {
705
+ type: "load",
706
+ requestId: r,
707
+ files: t.dicomFiles
708
+ };
709
+ try {
710
+ n.postMessage(m);
711
+ } catch (d) {
712
+ this.clearActiveRequest(), l(d instanceof Error ? d : new Error(String(d)));
713
+ }
714
+ });
715
+ }
716
+ dispose() {
717
+ this.disposed || (this.disposed = !0, this.rejectActiveRequest(new Error("DicomWorkerLoader has been disposed")), this.terminateWorker());
718
+ }
719
+ getWorker() {
720
+ return this.worker || (this.worker = this.workerFactory(), this.worker.addEventListener("message", this.handleMessage), this.worker.addEventListener("error", this.handleWorkerError), this.worker.addEventListener("messageerror", this.handleMessageError)), this.worker;
721
+ }
722
+ abortActiveRequest() {
723
+ this.rejectActiveRequest(ee()), this.terminateWorker();
724
+ }
725
+ rejectActiveRequest(t) {
726
+ const e = this.activeRequest;
727
+ e && (this.clearActiveRequest(), e.reject(t));
728
+ }
729
+ clearActiveRequest() {
730
+ const t = this.activeRequest;
731
+ t != null && t.signal && t.abortHandler && t.signal.removeEventListener("abort", t.abortHandler), this.activeRequest = void 0;
732
+ }
733
+ terminateWorker() {
734
+ this.worker && (this.worker.removeEventListener("message", this.handleMessage), this.worker.removeEventListener("error", this.handleWorkerError), this.worker.removeEventListener("messageerror", this.handleMessageError), this.worker.terminate(), this.worker = void 0);
735
+ }
736
+ }
737
+ const Ie = /* @__PURE__ */ new Map([
738
+ ["8_false_1", { format: u.RedIntegerFormat, internalFormat: "R8UI", textureType: u.UnsignedByteType }],
739
+ ["8_true_1", { format: u.RedIntegerFormat, internalFormat: "R8I", textureType: u.ByteType }],
740
+ ["8_false_3", { format: u.RGBIntegerFormat, internalFormat: "RGB8UI", textureType: u.UnsignedByteType }],
741
+ ["8_true_3", { format: u.RGBIntegerFormat, internalFormat: "RGB8I", textureType: u.ByteType }],
742
+ ["16_false_1", { format: u.RedIntegerFormat, internalFormat: "R16UI", textureType: u.UnsignedShortType }],
743
+ ["16_true_1", { format: u.RedIntegerFormat, internalFormat: "R16I", textureType: u.ShortType }],
744
+ ["16_false_3", { format: u.RGBIntegerFormat, internalFormat: "RGB16UI", textureType: u.UnsignedShortType }],
745
+ ["16_true_3", { format: u.RGBIntegerFormat, internalFormat: "RGB16I", textureType: u.ShortType }],
746
+ ["32_false_1", { format: u.RedFormat, internalFormat: "R32F", textureType: u.FloatType }],
747
+ ["32_true_1", { format: u.RedFormat, internalFormat: "R32F", textureType: u.FloatType }]
748
+ ]);
749
+ class Ee {
750
+ constructor(t) {
751
+ a(this, "_data3DTexture");
752
+ this.stack = t;
753
+ }
754
+ get data3DTexture() {
755
+ if (this._data3DTexture)
756
+ return this._data3DTexture;
757
+ const { pixelData: t, columns: e, rows: n, numberOfFrames: r, bitsAllocated: o, signed: s, samplesPerPixel: l } = this.stack, { format: c, internalFormat: m, textureType: d } = Ie.get(`${o}_${s}_${l}`) ?? {
758
+ format: u.RedIntegerFormat,
759
+ internalFormat: "R16UI",
760
+ textureType: u.UnsignedShortType
761
+ };
762
+ return this._data3DTexture = new u.Data3DTexture(t, e, n, r), this._data3DTexture.format = c, this._data3DTexture.internalFormat = m, this._data3DTexture.type = d, this._data3DTexture.minFilter = u.NearestFilter, this._data3DTexture.magFilter = u.NearestFilter, this._data3DTexture.unpackAlignment = 1, this._data3DTexture.needsUpdate = !0, this._data3DTexture;
763
+ }
764
+ dispose() {
765
+ const t = this._data3DTexture;
766
+ this._data3DTexture = void 0, t == null || t.dispose();
767
+ }
768
+ }
769
+ function Fe(i, t) {
770
+ switch (i) {
771
+ case 8:
772
+ return t ? Int8Array : Uint8Array;
773
+ case 12:
774
+ case 16:
775
+ return t ? Int16Array : Uint16Array;
776
+ case 32:
777
+ return Float32Array;
778
+ default:
779
+ throw new Error(`Unsupported bitsAllocated: ${i}`);
780
+ }
781
+ }
782
+ async function De(i, t, e, n) {
783
+ const { rows: r, columns: o, numberOfFrames: s, bitsAllocated: l, samplesPerPixel: c, signed: m } = t, d = Fe(l, m), f = new d(r * o * c * s);
784
+ let g = 0, v = 0;
785
+ for await (const w of i) {
786
+ e == null || e(w, v);
787
+ const { imageFrame: y } = await w.extractPixelData(), b = w.numberOfFrames ?? 1, P = r * o * c * b;
788
+ if (y.byteLength < P * d.BYTES_PER_ELEMENT)
789
+ throw new Error(`Pixel data length mismatch: expected ${P}, got ${y.length}`);
790
+ const I = new d(y.buffer, y.byteOffset, P);
791
+ f.set(I, g), g += I.length;
792
+ }
793
+ if (g !== f.length)
794
+ throw new Error(`Pixel data length mismatch: expected ${f.length}, got ${g}`);
795
+ return f;
796
+ }
797
+ const N = 1e-3, ue = 1e-4;
798
+ function Ce(i, t) {
799
+ const e = i.numberOfFrames ?? 1;
800
+ return Array.from({ length: e }, (n, r) => {
801
+ var o;
802
+ return {
803
+ sourceIndex: t,
804
+ frameIndex: r,
805
+ sourceFrameCount: e,
806
+ perFramePosition: i.hasPerFrameImagePosition(r),
807
+ id: `${i.sopInstanceUID() ?? ""}:${String(r).padStart(10, "0")}`,
808
+ seriesUID: i.seriesInstanceUID,
809
+ referenceUID: i.frameOfReferenceUID,
810
+ stackId: i.stackId(r),
811
+ temporalPosition: i.temporalPosition(r),
812
+ frameTime: i.frameTime,
813
+ instanceNumber: i.instanceNumber(r),
814
+ sliceLocation: i.rawHeader.floatString("x00201041"),
815
+ imagePosition: i.imagePosition(r),
816
+ imageOrientation: i.imageOrientation(r),
817
+ pixelSpacing: i.pixelSpacing(r),
818
+ sliceThickness: i.sliceThickness(r),
819
+ spacingBetweenSlices: i.spacingBetweenSlices(r),
820
+ windowWidth: i.windowWidth(r) ?? 300,
821
+ windowCenter: i.windowCenter(r) ?? 50,
822
+ rescaleSlope: i.rescaleSlope(r) ?? 1,
823
+ rescaleIntercept: i.rescaleIntercept(r) ?? 0,
824
+ modality: (o = i.modality) == null ? void 0 : o.toUpperCase(),
825
+ distanceSourceToDetector: i.distanceSourceToDetector,
826
+ distanceSourceToPatient: i.distanceSourceToPatient,
827
+ positionerPrimaryAngle: i.positionerPrimaryAngle,
828
+ positionerSecondaryAngle: i.positionerSecondaryAngle
829
+ };
830
+ });
831
+ }
832
+ function Me(i, t) {
833
+ return Math.abs(i - t) <= 1e-6 + ue * Math.max(Math.abs(i), Math.abs(t));
834
+ }
835
+ function _(i) {
836
+ throw new Error(`${i}; a regular 3D texture cannot represent this series. Split the series or resample it before loading`);
837
+ }
838
+ function Re(i) {
839
+ if (!i.length) throw new Error("No DICOM frames provided");
840
+ const t = j(i, !1), e = i.reduce((h, p) => h.id < p.id ? h : p);
841
+ for (const h of ["seriesUID", "referenceUID", "stackId", "modality"])
842
+ new Set(i.map((p) => p[h]).filter((p) => p != null)).size > 1 && _(`Inconsistent ${h} in series`), i.some((p) => p[h] != null) && i.some((p) => p[h] == null) && _(`Incomplete ${h} in series`);
843
+ for (const h of ["imagePosition", "imageOrientation", "pixelSpacing"])
844
+ i.some((p) => p[h] != null) && i.some((p) => p[h] == null) && _("Incomplete spatial metadata in part of the series");
845
+ const n = /* @__PURE__ */ new Set();
846
+ for (const h of i) {
847
+ if (!h.id.startsWith(":") && n.has(h.id) && _("Duplicate SOP instance/frame"), n.add(h.id), h.temporalPosition != null && (!Number.isSafeInteger(h.temporalPosition) || h.temporalPosition < 1)) throw new Error("Invalid temporal position");
848
+ if (h.imagePosition && (h.imagePosition.length !== 3 || !h.imagePosition.every(Number.isFinite))) throw new Error("Invalid ImagePositionPatient");
849
+ if (h.imageOrientation && A(h.imageOrientation), h.pixelSpacing && (h.pixelSpacing.length !== 2 || !h.pixelSpacing.every((p) => Number.isFinite(p) && p > 0))) throw new Error("Invalid PixelSpacing");
850
+ if (h.sliceThickness != null && (!Number.isFinite(h.sliceThickness) || h.sliceThickness <= 0)) throw new Error("Invalid SliceThickness");
851
+ if (h.spacingBetweenSlices != null && (!Number.isFinite(h.spacingBetweenSlices) || h.spacingBetweenSlices === 0)) throw new Error("Invalid SpacingBetweenSlices");
852
+ (!Number.isFinite(h.rescaleSlope) || !Number.isFinite(h.rescaleIntercept) || h.rescaleSlope !== e.rescaleSlope || h.rescaleIntercept !== e.rescaleIntercept) && _("Varying or invalid rescale parameters");
853
+ }
854
+ const r = i.map((h) => !!(h.imagePosition && h.imageOrientation && h.pixelSpacing));
855
+ r.some(Boolean) && !r.every(Boolean) && _("Incomplete spatial metadata in part of the series");
856
+ const o = e.modality === "XA", s = new Set(i.map((h) => h.temporalPosition).filter((h) => h != null)), l = s.size > 1 || i.some((h) => (h.frameTime ?? 0) > 0), c = !!e.imagePosition && i.every((h) => h.imagePosition && Math.hypot(...h.imagePosition.map((p, S) => p - e.imagePosition[S])) <= N), m = i.length > 1 && c && i.every((h) => h.sourceFrameCount > 1 && !h.perFramePosition), d = !o && r.every(Boolean) && !m && !(l && c);
857
+ s.size > 1 && d && i.length > 1 && _("Mixed spatial and temporal dimensions");
858
+ const f = e.imageOrientation ? A(e.imageOrientation) : [1, 0, 0, 0, 1, 0], g = e.pixelSpacing ?? [1, 1];
859
+ for (const h of i)
860
+ h.imageOrientation && A(h.imageOrientation).some((p, S) => Math.abs(p - f[S]) > R) && _("Inconsistent image orientations"), h.pixelSpacing && h.pixelSpacing.some((p, S) => !Me(p, g[S])) && _("Inconsistent pixel spacing"), o && ["distanceSourceToDetector", "distanceSourceToPatient", "positionerPrimaryAngle", "positionerSecondaryAngle"].some((p) => h[p] !== e[p]) && _("Varying XA detector geometry");
861
+ const v = d ? j(i) : t, w = v[0];
862
+ let y, b = w.spacingBetweenSlices ?? void 0;
863
+ if (d) {
864
+ const h = ce(f);
865
+ if (i.length > 1) {
866
+ const p = w.imagePosition, S = v[v.length - 1].imagePosition;
867
+ y = p.map((E, L) => (S[L] - E) / (i.length - 1)), b = W(y, h), b <= N && _("Duplicate or coplanar slice positions");
868
+ const D = Math.max(N, Math.hypot(...y) * ue);
869
+ for (let E = 1; E < v.length; E++) {
870
+ const L = v[E].imagePosition;
871
+ W(L, h) - W(v[E - 1].imagePosition, h) <= N && _("Duplicate or coplanar slice positions"), Math.hypot(...L.map((ye, J) => ye - p[J] - E * y[J])) > D && _("Irregular slice positions");
872
+ }
873
+ } else {
874
+ const p = b ?? w.sliceThickness ?? 1;
875
+ y = h.map((S) => S * p);
876
+ }
877
+ } else
878
+ y = [0, 0, 0];
879
+ const P = {
880
+ imageOrientation: f,
881
+ imagePosition: [...w.imagePosition ?? [0, 0, 0]],
882
+ pixelSpacing: [...g],
883
+ sliceThickness: w.sliceThickness ?? 1,
884
+ spacingBetweenSlices: b,
885
+ sliceStep: y,
886
+ frameAxis: d ? "space" : "sequence",
887
+ windowWidth: w.windowWidth,
888
+ windowCenter: w.windowCenter,
889
+ rescaleSlope: w.rescaleSlope,
890
+ rescaleIntercept: w.rescaleIntercept,
891
+ modality: w.modality,
892
+ distanceSourceToDetector: w.distanceSourceToDetector,
893
+ distanceSourceToPatient: w.distanceSourceToPatient,
894
+ positionerPrimaryAngle: w.positionerPrimaryAngle,
895
+ positionerSecondaryAngle: w.positionerSecondaryAngle
896
+ }, I = new Map(i.map((h, p) => [h, p]));
897
+ return { geometry: P, order: v.map((h) => I.get(h)) };
898
+ }
899
+ function Ae(i, t, e) {
900
+ if (t.every((o, s) => o === s)) return;
901
+ const n = i.slice(0, e), r = new Uint8Array(t.length);
902
+ for (let o = 0; o < t.length; o++) {
903
+ if (r[o] || t[o] === o) continue;
904
+ n.set(i.subarray(o * e, (o + 1) * e));
905
+ let s = o;
906
+ for (; t[s] !== o; ) {
907
+ const l = t[s];
908
+ i.copyWithin(s * e, l * e, (l + 1) * e), r[s] = 1, s = l;
909
+ }
910
+ i.set(n, s * e), r[s] = 1;
911
+ }
912
+ }
913
+ async function Oe(i, t, e) {
914
+ const n = [], r = await De(i, t, (l, c) => {
915
+ for (const m of Ce(l, c)) n.push(m);
916
+ }), { geometry: o, order: s } = Re(n);
917
+ return Ae(r, s, t.rows * t.columns * t.samplesPerPixel), { ...t, ...o, pixelData: r };
918
+ }
919
+ function Ve(i) {
920
+ if (i.length === 0)
921
+ throw new Error("No DICOM parsers provided");
922
+ const t = i[0], e = t.rows ?? -1, n = t.columns ?? -1, r = t.pixelRepresentation === 1, o = t.bitsAllocated ?? 16, s = t.samplesPerPixel ?? 1;
923
+ if (!Number.isSafeInteger(e) || !Number.isSafeInteger(n) || e <= 0 || n <= 0)
924
+ throw new Error(`Invalid DICOM dimensions: rows=${e}, columns=${n}`);
925
+ for (const l of i) {
926
+ if (!Number.isSafeInteger(l.numberOfFrames ?? 1) || (l.numberOfFrames ?? 1) <= 0)
927
+ throw new Error("Invalid number of frames");
928
+ if (l.rows !== e || l.columns !== n)
929
+ throw new Error("Inconsistent image dimensions in series");
930
+ if (l.bitsAllocated !== o)
931
+ throw new Error("Inconsistent bits per pixel in series");
932
+ if (l.pixelRepresentation !== (r ? 1 : 0))
933
+ throw new Error("Inconsistent pixel signedness in series");
934
+ if (l.samplesPerPixel !== s)
935
+ throw new Error("Inconsistent samples per pixel in series");
936
+ }
937
+ return {
938
+ rows: e,
939
+ columns: n,
940
+ numberOfFrames: i.reduce((l, c) => l + (c.numberOfFrames ?? 1), 0),
941
+ signed: r,
942
+ bitsAllocated: o,
943
+ samplesPerPixel: s
944
+ };
945
+ }
946
+ class X {
947
+ constructor(t, e) {
948
+ a(this, "rows");
949
+ a(this, "columns");
950
+ a(this, "numberOfFrames");
951
+ a(this, "bitsAllocated");
952
+ a(this, "signed");
953
+ a(this, "bytesPerPixel");
954
+ a(this, "samplesPerPixel");
955
+ a(this, "pixelData");
956
+ a(this, "windowWidth");
957
+ a(this, "windowCenter");
958
+ a(this, "rescaleSlope");
959
+ a(this, "rescaleIntercept");
960
+ a(this, "textureFactory");
961
+ a(this, "imageOrientation", [1, 0, 0, 0, 1, 0]);
962
+ a(this, "imagePosition", [0, 0, 0]);
963
+ a(this, "pixelSpacing");
964
+ a(this, "sliceThickness");
965
+ a(this, "spacingBetweenSlices");
966
+ a(this, "sliceStep");
967
+ a(this, "frameAxis");
968
+ a(this, "modality");
969
+ a(this, "distanceSourceToDetector");
970
+ a(this, "distanceSourceToPatient");
971
+ a(this, "positionerPrimaryAngle");
972
+ a(this, "positionerSecondaryAngle");
973
+ a(this, "ijk2lps", new u.Matrix4());
974
+ a(this, "lps2ijk", null);
975
+ a(this, "spatialRank", 3);
976
+ var f, g;
977
+ this.parsers = t;
978
+ const { rows: n, bitsAllocated: r, columns: o, numberOfFrames: s, signed: l, samplesPerPixel: c } = e, m = n * o * s * c;
979
+ if (e.pixelData.length !== m)
980
+ throw new Error(`Pixel data length mismatch: expected ${m}, got ${e.pixelData.length}`);
981
+ if (this.rows = n, this.columns = o, this.numberOfFrames = s, this.bitsAllocated = r, this.signed = l, this.bytesPerPixel = Math.ceil(r / 8), this.samplesPerPixel = c, this.pixelData = e.pixelData, this.windowWidth = e.windowWidth, this.windowCenter = e.windowCenter, this.rescaleSlope = e.rescaleSlope, this.rescaleIntercept = e.rescaleIntercept, this.imageOrientation = e.imageOrientation, this.imagePosition = e.imagePosition, this.pixelSpacing = e.pixelSpacing, this.sliceThickness = e.sliceThickness, this.spacingBetweenSlices = e.spacingBetweenSlices, this.frameAxis = ((f = e.modality) == null ? void 0 : f.toUpperCase()) === "XA" ? "sequence" : e.frameAxis ?? "space", e.frameAxis !== void 0 && e.frameAxis !== "space" && e.frameAxis !== "sequence") throw new Error("Invalid frameAxis");
982
+ if (e.spacingBetweenSlices !== void 0 && (!Number.isFinite(e.spacingBetweenSlices) || e.spacingBetweenSlices === 0)) throw new Error("Invalid spacingBetweenSlices");
983
+ if (e.sliceStep !== void 0 && (e.sliceStep.length !== 3 || !e.sliceStep.every(Number.isFinite))) throw new Error("Invalid sliceStep");
984
+ const d = new u.Vector3().crossVectors(new u.Vector3(...this.imageOrientation.slice(0, 3)), new u.Vector3(...this.imageOrientation.slice(3)));
985
+ if (this.sliceStep = this.frameAxis === "sequence" ? [0, 0, 0] : e.sliceStep ? [...e.sliceStep] : d.multiplyScalar(e.spacingBetweenSlices ?? e.sliceThickness).toArray(), !this.sliceStep.every(Number.isFinite)) throw new Error("Invalid sliceStep");
986
+ if (e.sliceStep && this.frameAxis === "space" && d.dot(new u.Vector3(...this.sliceStep)) === 0)
987
+ throw new Error("Spatial sliceStep must have a nonzero component along the slice normal");
988
+ switch (this.modality = e.modality, this.distanceSourceToDetector = e.distanceSourceToDetector, this.distanceSourceToPatient = e.distanceSourceToPatient, this.positionerPrimaryAngle = e.positionerPrimaryAngle, this.positionerSecondaryAngle = e.positionerSecondaryAngle, (g = this.modality) == null ? void 0 : g.toUpperCase()) {
989
+ case "XA":
990
+ this._computeAngioMath();
991
+ break;
992
+ default:
993
+ this._computeDefaultMath();
994
+ }
995
+ this.textureFactory = new Ee(this);
996
+ }
997
+ static async create(t) {
998
+ const e = Ve(t);
999
+ return new X([...t], await Oe(t, e));
1000
+ }
1001
+ static fromData(t) {
1002
+ return new X([], t);
1003
+ }
1004
+ hasSpatialVolume() {
1005
+ return this.spatialRank === 3 && this.lps2ijk !== null;
1006
+ }
1007
+ voxelToLps(t, e, n) {
1008
+ return new u.Vector3(t, e, n).applyMatrix4(this.ijk2lps);
1009
+ }
1010
+ lpsToVoxel(t) {
1011
+ if (!this.lps2ijk)
1012
+ throw new Error("Stack geometry is not invertible");
1013
+ return t.clone().applyMatrix4(this.lps2ijk);
1014
+ }
1015
+ _computeAngioMath() {
1016
+ const t = this.distanceSourceToDetector ?? 1e3, e = this.distanceSourceToPatient ?? 500, n = t - e, r = (this.positionerPrimaryAngle ?? 0) * Math.PI / 180, o = (this.positionerSecondaryAngle ?? 0) * Math.PI / 180, s = Math.cos(r), l = Math.sin(r), c = Math.cos(o), m = Math.sin(o), d = new u.Matrix3().set(s, -l * c, -l * m, l, s * c, s * m, 0, -m, c), [f, g] = this.pixelSpacing, v = this.rows, w = this.columns, y = new u.Vector3(g, 0, 0), b = new u.Vector3(0, 0, -f), P = new u.Vector3(
1017
+ (-w / 2 + 0.5) * g,
1018
+ -n,
1019
+ (v / 2 - 0.5) * f
1020
+ ), I = y.clone().applyMatrix3(d), h = b.clone().applyMatrix3(d), p = P.clone().applyMatrix3(d);
1021
+ this.ijk2lps.makeBasis(I, h, new u.Vector3()).setPosition(p), this.lps2ijk = null, this.spatialRank = 2;
1022
+ const S = I.clone().normalize(), D = h.clone().normalize();
1023
+ this.imageOrientation = [S.x, S.y, S.z, D.x, D.y, D.z], this.imagePosition = [p.x, p.y, p.z];
1024
+ }
1025
+ _computeDefaultMath() {
1026
+ const t = new u.Vector3(this.imageOrientation[0], this.imageOrientation[1], this.imageOrientation[2]), e = new u.Vector3(this.imageOrientation[3], this.imageOrientation[4], this.imageOrientation[5]), n = this.pixelSpacing[0], r = this.pixelSpacing[1];
1027
+ this.ijk2lps.makeBasis(
1028
+ t.clone().multiplyScalar(r),
1029
+ e.clone().multiplyScalar(n),
1030
+ new u.Vector3(...this.sliceStep)
1031
+ ).setPosition(new u.Vector3(this.imagePosition[0], this.imagePosition[1], this.imagePosition[2]));
1032
+ const o = this.ijk2lps.determinant();
1033
+ if (!Number.isFinite(o) || o === 0) {
1034
+ this.lps2ijk = null, this.spatialRank = 2;
1035
+ return;
1036
+ }
1037
+ this.lps2ijk = this.ijk2lps.clone().invert(), this.spatialRank = this.lps2ijk.elements.every(Number.isFinite) ? 3 : 2, this.spatialRank === 2 && (this.lps2ijk = null);
1038
+ }
1039
+ }
1040
+ function z(i) {
1041
+ return new T(i.columns, i.rows, i.numberOfFrames);
1042
+ }
1043
+ function B(i) {
1044
+ return z(i).subScalar(1).multiplyScalar(0.5);
1045
+ }
1046
+ function Ue(i) {
1047
+ return new be(new T(-0.5, -0.5, -0.5), z(i).subScalar(0.5));
1048
+ }
1049
+ function he(i) {
1050
+ const { min: t, max: e } = Ue(i);
1051
+ return [
1052
+ new T(t.x, t.y, t.z),
1053
+ new T(e.x, t.y, t.z),
1054
+ new T(e.x, e.y, t.z),
1055
+ new T(t.x, e.y, t.z),
1056
+ new T(t.x, t.y, e.z),
1057
+ new T(e.x, t.y, e.z),
1058
+ new T(e.x, e.y, e.z),
1059
+ new T(t.x, e.y, e.z)
1060
+ ];
1061
+ }
1062
+ function me(i) {
1063
+ if (i !== "data" && i !== "lps")
1064
+ throw new Error(`Unsupported slice plane space: ${i}; expected data or lps`);
1065
+ }
1066
+ function k(i, t) {
1067
+ if (!i || ![i.x, i.y, i.z].every(Number.isFinite))
1068
+ throw new Error(`Slice plane ${t} must have finite components`);
1069
+ }
1070
+ function de(i) {
1071
+ k(i, "normal");
1072
+ const t = Math.max(Math.abs(i.x), Math.abs(i.y), Math.abs(i.z));
1073
+ if (t === 0) throw new Error("Slice plane normal must be non-zero");
1074
+ return new T(i.x / t, i.y / t, i.z / t).normalize();
1075
+ }
1076
+ function pe(i) {
1077
+ const t = i.lps2ijk;
1078
+ if (!t || !t.elements.every(Number.isFinite) || !i.ijk2lps.elements.every(Number.isFinite) || i.ijk2lps.determinant() === 0)
1079
+ throw new Error("LPS slice planes require an invertible stack geometry");
1080
+ return t;
1081
+ }
1082
+ function Y(i) {
1083
+ if (!i) throw new Error("Slice plane is required");
1084
+ const t = i.space === void 0 ? "data" : i.space;
1085
+ return me(t), k(i.origin, "origin"), { origin: i.origin.clone(), normal: de(i.normal), space: t };
1086
+ }
1087
+ function q(i, t, e) {
1088
+ me(e);
1089
+ const n = Y(t), r = n.space === "lps" || e === "lps" ? pe(i) : null;
1090
+ if (n.space === e) return n;
1091
+ const o = e === "lps" ? i.ijk2lps : r, s = new Pe().setFromMatrix4(e === "lps" ? r : i.ijk2lps).transpose();
1092
+ return n.origin.applyMatrix4(o), k(n.origin, "origin"), { origin: n.origin, normal: de(n.normal.applyMatrix3(s)), space: e };
1093
+ }
1094
+ function ot(i, t) {
1095
+ if (!Number.isFinite(t)) throw new Error(`Slice plane offset must be finite, got ${t}`);
1096
+ const e = Y(i);
1097
+ return e.origin.addScaledVector(e.normal, t), k(e.origin, "origin"), e;
1098
+ }
1099
+ function st(i, t) {
1100
+ const e = Y(t);
1101
+ if (![i.columns, i.rows, i.numberOfFrames].every((o) => Number.isSafeInteger(o) && o > 0))
1102
+ throw new Error("Slice stack dimensions must be positive integers");
1103
+ e.space === "lps" && pe(i);
1104
+ let n = 1 / 0, r = -1 / 0;
1105
+ for (const o of he(i)) {
1106
+ e.space === "lps" && o.applyMatrix4(i.ijk2lps);
1107
+ const s = o.sub(e.origin).dot(e.normal);
1108
+ if (!Number.isFinite(s)) throw new Error("Slice offset range exceeds the finite numeric range");
1109
+ n = Math.min(n, s), r = Math.max(r, s);
1110
+ }
1111
+ return { min: n, max: r, space: e.space, unit: e.space === "lps" ? "mm" : "data" };
1112
+ }
1113
+ var ze = `in vec3 position;
1114
+
1115
+ uniform mat4 modelViewMatrix;
1116
+ uniform mat4 projectionMatrix;
1117
+
1118
+ out vec3 vDataPosition;
1119
+
1120
+ void main() {
1121
+ vDataPosition = position;
1122
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1123
+ }`;
1124
+ const Z = `
1125
+ vec3 dataToTexture(vec3 dataPosition, vec3 size) {
1126
+ return (dataPosition + vec3(0.5)) / size;
1127
+ }
1128
+
1129
+ ivec3 nearestVoxelIndex(vec3 dataPosition, vec3 size) {
1130
+ return ivec3(clamp(floor(dataPosition + vec3(0.5)), vec3(0.0), size - vec3(1.0)));
1131
+ }
1132
+ `;
1133
+ function $(i) {
1134
+ return Number.isFinite(i) && Number.isFinite(Math.fround(i));
1135
+ }
1136
+ function fe(i) {
1137
+ if (i.samplesPerPixel !== 1)
1138
+ throw new Error("Slices support scalar data only (samplesPerPixel=1); RGB is not supported");
1139
+ const t = i.bitsAllocated === 8 ? i.signed ? Int8Array : Uint8Array : i.bitsAllocated === 16 ? i.signed ? Int16Array : Uint16Array : i.bitsAllocated === 32 ? Float32Array : void 0;
1140
+ if (!t)
1141
+ throw new Error(`Unsupported slice bitsAllocated: ${i.bitsAllocated}; expected 8, 16 or 32`);
1142
+ if (!(i.pixelData instanceof t))
1143
+ throw new Error(`Slice pixelData must be ${t.name} for this stack format`);
1144
+ if (![i.columns, i.rows, i.numberOfFrames].every((e) => Number.isSafeInteger(e) && e > 0))
1145
+ throw new Error("Slice stack dimensions must be positive integers");
1146
+ if (!i.ijk2lps.elements.every(Number.isFinite))
1147
+ throw new Error("Slice stack geometry must be finite");
1148
+ ge(i);
1149
+ }
1150
+ function ge(i) {
1151
+ if (!$(i.rescaleSlope) || Math.fround(i.rescaleSlope) === 0 || !$(i.rescaleIntercept))
1152
+ throw new Error("Slice rescaleSlope must be finite and non-zero; rescaleIntercept must be finite (Float32 range)");
1153
+ }
1154
+ function V(i, t, e) {
1155
+ if (!$(t) || !$(e) || !(Math.fround(e) > 0))
1156
+ throw new Error(`Slice window must be finite with positive width (Float32 range), got center=${t}, width=${e}`);
1157
+ return ge(i), {
1158
+ uWindowCenter: { value: t },
1159
+ uWindowWidth: { value: e },
1160
+ uRescaleSlope: { value: i.rescaleSlope },
1161
+ uRescaleIntercept: { value: i.rescaleIntercept }
1162
+ };
1163
+ }
1164
+ const we = `
1165
+ uniform float uWindowCenter;
1166
+ uniform float uWindowWidth;
1167
+ uniform float uRescaleSlope;
1168
+ uniform float uRescaleIntercept;
1169
+
1170
+ float windowRawValue(float rawValue) {
1171
+ float value = rawValue * uRescaleSlope + uRescaleIntercept;
1172
+ return clamp((value - uWindowCenter) / uWindowWidth + 0.5, 0.0, 1.0);
1173
+ }
1174
+ `, te = {
1175
+ R8I: { samplerType: "isampler3D", texelType: "ivec4" },
1176
+ R8UI: { samplerType: "usampler3D", texelType: "uvec4" },
1177
+ R16I: { samplerType: "isampler3D", texelType: "ivec4" },
1178
+ R16UI: { samplerType: "usampler3D", texelType: "uvec4" },
1179
+ R32F: { samplerType: "sampler3D", texelType: "vec4" }
1180
+ };
1181
+ function Le(i) {
1182
+ const t = te[i];
1183
+ if (!Object.prototype.hasOwnProperty.call(te, i))
1184
+ throw new Error(`Unsupported oblique slice texture internalFormat: ${i}`);
1185
+ return `
1186
+ precision highp float;
1187
+ precision highp int;
1188
+ precision highp ${t.samplerType};
1189
+
1190
+ uniform ${t.samplerType} map;
1191
+ uniform vec3 uSize;
1192
+
1193
+ in vec3 vDataPosition;
1194
+ out vec4 fragColor;
1195
+
1196
+ ${Z}
1197
+ ${we}
1198
+
1199
+ void main() {
1200
+ vec3 minPosition = vec3(-0.5);
1201
+ vec3 maxPosition = uSize - vec3(0.5);
1202
+
1203
+ // Allow interpolation roundoff at a face, but discard genuinely external positions.
1204
+ const float boundaryTolerance = 0.00001;
1205
+ if (any(lessThan(vDataPosition, minPosition - vec3(boundaryTolerance))) ||
1206
+ any(greaterThan(vDataPosition, maxPosition + vec3(boundaryTolerance)))) {
1207
+ discard;
1208
+ }
1209
+
1210
+ ivec3 index = nearestVoxelIndex(vDataPosition, uSize);
1211
+ ${t.texelType} texel = texelFetch(map, index, 0);
1212
+ float pixelValue = windowRawValue(float(texel.r));
1213
+
1214
+ fragColor = vec4(pixelValue, pixelValue, pixelValue, 1.0);
1215
+ }
1216
+ `;
1217
+ }
1218
+ function U(i) {
1219
+ let t = !1, e;
1220
+ for (const n of i)
1221
+ try {
1222
+ n();
1223
+ } catch (r) {
1224
+ t || (e = r), t = !0;
1225
+ }
1226
+ if (t) throw e;
1227
+ }
1228
+ function x(i, t) {
1229
+ if (i.isDisposed) throw new Error(`${t} has been disposed`);
1230
+ }
1231
+ const C = 1e-6, M = 6, G = [0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7];
1232
+ class Ne {
1233
+ constructor(t) {
1234
+ a(this, "corners");
1235
+ a(this, "distances", new Float64Array(8));
1236
+ a(this, "pool", Array.from({ length: 20 }, () => new u.Vector3()));
1237
+ a(this, "points", []);
1238
+ a(this, "candidate", new u.Vector3());
1239
+ a(this, "center", new u.Vector3());
1240
+ a(this, "u", new u.Vector3());
1241
+ a(this, "v", new u.Vector3());
1242
+ a(this, "left", new u.Vector3());
1243
+ a(this, "right", new u.Vector3());
1244
+ this.corners = he(t);
1245
+ }
1246
+ intersect(t) {
1247
+ const { origin: e, normal: n } = t, { points: r, corners: o, distances: s } = this;
1248
+ r.length = 0;
1249
+ for (let c = 0; c < o.length; c++) {
1250
+ const m = this.candidate.subVectors(o[c], e).dot(n);
1251
+ if (!Number.isFinite(m)) throw new Error("Oblique slice plane distance exceeds the finite numeric range");
1252
+ s[c] = Math.abs(m) <= C ? 0 : m;
1253
+ }
1254
+ for (let c = 0; c < G.length; c += 2) {
1255
+ const m = G[c], d = G[c + 1], f = s[m], g = s[d];
1256
+ f === 0 && this.pushUnique(o[m]), g === 0 && this.pushUnique(o[d]), (f < 0 && g > 0 || f > 0 && g < 0) && this.pushUnique(this.candidate.copy(o[m]).lerp(o[d], f / (f - g)));
1257
+ }
1258
+ if (r.length < 3)
1259
+ return r.length = 0, r;
1260
+ this.center.set(0, 0, 0);
1261
+ for (const c of r) this.center.add(c);
1262
+ this.center.multiplyScalar(1 / r.length), this.candidate.set(0, Math.abs(n.z) < 0.9 ? 0 : 1, Math.abs(n.z) < 0.9 ? 1 : 0), this.u.crossVectors(this.candidate, n).normalize(), this.v.crossVectors(n, this.u).normalize(), r.sort((c, m) => this.angle(c) - this.angle(m));
1263
+ let l = 0;
1264
+ for (let c = 1; c < r.length - 1; c++)
1265
+ l += this.left.subVectors(r[c], r[0]).cross(this.right.subVectors(r[c + 1], r[0])).dot(n);
1266
+ if (l <= C * C)
1267
+ return r.length = 0, r;
1268
+ if (r.length > M) throw new Error("Oblique slice intersection exceeds the six-vertex capacity");
1269
+ for (const c of r)
1270
+ if (!Number.isFinite(Math.fround(c.x)) || !Number.isFinite(Math.fround(c.y)) || !Number.isFinite(Math.fround(c.z)))
1271
+ throw new Error("Oblique slice intersection exceeds the Float32 geometry range");
1272
+ return r;
1273
+ }
1274
+ pushUnique(t) {
1275
+ this.points.some((e) => e.distanceToSquared(t) <= C * C) || this.points.push(this.pool[this.points.length].copy(t));
1276
+ }
1277
+ angle(t) {
1278
+ return this.candidate.subVectors(t, this.center), Math.atan2(this.candidate.dot(this.v), this.candidate.dot(this.u));
1279
+ }
1280
+ }
1281
+ class H extends u.BufferGeometry {
1282
+ constructor() {
1283
+ super();
1284
+ a(this, "vertexCount", 0);
1285
+ a(this, "point", new u.Vector3());
1286
+ this.setAttribute("position", new u.BufferAttribute(new Float32Array(M * 3), 3).setUsage(u.DynamicDrawUsage)), this.setAttribute("normal", new u.BufferAttribute(new Float32Array(M * 3), 3).setUsage(u.DynamicDrawUsage)), this.setIndex(new u.BufferAttribute(new Uint16Array((M - 2) * 3), 1).setUsage(u.DynamicDrawUsage)), this.boundingBox = new u.Box3(), this.boundingSphere = new u.Sphere(), this.setDrawRange(0, 0);
1287
+ }
1288
+ update(e, n) {
1289
+ const r = this.getAttribute("position"), o = this.getAttribute("normal"), s = this.getIndex();
1290
+ this.vertexCount = e.length;
1291
+ for (let c = 0; c < M; c++) {
1292
+ const m = e[c] ?? e[0];
1293
+ r.setXYZ(c, (m == null ? void 0 : m.x) ?? 0, (m == null ? void 0 : m.y) ?? 0, (m == null ? void 0 : m.z) ?? 0), o.setXYZ(c, m ? n.x : 0, m ? n.y : 0, m ? n.z : 0);
1294
+ }
1295
+ const l = Math.max(0, e.length - 2) * 3;
1296
+ for (let c = 0; c < s.count; c += 3)
1297
+ s.setX(c, 0), s.setX(c + 1, c < l ? c / 3 + 1 : 0), s.setX(c + 2, c < l ? c / 3 + 2 : 0);
1298
+ this.setDrawRange(0, l), this.computeBoundingBox(), this.computeBoundingSphere(), r.needsUpdate = !0, o.needsUpdate = !0, s.needsUpdate = !0;
1299
+ }
1300
+ computeBoundingBox() {
1301
+ this.boundingBox ?? (this.boundingBox = new u.Box3()), this.boundingBox.makeEmpty();
1302
+ const e = this.getAttribute("position");
1303
+ for (let n = 0; n < this.vertexCount; n++)
1304
+ this.boundingBox.expandByPoint(this.point.fromBufferAttribute(e, n));
1305
+ }
1306
+ computeBoundingSphere() {
1307
+ if (this.boundingSphere ?? (this.boundingSphere = new u.Sphere()), this.boundingSphere.makeEmpty(), this.vertexCount === 0) return;
1308
+ this.computeBoundingBox(), this.boundingBox.getCenter(this.boundingSphere.center);
1309
+ let e = 0;
1310
+ const n = this.getAttribute("position");
1311
+ for (let r = 0; r < this.vertexCount; r++)
1312
+ e = Math.max(e, this.point.fromBufferAttribute(n, r).distanceToSquared(this.boundingSphere.center));
1313
+ this.boundingSphere.radius = Math.sqrt(e);
1314
+ }
1315
+ copy(e) {
1316
+ return super.copy(e), this.vertexCount = e instanceof H ? e.vertexCount : 0, this;
1317
+ }
1318
+ }
1319
+ class at extends u.Object3D {
1320
+ constructor(e, n, r = {}) {
1321
+ super();
1322
+ a(this, "stack");
1323
+ a(this, "texture");
1324
+ a(this, "mesh");
1325
+ a(this, "intersection");
1326
+ a(this, "sliceGeometry");
1327
+ a(this, "_plane");
1328
+ a(this, "_windowCenter");
1329
+ a(this, "_windowWidth");
1330
+ a(this, "_disposed", !1);
1331
+ fe(e), this.stack = e, this._plane = q(e, n, "data"), this._windowCenter = r.windowCenter === void 0 ? e.windowCenter : r.windowCenter, this._windowWidth = r.windowWidth === void 0 ? e.windowWidth : r.windowWidth;
1332
+ const o = V(e, this._windowCenter, this._windowWidth);
1333
+ this.intersection = new Ne(e);
1334
+ const s = this.intersection.intersect(this._plane);
1335
+ this.texture = e.textureFactory.data3DTexture;
1336
+ const l = Le(String(this.texture.internalFormat));
1337
+ this.sliceGeometry = new H(), this.sliceGeometry.update(s, this._plane.normal), this.mesh = new u.Mesh(this.sliceGeometry, this.createMaterial(l, o)), this.add(this.mesh), this.matrixAutoUpdate = !1, this.matrix.copy(e.ijk2lps);
1338
+ }
1339
+ get plane() {
1340
+ return this.getPlane();
1341
+ }
1342
+ set plane(e) {
1343
+ x(this, "ObliqueSlice");
1344
+ const n = q(this.stack, e, "data");
1345
+ if (n.origin.distanceToSquared(this._plane.origin) <= 1e-24 && n.normal.distanceToSquared(this._plane.normal) <= 1e-24) return;
1346
+ const r = this.intersection.intersect(n);
1347
+ this.sliceGeometry.update(r, n.normal), this._plane = n, this.dispatchEvent({ type: "change", reason: "plane" });
1348
+ }
1349
+ /** A tangent at a point/edge, or a plane outside the bounds, has no drawable section. */
1350
+ get hasIntersection() {
1351
+ return !this._disposed && this.vertexCount > 0;
1352
+ }
1353
+ /** Active polygon vertices; position/index attribute counts describe reserved capacity. */
1354
+ get vertexCount() {
1355
+ return this.sliceGeometry.vertexCount;
1356
+ }
1357
+ /** Return an independent plane in data/IJK (default) or patient LPS coordinates. */
1358
+ getPlane(e = "data") {
1359
+ return q(this.stack, this._plane, e);
1360
+ }
1361
+ get windowCenter() {
1362
+ return this._windowCenter;
1363
+ }
1364
+ set windowCenter(e) {
1365
+ this.setWindow(e, this._windowWidth);
1366
+ }
1367
+ get windowWidth() {
1368
+ return this._windowWidth;
1369
+ }
1370
+ set windowWidth(e) {
1371
+ this.setWindow(this._windowCenter, e);
1372
+ }
1373
+ get geometry() {
1374
+ return this.mesh.geometry;
1375
+ }
1376
+ get material() {
1377
+ return this.mesh.material;
1378
+ }
1379
+ setPlane(e) {
1380
+ this.plane = e;
1381
+ }
1382
+ setWindow(e, n) {
1383
+ x(this, "ObliqueSlice");
1384
+ const r = V(this.stack, e, n);
1385
+ if (!(e === this._windowCenter && n === this._windowWidth && Object.entries(r).every(([o, s]) => this.material.uniforms[o].value === s.value))) {
1386
+ this._windowCenter = e, this._windowWidth = n;
1387
+ for (const [o, s] of Object.entries(r))
1388
+ this.material.uniforms[o].value = s.value;
1389
+ this.dispatchEvent({ type: "change", reason: "window" });
1390
+ }
1391
+ }
1392
+ get isDisposed() {
1393
+ return this._disposed;
1394
+ }
1395
+ dispose() {
1396
+ if (this._disposed) return;
1397
+ this._disposed = !0, this.visible = !1;
1398
+ const { geometry: e, material: n } = this.mesh;
1399
+ U([
1400
+ () => this.mesh.removeFromParent(),
1401
+ () => this.removeFromParent(),
1402
+ () => this.clear(),
1403
+ () => e.dispose(),
1404
+ () => n.dispose(),
1405
+ () => this.dispatchEvent({ type: "dispose" })
1406
+ ]);
1407
+ }
1408
+ createMaterial(e, n) {
1409
+ return new u.RawShaderMaterial({
1410
+ glslVersion: u.GLSL3,
1411
+ uniforms: {
1412
+ map: { value: this.texture },
1413
+ uSize: { value: z(this.stack) },
1414
+ ...n
1415
+ },
1416
+ vertexShader: ze,
1417
+ fragmentShader: e,
1418
+ side: u.DoubleSide
1419
+ });
1420
+ }
1421
+ }
1422
+ var We = `in vec3 position;
1423
+
1424
+ uniform mat4 modelViewMatrix;\r
1425
+ uniform mat4 projectionMatrix;
1426
+
1427
+ out vec3 vPosition;
1428
+
1429
+ void main() {\r
1430
+ vPosition = position;\r
1431
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\r
1432
+ }`;
1433
+ const ie = {
1434
+ R8I: { samplerType: "isampler3D", texelType: "ivec4" },
1435
+ R8UI: { samplerType: "usampler3D", texelType: "uvec4" },
1436
+ R16I: { samplerType: "isampler3D", texelType: "ivec4" },
1437
+ R16UI: { samplerType: "usampler3D", texelType: "uvec4" },
1438
+ R32F: { samplerType: "sampler3D", texelType: "vec4" }
1439
+ };
1440
+ function Be(i) {
1441
+ const t = ie[i];
1442
+ if (!Object.prototype.hasOwnProperty.call(ie, i))
1443
+ throw new Error(`Unsupported slice texture internalFormat: ${i}`);
1444
+ const { samplerType: e, texelType: n } = t, r = (o, s) => `
1445
+ precision highp float;
1446
+ precision highp int;
1447
+ precision highp ${e};
1448
+
1449
+ uniform ${e} map;
1450
+ uniform int ${o};
1451
+ uniform vec3 uSize;
1452
+
1453
+ in vec3 vPosition;
1454
+ out vec4 fragColor;
1455
+
1456
+ ${Z}
1457
+ ${we}
1458
+
1459
+ void main() {
1460
+ // Geometry is embedded in IJK; the mesh translates only along the selected axis.
1461
+ vec3 dataPosition = ${s};
1462
+ ivec3 index = nearestVoxelIndex(dataPosition, uSize);
1463
+ ${n} texel = texelFetch(map, index, 0);
1464
+ float pixelValue = windowRawValue(float(texel.r));
1465
+ fragColor = vec4(pixelValue, pixelValue, pixelValue, 1.0);
1466
+ }
1467
+ `;
1468
+ return {
1469
+ fragmentX: r("ix", "vec3(float(ix), vPosition.y, vPosition.z)"),
1470
+ fragmentY: r("iy", "vec3(vPosition.x, float(iy), vPosition.z)"),
1471
+ fragmentZ: r("iz", "vec3(vPosition.x, vPosition.y, float(iz))")
1472
+ };
1473
+ }
1474
+ const ne = {
1475
+ x: {
1476
+ fragment: "fragmentX",
1477
+ indexUniform: "ix",
1478
+ positionComponent: "x",
1479
+ size: (i) => i.columns,
1480
+ defaultIndex: (i) => Math.trunc(i.columns / 2),
1481
+ geometry: (i) => {
1482
+ const t = B(i);
1483
+ return new u.PlaneGeometry(i.numberOfFrames, i.rows).rotateY(-Math.PI / 2).translate(0, t.y, t.z);
1484
+ },
1485
+ uniforms: (i) => ({
1486
+ ix: { value: i }
1487
+ })
1488
+ },
1489
+ y: {
1490
+ fragment: "fragmentY",
1491
+ indexUniform: "iy",
1492
+ positionComponent: "y",
1493
+ size: (i) => i.rows,
1494
+ defaultIndex: (i) => Math.trunc(i.rows / 2),
1495
+ geometry: (i) => {
1496
+ const t = B(i);
1497
+ return new u.PlaneGeometry(i.columns, i.numberOfFrames).rotateX(Math.PI / 2).translate(t.x, 0, t.z);
1498
+ },
1499
+ uniforms: (i) => ({
1500
+ iy: { value: i }
1501
+ })
1502
+ },
1503
+ z: {
1504
+ fragment: "fragmentZ",
1505
+ indexUniform: "iz",
1506
+ positionComponent: "z",
1507
+ size: (i) => i.numberOfFrames,
1508
+ defaultIndex: (i) => Math.trunc(i.numberOfFrames / 2),
1509
+ geometry: (i) => {
1510
+ const t = B(i);
1511
+ return new u.PlaneGeometry(i.columns, i.rows).translate(t.x, t.y, 0);
1512
+ },
1513
+ uniforms: (i) => ({
1514
+ iz: { value: i }
1515
+ })
1516
+ }
1517
+ };
1518
+ class O extends u.Object3D {
1519
+ constructor(e, n, r = {}) {
1520
+ super();
1521
+ a(this, "stack");
1522
+ a(this, "axis");
1523
+ a(this, "texture");
1524
+ a(this, "mesh");
1525
+ a(this, "config");
1526
+ a(this, "_index");
1527
+ a(this, "_windowCenter");
1528
+ a(this, "_windowWidth");
1529
+ a(this, "_disposed", !1);
1530
+ if (!Object.prototype.hasOwnProperty.call(ne, n))
1531
+ throw new Error(`Unsupported slice axis: ${n}; expected x, y or z`);
1532
+ fe(e), this.stack = e, this.axis = n, this.config = ne[n], this._index = r.index === void 0 ? this.config.defaultIndex(e) : r.index, this.validateIndex(this._index), this._windowCenter = r.windowCenter === void 0 ? e.windowCenter : r.windowCenter, this._windowWidth = r.windowWidth === void 0 ? e.windowWidth : r.windowWidth;
1533
+ const o = V(e, this._windowCenter, this._windowWidth);
1534
+ this.texture = e.textureFactory.data3DTexture;
1535
+ const s = Be(String(this.texture.internalFormat));
1536
+ this.mesh = new u.Mesh(this.config.geometry(e), this.createMaterial(s[this.config.fragment], o)), this.add(this.mesh), this.matrixAutoUpdate = !1, this.matrix.copy(e.ijk2lps), this.mesh.position[this.config.positionComponent] = this._index;
1537
+ }
1538
+ static fromAxis(e, n, r, o = {}) {
1539
+ return new O(e, n, { ...o, index: r === void 0 ? o.index : r });
1540
+ }
1541
+ get index() {
1542
+ return this._index;
1543
+ }
1544
+ set index(e) {
1545
+ x(this, "Slice"), this.validateIndex(e), e !== this._index && (this._index = e, this.mesh.material.uniforms[this.config.indexUniform].value = e, this.mesh.position[this.config.positionComponent] = e, this.dispatchEvent({ type: "change", reason: "index" }));
1546
+ }
1547
+ get windowCenter() {
1548
+ return this._windowCenter;
1549
+ }
1550
+ set windowCenter(e) {
1551
+ this.setWindow(e, this._windowWidth);
1552
+ }
1553
+ get windowWidth() {
1554
+ return this._windowWidth;
1555
+ }
1556
+ set windowWidth(e) {
1557
+ this.setWindow(this._windowCenter, e);
1558
+ }
1559
+ get geometry() {
1560
+ return this.mesh.geometry;
1561
+ }
1562
+ get material() {
1563
+ return this.mesh.material;
1564
+ }
1565
+ setWindow(e, n) {
1566
+ x(this, "Slice");
1567
+ const r = V(this.stack, e, n);
1568
+ if (!(e === this._windowCenter && n === this._windowWidth && Object.entries(r).every(([o, s]) => this.material.uniforms[o].value === s.value))) {
1569
+ this._windowCenter = e, this._windowWidth = n;
1570
+ for (const [o, s] of Object.entries(r))
1571
+ this.material.uniforms[o].value = s.value;
1572
+ this.dispatchEvent({ type: "change", reason: "window" });
1573
+ }
1574
+ }
1575
+ get isDisposed() {
1576
+ return this._disposed;
1577
+ }
1578
+ dispose() {
1579
+ if (this._disposed) return;
1580
+ this._disposed = !0, this.visible = !1;
1581
+ const { geometry: e, material: n } = this.mesh;
1582
+ U([
1583
+ () => this.mesh.removeFromParent(),
1584
+ () => this.removeFromParent(),
1585
+ () => this.clear(),
1586
+ () => e.dispose(),
1587
+ () => n.dispose(),
1588
+ () => this.dispatchEvent({ type: "dispose" })
1589
+ ]);
1590
+ }
1591
+ createMaterial(e, n) {
1592
+ return new u.RawShaderMaterial({
1593
+ glslVersion: u.GLSL3,
1594
+ uniforms: {
1595
+ map: { value: this.texture },
1596
+ uSize: { value: z(this.stack) },
1597
+ ...this.config.uniforms(this._index),
1598
+ ...n
1599
+ },
1600
+ vertexShader: We,
1601
+ fragmentShader: e,
1602
+ side: u.DoubleSide
1603
+ });
1604
+ }
1605
+ validateIndex(e) {
1606
+ if (!(Number.isInteger(e) && e >= 0 && e < this.config.size(this.stack)))
1607
+ throw new Error(`Slice index must be an integer in [0, ${this.config.size(this.stack) - 1}], got ${e}`);
1608
+ }
1609
+ }
1610
+ class lt extends u.Object3D {
1611
+ constructor(e) {
1612
+ super();
1613
+ a(this, "stack");
1614
+ a(this, "nx");
1615
+ a(this, "ny");
1616
+ a(this, "nz");
1617
+ a(this, "size");
1618
+ a(this, "lx");
1619
+ a(this, "ly");
1620
+ a(this, "lz");
1621
+ a(this, "hx");
1622
+ a(this, "hy");
1623
+ a(this, "hz");
1624
+ a(this, "sliceX");
1625
+ a(this, "sliceY");
1626
+ a(this, "sliceZ");
1627
+ a(this, "_disposed", !1);
1628
+ a(this, "windowUpdateDepth", 0);
1629
+ a(this, "windowChanged", !1);
1630
+ a(this, "onSliceChange", (e) => {
1631
+ if (!this._disposed) {
1632
+ if (this.windowUpdateDepth > 0 && e.reason === "window") {
1633
+ this.windowChanged = !0;
1634
+ return;
1635
+ }
1636
+ this.dispatchEvent({ type: "change", reason: e.reason, axis: e.target.axis });
1637
+ }
1638
+ });
1639
+ a(this, "onSliceDispose", (e) => {
1640
+ this._disposed || this.dispatchEvent({ type: "change", reason: "dispose", axis: e.target.axis });
1641
+ });
1642
+ if (!e.hasSpatialVolume()) throw new Error("OrthoSlicer requires a spatial volume; use Slice Z for a frame sequence");
1643
+ this.stack = e, this.nx = e.columns, this.ny = e.rows, this.nz = e.numberOfFrames, this.size = this.nx * this.ny * this.nz, this.hx = e.pixelSpacing[1], this.hy = e.pixelSpacing[0], this.hz = Math.hypot(...e.sliceStep), this.lx = (this.nx - 1) * this.hx, this.ly = (this.ny - 1) * this.hy, this.lz = (this.nz - 1) * this.hz, this.sliceX = O.fromAxis(e, "x"), this.sliceY = O.fromAxis(e, "y"), this.sliceZ = O.fromAxis(e, "z"), this.add(this.sliceX, this.sliceY, this.sliceZ);
1644
+ for (const n of [this.sliceX, this.sliceY, this.sliceZ])
1645
+ n.addEventListener("change", this.onSliceChange), n.addEventListener("dispose", this.onSliceDispose);
1646
+ }
1647
+ set ix(e) {
1648
+ x(this, "OrthoSlicer"), this.sliceX.index = e;
1649
+ }
1650
+ get ix() {
1651
+ return this.sliceX.index;
1652
+ }
1653
+ set iy(e) {
1654
+ x(this, "OrthoSlicer"), this.sliceY.index = e;
1655
+ }
1656
+ get iy() {
1657
+ return this.sliceY.index;
1658
+ }
1659
+ set iz(e) {
1660
+ x(this, "OrthoSlicer"), this.sliceZ.index = e;
1661
+ }
1662
+ get iz() {
1663
+ return this.sliceZ.index;
1664
+ }
1665
+ setWindow(e, n) {
1666
+ x(this, "OrthoSlicer");
1667
+ const r = [this.sliceX, this.sliceY, this.sliceZ];
1668
+ for (const o of r) x(o, "Slice");
1669
+ V(this.stack, e, n), this.windowUpdateDepth++;
1670
+ try {
1671
+ U(r.map((o) => () => o.setWindow(e, n)));
1672
+ } finally {
1673
+ this.windowUpdateDepth--, this.windowUpdateDepth === 0 && this.windowChanged && (this.windowChanged = !1, this._disposed || this.dispatchEvent({ type: "change", reason: "window" }));
1674
+ }
1675
+ }
1676
+ get isDisposed() {
1677
+ return this._disposed;
1678
+ }
1679
+ dispose() {
1680
+ if (this._disposed) return;
1681
+ this._disposed = !0, this.visible = !1;
1682
+ const e = [this.sliceX, this.sliceY, this.sliceZ];
1683
+ for (const n of e)
1684
+ n.removeEventListener("change", this.onSliceChange), n.removeEventListener("dispose", this.onSliceDispose);
1685
+ U([
1686
+ () => this.removeFromParent(),
1687
+ ...e.map((n) => () => n.dispose()),
1688
+ () => this.clear(),
1689
+ () => this.dispatchEvent({ type: "dispose" })
1690
+ ]);
1691
+ }
1692
+ }
1693
+ const $e = {
1694
+ "ct-soft-tissue": {
1695
+ name: "CT soft tissue",
1696
+ mode: "composite",
1697
+ window: [-160, 240],
1698
+ threshold: 40,
1699
+ sampleDistance: 1,
1700
+ opacityScale: 0.72,
1701
+ lightingEnabled: !0,
1702
+ transferFunction: [
1703
+ { value: -1e3, color: [0, 0, 0], opacity: 0 },
1704
+ { value: -200, color: [0.35, 0.18, 0.12], opacity: 0 },
1705
+ { value: -80, color: [0.72, 0.36, 0.24], opacity: 0.05 },
1706
+ { value: 40, color: [0.9, 0.52, 0.42], opacity: 0.18 },
1707
+ { value: 180, color: [1, 0.76, 0.68], opacity: 0.28 },
1708
+ { value: 420, color: [1, 0.95, 0.86], opacity: 0.12 }
1709
+ ]
1710
+ },
1711
+ "ct-bone": {
1712
+ name: "CT bone",
1713
+ mode: "composite",
1714
+ window: [150, 1800],
1715
+ threshold: 320,
1716
+ sampleDistance: 0.85,
1717
+ opacityScale: 1.25,
1718
+ lightingEnabled: !0,
1719
+ lighting: {
1720
+ ambient: 0.18,
1721
+ diffuse: 0.82,
1722
+ specular: 0.22,
1723
+ shininess: 36
1724
+ },
1725
+ transferFunction: [
1726
+ { value: -3024, color: [0, 0, 0], opacity: 0 },
1727
+ { value: 120, color: [0.56, 0.32, 0.28], opacity: 0 },
1728
+ { value: 300, color: [0.78, 0.58, 0.42], opacity: 0.08 },
1729
+ { value: 641, color: [0.91, 0.82, 0.56], opacity: 0.72 },
1730
+ { value: 1250, color: [0.98, 0.95, 0.88], opacity: 0.86 },
1731
+ { value: 3071, color: [1, 1, 1], opacity: 0.92 }
1732
+ ]
1733
+ },
1734
+ "ct-bone-mip": {
1735
+ name: "CT bone MIP",
1736
+ mode: "mip",
1737
+ window: [120, 2200],
1738
+ threshold: 320,
1739
+ sampleDistance: 1,
1740
+ opacityScale: 1,
1741
+ lightingEnabled: !1,
1742
+ transferFunction: [
1743
+ { value: 120, color: [0.05, 0.05, 0.05], opacity: 0 },
1744
+ { value: 420, color: [0.72, 0.69, 0.62], opacity: 0.2 },
1745
+ { value: 1e3, color: [0.96, 0.92, 0.82], opacity: 0.75 },
1746
+ { value: 2200, color: [1, 1, 1], opacity: 1 }
1747
+ ]
1748
+ },
1749
+ "ct-lung": {
1750
+ name: "CT lung",
1751
+ mode: "composite",
1752
+ window: [-1e3, 250],
1753
+ threshold: -650,
1754
+ sampleDistance: 1,
1755
+ opacityScale: 0.95,
1756
+ lightingEnabled: !0,
1757
+ transferFunction: [
1758
+ { value: -1e3, color: [0, 0, 0], opacity: 0 },
1759
+ { value: -900, color: [0.42, 0.55, 0.68], opacity: 0.08 },
1760
+ { value: -720, color: [0.62, 0.72, 0.82], opacity: 0.32 },
1761
+ { value: -520, color: [0.72, 0.78, 0.84], opacity: 0.16 },
1762
+ { value: -260, color: [0.88, 0.74, 0.64], opacity: 0.04 },
1763
+ { value: 80, color: [1, 0.86, 0.78], opacity: 0 }
1764
+ ]
1765
+ },
1766
+ "ct-fat": {
1767
+ name: "CT fat",
1768
+ mode: "composite",
1769
+ window: [-220, 120],
1770
+ threshold: -95,
1771
+ sampleDistance: 0.9,
1772
+ opacityScale: 1.05,
1773
+ lightingEnabled: !0,
1774
+ transferFunction: [
1775
+ { value: -1e3, color: [0, 0, 0], opacity: 0 },
1776
+ { value: -190, color: [0.7, 0.52, 0.18], opacity: 0 },
1777
+ { value: -125, color: [0.95, 0.76, 0.28], opacity: 0.36 },
1778
+ { value: -70, color: [1, 0.86, 0.46], opacity: 0.42 },
1779
+ { value: -20, color: [0.92, 0.64, 0.3], opacity: 0.06 },
1780
+ { value: 120, color: [0.72, 0.38, 0.28], opacity: 0 }
1781
+ ]
1782
+ },
1783
+ "ct-air": {
1784
+ name: "CT air",
1785
+ mode: "composite",
1786
+ window: [-1100, -450],
1787
+ threshold: -900,
1788
+ sampleDistance: 1,
1789
+ opacityScale: 0.8,
1790
+ lightingEnabled: !1,
1791
+ transferFunction: [
1792
+ { value: -1100, color: [0.05, 0.1, 0.16], opacity: 0.26 },
1793
+ { value: -1e3, color: [0.12, 0.2, 0.28], opacity: 0.2 },
1794
+ { value: -820, color: [0.3, 0.42, 0.52], opacity: 0.08 },
1795
+ { value: -600, color: [0.62, 0.68, 0.72], opacity: 0.02 },
1796
+ { value: -450, color: [0.9, 0.9, 0.86], opacity: 0 }
1797
+ ]
1798
+ }
1799
+ };
1800
+ function ke(i) {
1801
+ return typeof i != "string" ? i : $e[i];
1802
+ }
1803
+ const re = {
1804
+ mip: 0,
1805
+ composite: 1,
1806
+ iso: 2
1807
+ };
1808
+ var qe = `in vec3 position;
1809
+
1810
+ uniform mat4 modelViewMatrix;
1811
+ uniform mat4 projectionMatrix;
1812
+
1813
+ out vec3 vPosition;
1814
+
1815
+ void main() {
1816
+ vPosition = position;
1817
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1818
+ }`;
1819
+ const Ge = {
1820
+ R8I: { samplerType: "isampler3D", texelType: "ivec4" },
1821
+ R8UI: { samplerType: "usampler3D", texelType: "uvec4" },
1822
+ R16I: { samplerType: "isampler3D", texelType: "ivec4" },
1823
+ R16UI: { samplerType: "usampler3D", texelType: "uvec4" },
1824
+ R32F: { samplerType: "sampler3D", texelType: "vec4" },
1825
+ RGB8I: { samplerType: "isampler3D", texelType: "ivec4" },
1826
+ RGB8UI: { samplerType: "usampler3D", texelType: "uvec4" },
1827
+ RGB16I: { samplerType: "isampler3D", texelType: "ivec4" },
1828
+ RGB16UI: { samplerType: "usampler3D", texelType: "uvec4" }
1829
+ };
1830
+ function je(i, { maxSteps: t, maxTransferPoints: e }) {
1831
+ const n = Ge[i];
1832
+ if (!n)
1833
+ throw new Error(`Unsupported volume texture internalFormat: ${i}`);
1834
+ const r = Math.max(1, Math.trunc(t)), o = Math.max(2, Math.trunc(e));
1835
+ return `
1836
+ precision highp float;
1837
+ precision highp int;
1838
+ precision highp ${n.samplerType};
1839
+
1840
+ uniform ${n.samplerType} map;
1841
+ uniform vec3 uCameraLocalPosition;
1842
+ uniform vec3 uCameraLocalDirection;
1843
+ uniform bool uOrthographicCamera;
1844
+ uniform vec3 uSize;
1845
+ uniform float uRescaleSlope;
1846
+ uniform float uRescaleIntercept;
1847
+ uniform int uMode;
1848
+ uniform vec2 uWindow;
1849
+ uniform float uThreshold;
1850
+ uniform float uSampleDistance;
1851
+ uniform float uOpacityScale;
1852
+ uniform bool uLightingEnabled;
1853
+ uniform vec4 uLighting;
1854
+ uniform int uTransferPointCount;
1855
+ uniform vec4 uTransferPoints[${o}];
1856
+ uniform vec2 uOpacityPoints[${o}];
1857
+
1858
+ in vec3 vPosition;
1859
+
1860
+ out vec4 fragColor;
1861
+
1862
+ const int MAX_STEPS = ${r};
1863
+ const int MAX_TRANSFER_POINTS = ${o};
1864
+ const int REFINEMENT_STEPS = 4;
1865
+
1866
+ ${Z}
1867
+
1868
+ float windowValue(float value);
1869
+ float safeDirection(float value);
1870
+ vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 boxMin, vec3 boxMax);
1871
+ float sampleRaw(vec3 texcoords);
1872
+ float sampleValue(vec3 texcoords);
1873
+ vec3 transferColor(float value);
1874
+ float transferOpacity(float value);
1875
+ vec4 applyTransfer(float value);
1876
+ vec4 applyLighting(float value, vec3 loc, vec3 viewRay);
1877
+ void castMip(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay);
1878
+ void castComposite(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay);
1879
+ void castIso(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay);
1880
+
1881
+ void main() {
1882
+ vec3 localCameraPosition = uCameraLocalPosition;
1883
+ vec3 rayDirection = normalize(vPosition - localCameraPosition);
1884
+
1885
+ if (uOrthographicCamera) {
1886
+ rayDirection = normalize(uCameraLocalDirection);
1887
+ localCameraPosition = vPosition - rayDirection * max(max(uSize.x, uSize.y), uSize.z) * 2.0;
1888
+ }
1889
+
1890
+ vec2 hit = intersectBox(localCameraPosition, rayDirection, vec3(-0.5), uSize - vec3(0.5));
1891
+ hit.x = max(hit.x, 0.0);
1892
+
1893
+ if (hit.x >= hit.y) {
1894
+ discard;
1895
+ }
1896
+
1897
+ vec3 startPosition = localCameraPosition + hit.x * rayDirection;
1898
+ vec3 endPosition = localCameraPosition + hit.y * rayDirection;
1899
+ float travelDistance = distance(startPosition, endPosition);
1900
+ int nsteps = int(travelDistance / max(uSampleDistance, 0.01) + 0.5);
1901
+
1902
+ if (nsteps < 1) {
1903
+ discard;
1904
+ }
1905
+
1906
+ nsteps = min(nsteps, MAX_STEPS);
1907
+
1908
+ vec3 stepVec = ((endPosition - startPosition) / uSize) / float(nsteps);
1909
+ vec3 startLoc = dataToTexture(startPosition, uSize);
1910
+
1911
+ fragColor = vec4(0.0);
1912
+
1913
+ if (uMode == 0) {
1914
+ castMip(startLoc, stepVec, nsteps, -rayDirection);
1915
+ } else if (uMode == 2) {
1916
+ castIso(startLoc, stepVec, nsteps, -rayDirection);
1917
+ } else {
1918
+ castComposite(startLoc, stepVec, nsteps, -rayDirection);
1919
+ }
1920
+
1921
+ if (fragColor.a <= 0.01) {
1922
+ discard;
1923
+ }
1924
+ }
1925
+
1926
+ float windowValue(float value) {
1927
+ return clamp((value - uWindow.x) / max(uWindow.y - uWindow.x, 0.0001), 0.0, 1.0);
1928
+ }
1929
+
1930
+ float safeDirection(float value) {
1931
+ if (abs(value) < 0.000001) {
1932
+ return value < 0.0 ? -0.000001 : 0.000001;
1933
+ }
1934
+
1935
+ return value;
1936
+ }
1937
+
1938
+ vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 boxMin, vec3 boxMax) {
1939
+ vec3 safeRayDirection = vec3(
1940
+ safeDirection(rayDirection.x),
1941
+ safeDirection(rayDirection.y),
1942
+ safeDirection(rayDirection.z)
1943
+ );
1944
+ vec3 invDirection = 1.0 / safeRayDirection;
1945
+ vec3 t0 = (boxMin - rayOrigin) * invDirection;
1946
+ vec3 t1 = (boxMax - rayOrigin) * invDirection;
1947
+ vec3 tMin = min(t0, t1);
1948
+ vec3 tMax = max(t0, t1);
1949
+ float tNear = max(max(tMin.x, tMin.y), tMin.z);
1950
+ float tFar = min(min(tMax.x, tMax.y), tMax.z);
1951
+
1952
+ return vec2(tNear, tFar);
1953
+ }
1954
+
1955
+ float sampleRaw(vec3 texcoords) {
1956
+ vec3 clampedCoords = clamp(texcoords, vec3(0.0), vec3(1.0));
1957
+ ivec3 index = nearestVoxelIndex(clampedCoords * uSize - vec3(0.5), uSize);
1958
+ ${n.texelType} texel = texelFetch(map, index, 0);
1959
+
1960
+ return float(texel.r);
1961
+ }
1962
+
1963
+ float sampleValue(vec3 texcoords) {
1964
+ return sampleRaw(texcoords) * uRescaleSlope + uRescaleIntercept;
1965
+ }
1966
+
1967
+ vec3 transferColor(float value) {
1968
+ if (uTransferPointCount <= 0) {
1969
+ return vec3(windowValue(value));
1970
+ }
1971
+
1972
+ vec4 previousPoint = uTransferPoints[0];
1973
+
1974
+ if (value <= previousPoint.x) {
1975
+ return previousPoint.yzw;
1976
+ }
1977
+
1978
+ for (int i = 1; i < MAX_TRANSFER_POINTS; i++) {
1979
+ if (i >= uTransferPointCount) {
1980
+ break;
1981
+ }
1982
+
1983
+ vec4 currentPoint = uTransferPoints[i];
1984
+
1985
+ if (value <= currentPoint.x) {
1986
+ float rangeValue = max(currentPoint.x - previousPoint.x, 0.0001);
1987
+ float t = clamp((value - previousPoint.x) / rangeValue, 0.0, 1.0);
1988
+ return mix(previousPoint.yzw, currentPoint.yzw, t);
1989
+ }
1990
+
1991
+ previousPoint = currentPoint;
1992
+ }
1993
+
1994
+ return previousPoint.yzw;
1995
+ }
1996
+
1997
+ float transferOpacity(float value) {
1998
+ if (uTransferPointCount <= 0) {
1999
+ return windowValue(value);
2000
+ }
2001
+
2002
+ vec2 previousPoint = uOpacityPoints[0];
2003
+
2004
+ if (value <= previousPoint.x) {
2005
+ return previousPoint.y;
2006
+ }
2007
+
2008
+ for (int i = 1; i < MAX_TRANSFER_POINTS; i++) {
2009
+ if (i >= uTransferPointCount) {
2010
+ break;
2011
+ }
2012
+
2013
+ vec2 currentPoint = uOpacityPoints[i];
2014
+
2015
+ if (value <= currentPoint.x) {
2016
+ float rangeValue = max(currentPoint.x - previousPoint.x, 0.0001);
2017
+ float t = clamp((value - previousPoint.x) / rangeValue, 0.0, 1.0);
2018
+ return mix(previousPoint.y, currentPoint.y, t);
2019
+ }
2020
+
2021
+ previousPoint = currentPoint;
2022
+ }
2023
+
2024
+ return previousPoint.y;
2025
+ }
2026
+
2027
+ vec4 applyTransfer(float value) {
2028
+ return vec4(transferColor(value), clamp(transferOpacity(value) * uOpacityScale, 0.0, 1.0));
2029
+ }
2030
+
2031
+ vec4 applyLighting(float value, vec3 loc, vec3 viewRay) {
2032
+ vec4 baseColor = applyTransfer(value);
2033
+
2034
+ if (!uLightingEnabled || baseColor.a <= 0.0) {
2035
+ return baseColor;
2036
+ }
2037
+
2038
+ vec3 gradientStep = 1.5 / max(uSize, vec3(1.0));
2039
+ vec3 normal;
2040
+ normal.x = sampleValue(loc + vec3(-gradientStep.x, 0.0, 0.0)) - sampleValue(loc + vec3(gradientStep.x, 0.0, 0.0));
2041
+ normal.y = sampleValue(loc + vec3(0.0, -gradientStep.y, 0.0)) - sampleValue(loc + vec3(0.0, gradientStep.y, 0.0));
2042
+ normal.z = sampleValue(loc + vec3(0.0, 0.0, -gradientStep.z)) - sampleValue(loc + vec3(0.0, 0.0, gradientStep.z));
2043
+
2044
+ if (length(normal) <= 0.0001) {
2045
+ return baseColor;
2046
+ }
2047
+
2048
+ vec3 viewDirection = normalize(viewRay);
2049
+ normal = normalize(normal);
2050
+
2051
+ if (dot(normal, viewDirection) < 0.0) {
2052
+ normal = -normal;
2053
+ }
2054
+
2055
+ float lambert = clamp(dot(normal, viewDirection), 0.0, 1.0);
2056
+ float specular = pow(max(dot(normal, viewDirection), 0.0), max(uLighting.w, 1.0));
2057
+ vec3 litColor = baseColor.rgb * (uLighting.x + uLighting.y * lambert) + vec3(uLighting.z * specular);
2058
+
2059
+ return vec4(clamp(litColor, vec3(0.0), vec3(1.0)), baseColor.a);
2060
+ }
2061
+
2062
+ void castMip(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
2063
+ float maxValue = -1e20;
2064
+ vec3 maxLoc = startLoc;
2065
+ vec3 loc = startLoc;
2066
+
2067
+ for (int iter = 0; iter < MAX_STEPS; iter++) {
2068
+ if (iter >= nsteps) {
2069
+ break;
2070
+ }
2071
+
2072
+ float value = sampleValue(loc);
2073
+
2074
+ if (value > maxValue) {
2075
+ maxValue = value;
2076
+ maxLoc = loc;
2077
+ }
2078
+
2079
+ loc += stepVec;
2080
+ }
2081
+
2082
+ vec3 refineStep = stepVec / float(REFINEMENT_STEPS);
2083
+ loc = maxLoc - 0.5 * stepVec;
2084
+
2085
+ for (int i = 0; i < REFINEMENT_STEPS; i++) {
2086
+ float value = sampleValue(loc);
2087
+
2088
+ if (value > maxValue) {
2089
+ maxValue = value;
2090
+ maxLoc = loc;
2091
+ }
2092
+
2093
+ loc += refineStep;
2094
+ }
2095
+
2096
+ float intensity = windowValue(maxValue);
2097
+ vec4 color = applyTransfer(maxValue);
2098
+ fragColor = vec4(color.rgb * max(intensity, 0.2), max(color.a, intensity));
2099
+ }
2100
+
2101
+ void castComposite(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
2102
+ vec4 accumulated = vec4(0.0);
2103
+ vec3 loc = startLoc;
2104
+ float stepLength = max(length(stepVec * uSize), 0.01);
2105
+
2106
+ for (int iter = 0; iter < MAX_STEPS; iter++) {
2107
+ if (iter >= nsteps || accumulated.a >= 0.98) {
2108
+ break;
2109
+ }
2110
+
2111
+ float value = sampleValue(loc);
2112
+ vec4 sampleColor = applyLighting(value, loc, viewRay);
2113
+ sampleColor.a = clamp(sampleColor.a * stepLength, 0.0, 1.0);
2114
+
2115
+ accumulated.rgb += (1.0 - accumulated.a) * sampleColor.rgb * sampleColor.a;
2116
+ accumulated.a += (1.0 - accumulated.a) * sampleColor.a;
2117
+
2118
+ loc += stepVec;
2119
+ }
2120
+
2121
+ if (accumulated.a > 0.0) {
2122
+ accumulated.rgb /= accumulated.a;
2123
+ }
2124
+
2125
+ fragColor = accumulated;
2126
+ }
2127
+
2128
+ void castIso(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
2129
+ vec3 loc = startLoc;
2130
+ float lowThreshold = uThreshold - 0.02 * max(uWindow.y - uWindow.x, 1.0);
2131
+
2132
+ for (int iter = 0; iter < MAX_STEPS; iter++) {
2133
+ if (iter >= nsteps) {
2134
+ break;
2135
+ }
2136
+
2137
+ float value = sampleValue(loc);
2138
+
2139
+ if (value > lowThreshold) {
2140
+ vec3 refineLoc = loc - 0.5 * stepVec;
2141
+ vec3 refineStep = stepVec / float(REFINEMENT_STEPS);
2142
+
2143
+ for (int i = 0; i < REFINEMENT_STEPS; i++) {
2144
+ value = sampleValue(refineLoc);
2145
+
2146
+ if (value >= uThreshold) {
2147
+ fragColor = applyLighting(value, refineLoc, viewRay);
2148
+ fragColor.a = max(fragColor.a, 0.95);
2149
+ return;
2150
+ }
2151
+
2152
+ refineLoc += refineStep;
2153
+ }
2154
+ }
2155
+
2156
+ loc += stepVec;
2157
+ }
2158
+ }
2159
+ `;
2160
+ }
2161
+ const F = 8, Xe = 1024, Ye = {
2162
+ ambient: 0.22,
2163
+ diffuse: 0.78,
2164
+ specular: 0.16,
2165
+ shininess: 32
2166
+ };
2167
+ class ct extends u.Object3D {
2168
+ constructor(e, n = {}) {
2169
+ var f;
2170
+ super();
2171
+ a(this, "stack");
2172
+ a(this, "nx");
2173
+ a(this, "ny");
2174
+ a(this, "nz");
2175
+ a(this, "size");
2176
+ a(this, "lx");
2177
+ a(this, "ly");
2178
+ a(this, "lz");
2179
+ a(this, "hx");
2180
+ a(this, "hy");
2181
+ a(this, "hz");
2182
+ a(this, "texture");
2183
+ a(this, "mesh");
2184
+ a(this, "maxSteps");
2185
+ a(this, "_mode", "composite");
2186
+ a(this, "_window");
2187
+ a(this, "_threshold");
2188
+ a(this, "_sampleDistance", 1);
2189
+ a(this, "_opacityScale", 1);
2190
+ a(this, "_lightingEnabled", !0);
2191
+ a(this, "_lighting", { ...Ye });
2192
+ a(this, "_transferFunction");
2193
+ a(this, "_disposed", !1);
2194
+ a(this, "_inverseMatrixWorld", new u.Matrix4());
2195
+ a(this, "_cameraWorldPosition", new u.Vector3());
2196
+ a(this, "_cameraWorldDirection", new u.Vector3());
2197
+ if (!e.hasSpatialVolume()) throw new Error("VolumeRaycaster requires a spatial volume; use Slice Z for a frame sequence");
2198
+ this.stack = e, this.nx = e.columns, this.ny = e.rows, this.nz = e.numberOfFrames, this.size = this.nx * this.ny * this.nz, this.hx = e.pixelSpacing[1], this.hy = e.pixelSpacing[0], this.hz = Math.hypot(...e.sliceStep), this.lx = (this.nx - 1) * this.hx, this.ly = (this.ny - 1) * this.hy, this.lz = (this.nz - 1) * this.hz, this.texture = e.textureFactory.data3DTexture, this.maxSteps = Math.max(1, Math.trunc(n.maxSteps ?? Xe));
2199
+ const r = se(e);
2200
+ this._window = [...r], this._threshold = r[0] + (r[1] - r[0]) * 0.65, this._transferFunction = oe(r);
2201
+ const o = je(String(this.texture.internalFormat), {
2202
+ maxSteps: this.maxSteps,
2203
+ maxTransferPoints: F
2204
+ }), s = {
2205
+ map: { value: this.texture },
2206
+ uCameraLocalPosition: { value: new u.Vector3() },
2207
+ uCameraLocalDirection: { value: new u.Vector3(0, 0, -1) },
2208
+ uOrthographicCamera: { value: !1 },
2209
+ uSize: { value: z(e) },
2210
+ uRescaleSlope: { value: e.rescaleSlope },
2211
+ uRescaleIntercept: { value: e.rescaleIntercept },
2212
+ uMode: { value: re[this._mode] },
2213
+ uWindow: { value: new u.Vector2(this._window[0], this._window[1]) },
2214
+ uThreshold: { value: this._threshold },
2215
+ uSampleDistance: { value: this._sampleDistance },
2216
+ uOpacityScale: { value: this._opacityScale },
2217
+ uLightingEnabled: { value: this._lightingEnabled },
2218
+ uLighting: { value: ae(this._lighting) },
2219
+ uTransferPointCount: { value: this._transferFunction.length },
2220
+ uTransferPoints: { value: He() },
2221
+ uOpacityPoints: { value: Je() }
2222
+ }, l = new u.RawShaderMaterial({
2223
+ glslVersion: u.GLSL3,
2224
+ uniforms: s,
2225
+ vertexShader: qe,
2226
+ fragmentShader: o,
2227
+ side: u.BackSide,
2228
+ transparent: !0,
2229
+ depthWrite: !1
2230
+ }), c = new u.BoxGeometry(this.nx, this.ny, this.nz), m = B(e);
2231
+ c.translate(m.x, m.y, m.z), this.mesh = new u.Mesh(c, l), this.mesh.onBeforeRender = (g, v, w) => {
2232
+ this.updateCameraUniforms(w);
2233
+ }, this.add(this.mesh), this.transferFunction = this._transferFunction;
2234
+ const d = n.preset ?? (((f = e.modality) == null ? void 0 : f.toUpperCase()) === "CT" ? "ct-soft-tissue" : void 0);
2235
+ d && this.setPreset(d), this.applyOptions(n), this.matrixAutoUpdate = !1, this.matrix.copy(e.ijk2lps);
2236
+ }
2237
+ set mode(e) {
2238
+ x(this, "VolumeRaycaster");
2239
+ const n = re[e];
2240
+ if (n === void 0)
2241
+ throw new Error(`Unsupported volume rendering mode: ${e}`);
2242
+ this._mode = e, this.mesh.material.uniforms.uMode.value = n;
2243
+ }
2244
+ get mode() {
2245
+ return this._mode;
2246
+ }
2247
+ set window(e) {
2248
+ x(this, "VolumeRaycaster");
2249
+ const n = xe(e);
2250
+ this._window = n, this.mesh.material.uniforms.uWindow.value.set(n[0], n[1]);
2251
+ }
2252
+ get window() {
2253
+ return [...this._window];
2254
+ }
2255
+ set threshold(e) {
2256
+ if (x(this, "VolumeRaycaster"), !Number.isFinite(e))
2257
+ throw new Error(`Volume threshold must be finite, got: ${e}`);
2258
+ this._threshold = e, this.mesh.material.uniforms.uThreshold.value = e;
2259
+ }
2260
+ get threshold() {
2261
+ return this._threshold;
2262
+ }
2263
+ set sampleDistance(e) {
2264
+ if (x(this, "VolumeRaycaster"), !(Number.isFinite(e) && e > 0))
2265
+ throw new Error(`Volume sampleDistance must be positive, got: ${e}`);
2266
+ this._sampleDistance = e, this.mesh.material.uniforms.uSampleDistance.value = e;
2267
+ }
2268
+ get sampleDistance() {
2269
+ return this._sampleDistance;
2270
+ }
2271
+ set opacityScale(e) {
2272
+ if (x(this, "VolumeRaycaster"), !(Number.isFinite(e) && e >= 0))
2273
+ throw new Error(`Volume opacityScale must be non-negative, got: ${e}`);
2274
+ this._opacityScale = e, this.mesh.material.uniforms.uOpacityScale.value = e;
2275
+ }
2276
+ get opacityScale() {
2277
+ return this._opacityScale;
2278
+ }
2279
+ set lightingEnabled(e) {
2280
+ x(this, "VolumeRaycaster"), this._lightingEnabled = e, this.mesh.material.uniforms.uLightingEnabled.value = e;
2281
+ }
2282
+ get lightingEnabled() {
2283
+ return this._lightingEnabled;
2284
+ }
2285
+ set lighting(e) {
2286
+ x(this, "VolumeRaycaster"), this._lighting = {
2287
+ ...this._lighting,
2288
+ ...e
2289
+ }, this.mesh.material.uniforms.uLighting.value.copy(ae(this._lighting));
2290
+ }
2291
+ get lighting() {
2292
+ return { ...this._lighting };
2293
+ }
2294
+ set transferFunction(e) {
2295
+ x(this, "VolumeRaycaster"), this._transferFunction = Ze(e);
2296
+ const n = this.mesh.material.uniforms.uTransferPoints.value, r = this.mesh.material.uniforms.uOpacityPoints.value, o = this._transferFunction[this._transferFunction.length - 1];
2297
+ for (let s = 0; s < F; s++) {
2298
+ const l = this._transferFunction[s] ?? o;
2299
+ n[s].set(l.value, l.color[0], l.color[1], l.color[2]), r[s].set(l.value, l.opacity);
2300
+ }
2301
+ this.mesh.material.uniforms.uTransferPointCount.value = this._transferFunction.length;
2302
+ }
2303
+ get transferFunction() {
2304
+ return this._transferFunction.map((e) => ({
2305
+ value: e.value,
2306
+ color: [...e.color],
2307
+ opacity: e.opacity
2308
+ }));
2309
+ }
2310
+ setPreset(e) {
2311
+ x(this, "VolumeRaycaster");
2312
+ const n = ke(e);
2313
+ n.mode && (this.mode = n.mode), n.window && (this.window = n.window), n.threshold !== void 0 && (this.threshold = n.threshold), n.sampleDistance !== void 0 && (this.sampleDistance = n.sampleDistance), n.opacityScale !== void 0 && (this.opacityScale = n.opacityScale), n.lightingEnabled !== void 0 && (this.lightingEnabled = n.lightingEnabled), n.lighting && (this.lighting = n.lighting), n.transferFunction && (this.transferFunction = n.transferFunction);
2314
+ }
2315
+ resetToStackWindow() {
2316
+ x(this, "VolumeRaycaster");
2317
+ const e = se(this.stack);
2318
+ this.window = e, this.threshold = e[0] + (e[1] - e[0]) * 0.65, this.transferFunction = oe(e);
2319
+ }
2320
+ get isDisposed() {
2321
+ return this._disposed;
2322
+ }
2323
+ dispose() {
2324
+ if (this._disposed) return;
2325
+ this._disposed = !0, this.visible = !1, this.mesh.onBeforeRender = () => {
2326
+ };
2327
+ const { geometry: e, material: n } = this.mesh;
2328
+ U([
2329
+ () => this.mesh.removeFromParent(),
2330
+ () => this.removeFromParent(),
2331
+ () => this.clear(),
2332
+ () => e.dispose(),
2333
+ () => n.dispose()
2334
+ ]);
2335
+ }
2336
+ applyOptions(e) {
2337
+ e.mode && (this.mode = e.mode), e.window && (this.window = e.window), e.threshold !== void 0 && (this.threshold = e.threshold), e.sampleDistance !== void 0 && (this.sampleDistance = e.sampleDistance), e.opacityScale !== void 0 && (this.opacityScale = e.opacityScale), e.lightingEnabled !== void 0 && (this.lightingEnabled = e.lightingEnabled), e.lighting && (this.lighting = e.lighting), e.transferFunction && (this.transferFunction = e.transferFunction);
2338
+ }
2339
+ updateCameraUniforms(e) {
2340
+ this._inverseMatrixWorld.copy(this.mesh.matrixWorld).invert(), e.getWorldPosition(this._cameraWorldPosition), e.getWorldDirection(this._cameraWorldDirection);
2341
+ const n = this.mesh.material.uniforms;
2342
+ n.uCameraLocalPosition.value.copy(this._cameraWorldPosition).applyMatrix4(this._inverseMatrixWorld), n.uCameraLocalDirection.value.copy(this._cameraWorldDirection).transformDirection(this._inverseMatrixWorld), n.uOrthographicCamera.value = e.isOrthographicCamera === !0;
2343
+ }
2344
+ }
2345
+ function oe(i) {
2346
+ const [t, e] = xe(i);
2347
+ return [
2348
+ { value: t, color: [0, 0, 0], opacity: 0 },
2349
+ { value: e, color: [1, 1, 1], opacity: 1 }
2350
+ ];
2351
+ }
2352
+ function se(i) {
2353
+ const t = Number.isFinite(i.windowWidth) && i.windowWidth > 0 ? i.windowWidth : 1, e = Number.isFinite(i.windowCenter) ? i.windowCenter : 0;
2354
+ return [e - t / 2, e + t / 2];
2355
+ }
2356
+ function xe(i) {
2357
+ const [t, e] = i;
2358
+ if (!(Number.isFinite(t) && Number.isFinite(e) && t < e))
2359
+ throw new Error(`Volume window must be [finite lower, finite upper], got: [${t}, ${e}]`);
2360
+ return [t, e];
2361
+ }
2362
+ function Ze(i) {
2363
+ if (i.length === 0)
2364
+ throw new Error("Volume transferFunction must contain at least one point");
2365
+ if (i.length > F)
2366
+ throw new Error(
2367
+ `Volume transferFunction supports up to ${F} points, got: ${i.length}`
2368
+ );
2369
+ return [...i].sort((t, e) => t.value - e.value).map((t) => {
2370
+ if (!Number.isFinite(t.value))
2371
+ throw new Error(`Volume transferFunction point value must be finite, got: ${t.value}`);
2372
+ return {
2373
+ value: t.value,
2374
+ color: [
2375
+ u.MathUtils.clamp(t.color[0], 0, 1),
2376
+ u.MathUtils.clamp(t.color[1], 0, 1),
2377
+ u.MathUtils.clamp(t.color[2], 0, 1)
2378
+ ],
2379
+ opacity: u.MathUtils.clamp(t.opacity, 0, 1)
2380
+ };
2381
+ });
2382
+ }
2383
+ function He() {
2384
+ return Array.from({ length: F }, () => new u.Vector4());
2385
+ }
2386
+ function Je() {
2387
+ return Array.from({ length: F }, () => new u.Vector2());
2388
+ }
2389
+ function ae(i) {
2390
+ return new u.Vector4(i.ambient, i.diffuse, i.specular, i.shininess);
2391
+ }
2392
+ export {
2393
+ Xe as DEFAULT_VOLUME_MAX_STEPS,
2394
+ it as DicomLoader,
2395
+ K as DicomParser,
2396
+ rt as DicomWorkerLoader,
2397
+ F as MAX_VOLUME_TRANSFER_POINTS,
2398
+ at as ObliqueSlice,
2399
+ lt as OrthoSlicer,
2400
+ O as Slice,
2401
+ X as Stack,
2402
+ re as VOLUME_RENDERING_MODE_VALUES,
2403
+ $e as VOLUME_RENDERING_PRESETS,
2404
+ ct as VolumeRaycaster,
2405
+ q as convertSlicePlane,
2406
+ oe as createWindowTransferFunction,
2407
+ nt as dicomPreloader,
2408
+ st as getSliceOffsetRange,
2409
+ Ue as getStackBounds,
2410
+ B as getStackCenter,
2411
+ he as getStackCorners,
2412
+ z as getStackSize,
2413
+ Y as normalizeSlicePlane,
2414
+ ot as offsetSlicePlane,
2415
+ ke as resolveVolumeRenderingPreset
2416
+ };