copper3d 4.0.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +16 -7
  2. package/ai-index/guides/load-callbacks.md +24 -5
  3. package/ai-index/guides/orientation.md +163 -0
  4. package/ai-index/guides/segmentation-module.md +51 -25
  5. package/ai-index/guides/volume-display.md +1 -1
  6. package/ai-index/manifest.json +14 -6
  7. package/ai-index/symbols.json +1 -1
  8. package/dist/Controls/orbitFraming.d.ts +4 -4
  9. package/dist/Controls/orbitFraming.js +4 -4
  10. package/dist/Loader/copperNrrdLoader.d.ts +15 -1
  11. package/dist/Loader/copperNrrdLoader.js +30 -8
  12. package/dist/Loader/copperNrrdLoader.js.map +1 -1
  13. package/dist/Loader/nrrdWorkerCore.d.ts +15 -2
  14. package/dist/Loader/nrrdWorkerCore.js +47 -3
  15. package/dist/Loader/nrrdWorkerCore.js.map +1 -1
  16. package/dist/Loader/rasDimensions.d.ts +9 -0
  17. package/dist/Loader/rasDimensions.js +12 -0
  18. package/dist/Loader/rasDimensions.js.map +1 -0
  19. package/dist/Scene/commonSceneMethod.d.ts +10 -1
  20. package/dist/Scene/commonSceneMethod.js +11 -3
  21. package/dist/Scene/commonSceneMethod.js.map +1 -1
  22. package/dist/Utils/orientation.d.ts +94 -0
  23. package/dist/Utils/orientation.js +261 -0
  24. package/dist/Utils/orientation.js.map +1 -0
  25. package/dist/Utils/segmentation/NrrdTools.d.ts +4 -0
  26. package/dist/Utils/segmentation/NrrdTools.js +4 -2
  27. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  28. package/dist/Utils/segmentation/RenderingUtils.d.ts +0 -5
  29. package/dist/Utils/segmentation/RenderingUtils.js +3 -23
  30. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  31. package/dist/Utils/segmentation/contourPaint.d.ts +5 -0
  32. package/dist/Utils/segmentation/contourPaint.js +10 -3
  33. package/dist/Utils/segmentation/contourPaint.js.map +1 -1
  34. package/dist/Utils/segmentation/core/MaskVolume.d.ts +1 -1
  35. package/dist/Utils/segmentation/core/MaskVolume.js +38 -38
  36. package/dist/Utils/segmentation/core/MaskVolume.js.map +1 -1
  37. package/dist/Utils/segmentation/tools/AiAssistTool.js +10 -10
  38. package/dist/Utils/segmentation/tools/AiAssistTool.js.map +1 -1
  39. package/dist/Utils/segmentation/tools/ContrastTool.js +1 -1
  40. package/dist/Utils/segmentation/tools/CrosshairTool.js +30 -22
  41. package/dist/Utils/segmentation/tools/CrosshairTool.js.map +1 -1
  42. package/dist/Utils/segmentation/tools/DrawingTool.js +14 -14
  43. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  44. package/dist/Utils/segmentation/tools/ImageStoreHelper.d.ts +3 -5
  45. package/dist/Utils/segmentation/tools/ImageStoreHelper.js +7 -11
  46. package/dist/Utils/segmentation/tools/ImageStoreHelper.js.map +1 -1
  47. package/dist/Utils/segmentation/tools/MaskMirror.js +5 -5
  48. package/dist/Utils/segmentation/tools/MaskMirror.js.map +1 -1
  49. package/dist/Utils/segmentation/tools/SliceRenderPipeline.d.ts +28 -4
  50. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +50 -24
  51. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  52. package/dist/Utils/segmentation/tools/SphereBrushTool.js +5 -4
  53. package/dist/Utils/segmentation/tools/SphereBrushTool.js.map +1 -1
  54. package/dist/Utils/segmentation/tools/SphereTool.js +13 -11
  55. package/dist/Utils/segmentation/tools/SphereTool.js.map +1 -1
  56. package/dist/bundle.esm.mjs +628 -317
  57. package/dist/bundle.umd.js +639 -320
  58. package/dist/index.d.ts +5 -2
  59. package/dist/index.js +3 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/orientation.cjs +276 -0
  62. package/dist/orientation.mjs +262 -0
  63. package/dist/types/Controls/orbitFraming.d.ts +4 -4
  64. package/dist/types/Loader/copperNrrdLoader.d.ts +15 -1
  65. package/dist/types/Loader/nrrdWorkerCore.d.ts +15 -2
  66. package/dist/types/Loader/rasDimensions.d.ts +9 -0
  67. package/dist/types/Scene/commonSceneMethod.d.ts +10 -1
  68. package/dist/types/Utils/orientation.d.ts +94 -0
  69. package/dist/types/Utils/segmentation/NrrdTools.d.ts +4 -0
  70. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +0 -5
  71. package/dist/types/Utils/segmentation/contourPaint.d.ts +5 -0
  72. package/dist/types/Utils/segmentation/core/MaskVolume.d.ts +1 -1
  73. package/dist/types/Utils/segmentation/tools/ImageStoreHelper.d.ts +3 -5
  74. package/dist/types/Utils/segmentation/tools/SliceRenderPipeline.d.ts +28 -4
  75. package/dist/types/index.d.ts +5 -2
  76. package/package.json +6 -1
package/dist/index.d.ts CHANGED
@@ -45,6 +45,7 @@ import type { PosableScene } from "./Controls/setCameraPose";
45
45
  import { addVolumeBoundingBox, VOLUME_BOUNDS_NAME } from "./Loader/volumeBoundingBox";
46
46
  import type { BoundingBoxHost, VolumeBoundingBoxOpts } from "./Loader/volumeBoundingBox";
47
47
  import { DEFAULT_AXES, ensureAxisExtracted, prepareVolumeSlices } from "./Loader/copperNrrdLoader";
48
+ import { rasDimensions } from "./Loader/rasDimensions";
48
49
  import type { NrrdAxis } from "./Loader/copperNrrdLoader";
49
50
  import { easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle } from "./Controls/cameraTransitions";
50
51
  import type { Pose } from "./Controls/cameraTransitions";
@@ -60,8 +61,10 @@ import { CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_
60
61
  import type { LayerId, ChannelValue } from "./Utils/segmentation/core/index";
61
62
  import { MAX_ENGINE_CHANNEL } from "./Utils/segmentation/core/index";
62
63
  import type { AiPromptTool, AiPromptPoint, AiPromptPayload, AiMaskResult } from "./Utils/segmentation/tools/AiAssistTool";
64
+ import { OrientationError, canonicalTransform, geometryFromNrrd, readNrrdOrientationFields, reorientVoxels, reorientedGeometry, viewLabels } from "./Utils/orientation";
65
+ import type { NrrdOrientationFields, OrientationErrorCode, OrientationTransform, ViewAxis, ViewLabels, VolumeGeometry, VolumeOrientation } from "./Utils/orientation";
63
66
  import "./css/style.css";
64
67
  export declare const REVISION: string;
65
- export { copperRenderer, copperRendererOnDemond, copperMSceneRenderer, setHDRFilePath, addLabelToScene, convert3DPostoScreenPos, convertScreenPosto3DPos, addBoxHelper, fullScreenListenner, configKiwriousHeart, copperScene, copperSceneOnDemond, copperMScene, CameraViewPoint, kiwrious, loadKiwrious, NrrdTools, registerNiftiMaskGrid, loading, Copper3dTrackballControls, Copper3dOrbitControls, createTexture2D_NRRD, MeshNodeTool, throttle, removeGuiFolderChilden, MAX_ENGINE_CHANNEL, CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss, GaussianSmoother, SurfaceAnnotator, exposureExponent, DEFAULT_TARGET_GREY, disposeObject3D, disposeMaterial, collectFadeTargets, setFade, restoreFade, createSceneBudget, defaultBudgetBytes, disposeScene, removeSceneFromMap, fitDistance, fitView, isRotateEnabled, setRotateEnabled, isPanEnabled, setPanEnabled, isZoomEnabled, setZoomEnabled, beginGesture, isGestureActive, setCameraPose, addVolumeBoundingBox, VOLUME_BOUNDS_NAME, DEFAULT_AXES, ensureAxisExtracted, prepareVolumeSlices, copperGltfLoader, setDracoDecoderPath, setKTX2TranscoderPath, easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle, installFastSliceRepaint, };
66
- export type { positionType, screenPosType, optsType, NrrdHeaderLike, GltfLoadOpts, nrrdMeshesType, nrrdSliceType, SensorDecodedValue_kiwrious, SensorReadResult_kiwrious, HeartRateResult_kiwrious, loadingBarType, IPaintImage, exportPaintImageType, IOptVTKLoader, aligned4DSurfaceType, aligned4DOptsType, Aligned4DController, raw4DVolumeTransformType, raw4DVolumeOptsType, Raw4DVolumeController, ICommXYZ, IGUIStates, IGuiParameterSettings, INrrdStates, NrrdState, GuiState, IGuiMeta, ToolMode, IAnnotationCallbacks, MaskRenderMode, LayerId, ChannelValue, AiPromptTool, AiPromptPoint, AiPromptPayload, AiMaskResult, SurfaceAnnotatorOptions, Annotation, AnnotationMode, ExportOptions, ExposureVolume, DisposableObject3D, DisposableMaterial, FadeTarget, FadeableMaterial, SceneBudget, DisposableScene, SceneDisposalHost, FitBounds, FitViewScene, AxisGatedControls, GestureAxes, PosableScene, BoundingBoxHost, VolumeBoundingBoxOpts, NrrdAxis, Pose, };
68
+ export { copperRenderer, copperRendererOnDemond, copperMSceneRenderer, setHDRFilePath, addLabelToScene, convert3DPostoScreenPos, convertScreenPosto3DPos, addBoxHelper, fullScreenListenner, configKiwriousHeart, copperScene, copperSceneOnDemond, copperMScene, CameraViewPoint, kiwrious, loadKiwrious, NrrdTools, registerNiftiMaskGrid, loading, Copper3dTrackballControls, Copper3dOrbitControls, createTexture2D_NRRD, MeshNodeTool, throttle, removeGuiFolderChilden, MAX_ENGINE_CHANNEL, CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss, GaussianSmoother, SurfaceAnnotator, exposureExponent, DEFAULT_TARGET_GREY, disposeObject3D, disposeMaterial, collectFadeTargets, setFade, restoreFade, createSceneBudget, defaultBudgetBytes, disposeScene, removeSceneFromMap, fitDistance, fitView, isRotateEnabled, setRotateEnabled, isPanEnabled, setPanEnabled, isZoomEnabled, setZoomEnabled, beginGesture, isGestureActive, setCameraPose, addVolumeBoundingBox, VOLUME_BOUNDS_NAME, rasDimensions, DEFAULT_AXES, ensureAxisExtracted, prepareVolumeSlices, copperGltfLoader, setDracoDecoderPath, setKTX2TranscoderPath, easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle, installFastSliceRepaint, OrientationError, canonicalTransform, geometryFromNrrd, readNrrdOrientationFields, reorientVoxels, reorientedGeometry, viewLabels, };
69
+ export type { positionType, screenPosType, optsType, NrrdHeaderLike, GltfLoadOpts, nrrdMeshesType, nrrdSliceType, SensorDecodedValue_kiwrious, SensorReadResult_kiwrious, HeartRateResult_kiwrious, loadingBarType, IPaintImage, exportPaintImageType, IOptVTKLoader, aligned4DSurfaceType, aligned4DOptsType, Aligned4DController, raw4DVolumeTransformType, raw4DVolumeOptsType, Raw4DVolumeController, ICommXYZ, IGUIStates, IGuiParameterSettings, INrrdStates, NrrdState, GuiState, IGuiMeta, ToolMode, IAnnotationCallbacks, MaskRenderMode, LayerId, ChannelValue, AiPromptTool, AiPromptPoint, AiPromptPayload, AiMaskResult, SurfaceAnnotatorOptions, Annotation, AnnotationMode, ExportOptions, ExposureVolume, DisposableObject3D, DisposableMaterial, FadeTarget, FadeableMaterial, SceneBudget, DisposableScene, SceneDisposalHost, FitBounds, FitViewScene, AxisGatedControls, GestureAxes, PosableScene, BoundingBoxHost, VolumeBoundingBoxOpts, NrrdAxis, Pose, NrrdOrientationFields, OrientationErrorCode, OrientationTransform, ViewAxis, ViewLabels, VolumeGeometry, VolumeOrientation, };
67
70
  export type { CameraViewPreset } from "./Controls/orbitFraming";
package/dist/index.js CHANGED
@@ -34,6 +34,7 @@ import { beginGesture, isGestureActive } from "./Controls/gestureGate";
34
34
  import { setCameraPose } from "./Controls/setCameraPose";
35
35
  import { addVolumeBoundingBox, VOLUME_BOUNDS_NAME, } from "./Loader/volumeBoundingBox";
36
36
  import { DEFAULT_AXES, ensureAxisExtracted, prepareVolumeSlices } from "./Loader/copperNrrdLoader";
37
+ import { rasDimensions } from "./Loader/rasDimensions";
37
38
  import { easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle, } from "./Controls/cameraTransitions";
38
39
  import { installFastSliceRepaint } from "./Loader/fastSliceRepaint";
39
40
  import { SurfaceAnnotator } from "./Utils/surfaceAnnotation";
@@ -41,6 +42,7 @@ import { CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_
41
42
  import { MAX_ENGINE_CHANNEL } from "./Utils/segmentation/core/index";
42
43
  import { REVISION as THREE_REVISION } from "three";
43
44
  import { checkThreeRevision } from "./Utils/threeRevisionCheck";
45
+ import { OrientationError, canonicalTransform, geometryFromNrrd, readNrrdOrientationFields, reorientVoxels, reorientedGeometry, viewLabels, } from "./Utils/orientation";
44
46
  import "./css/style.css";
45
47
  // __REVISION__ is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
46
48
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
@@ -69,5 +71,5 @@ if (typeof window !== "undefined") {
69
71
  if (typeof console !== "undefined") {
70
72
  console.log(`%cCopper3D Visualisation %c${REVISION}`, "padding: 3px;color:white; background:#023047", "padding: 3px;color:white; background:#f50a25");
71
73
  }
72
- export { copperRenderer, copperRendererOnDemond, copperMSceneRenderer, setHDRFilePath, addLabelToScene, convert3DPostoScreenPos, convertScreenPosto3DPos, addBoxHelper, fullScreenListenner, configKiwriousHeart, copperScene, copperSceneOnDemond, copperMScene, CameraViewPoint, kiwrious, loadKiwrious, NrrdTools, registerNiftiMaskGrid, loading, Copper3dTrackballControls, Copper3dOrbitControls, createTexture2D_NRRD, MeshNodeTool, throttle, removeGuiFolderChilden, MAX_ENGINE_CHANNEL, CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss, GaussianSmoother, SurfaceAnnotator, exposureExponent, DEFAULT_TARGET_GREY, disposeObject3D, disposeMaterial, collectFadeTargets, setFade, restoreFade, createSceneBudget, defaultBudgetBytes, disposeScene, removeSceneFromMap, fitDistance, fitView, isRotateEnabled, setRotateEnabled, isPanEnabled, setPanEnabled, isZoomEnabled, setZoomEnabled, beginGesture, isGestureActive, setCameraPose, addVolumeBoundingBox, VOLUME_BOUNDS_NAME, DEFAULT_AXES, ensureAxisExtracted, prepareVolumeSlices, copperGltfLoader, setDracoDecoderPath, setKTX2TranscoderPath, easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle, installFastSliceRepaint, };
74
+ export { copperRenderer, copperRendererOnDemond, copperMSceneRenderer, setHDRFilePath, addLabelToScene, convert3DPostoScreenPos, convertScreenPosto3DPos, addBoxHelper, fullScreenListenner, configKiwriousHeart, copperScene, copperSceneOnDemond, copperMScene, CameraViewPoint, kiwrious, loadKiwrious, NrrdTools, registerNiftiMaskGrid, loading, Copper3dTrackballControls, Copper3dOrbitControls, createTexture2D_NRRD, MeshNodeTool, throttle, removeGuiFolderChilden, MAX_ENGINE_CHANNEL, CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss, GaussianSmoother, SurfaceAnnotator, exposureExponent, DEFAULT_TARGET_GREY, disposeObject3D, disposeMaterial, collectFadeTargets, setFade, restoreFade, createSceneBudget, defaultBudgetBytes, disposeScene, removeSceneFromMap, fitDistance, fitView, isRotateEnabled, setRotateEnabled, isPanEnabled, setPanEnabled, isZoomEnabled, setZoomEnabled, beginGesture, isGestureActive, setCameraPose, addVolumeBoundingBox, VOLUME_BOUNDS_NAME, rasDimensions, DEFAULT_AXES, ensureAxisExtracted, prepareVolumeSlices, copperGltfLoader, setDracoDecoderPath, setKTX2TranscoderPath, easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle, installFastSliceRepaint, OrientationError, canonicalTransform, geometryFromNrrd, readNrrdOrientationFields, reorientVoxels, reorientedGeometry, viewLabels, };
73
75
  //# sourceMappingURL=index.js.map
package/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EACP,yBAAyB,EACzB,qBAAqB,EACrB,oBAAoB,EACpB,YAAY,EACZ,QAAQ,EACR,sBAAsB,EACtB,kBAAkB,EAClB,cAAc,EACd,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,kBAAkB,EAClB,OAAO,EACP,WAAW,EACX,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,EACZ,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,eAAe,EACf,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,aAAa,EACb,cAAc,EACd,YAAY,EACZ,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,eAAe,EACf,uBAAuB,GACxB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EACL,eAAe,EAGf,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,YAAY,EAAY,MAAM,2BAA2B,CAAC;AACnE,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,mBAAmB,EAAE,O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EACf,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,aAAa,EACb,cAAc,EACd,YAAY,EACZ,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,UAAU,GACX,CAAC"}
@@ -0,0 +1,276 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ /**
6
+ * The canonical voxel order, and the rule that puts any volume into it.
7
+ *
8
+ * Canonical order: voxel index i increases toward the patient's Left, j toward Posterior, k
9
+ * toward Superior. Axis codes use the TOWARD convention of DICOM, nibabel and SimpleITK, so "LPS"
10
+ * names that order (legacy ITK and ITK-SNAP call the same order "RAI").
11
+ *
12
+ * Each native axis is assigned the anatomical axis it is nearest to and flipped when it points the
13
+ * other way. That is a permutation and flips, never a resampling, so obliquity stays in the
14
+ * geometry instead of being snapped away. With the voxels in this order, the fixed per-axis display
15
+ * mapping (SliceRenderPipeline.flipDisplayImageByAxis) shows every volume in the radiological
16
+ * convention, whatever order its file stores.
17
+ *
18
+ * The backend (app/geometry/canonical.py) implements the same rule for everything it reads and
19
+ * writes. The app holds both to one fixture, annotator-backend/tests/fixtures/orientation_cases.json.
20
+ *
21
+ * Pure: no DOM and no three, so it runs inside the NRRD worker as well as on the main thread.
22
+ */
23
+ /** A volume whose patient orientation cannot be established. It is refused, never guessed. */
24
+ class OrientationError extends Error {
25
+ constructor(code, detail) {
26
+ super(`${code}: ${detail}`);
27
+ this.name = "OrientationError";
28
+ this.code = code;
29
+ this.detail = detail;
30
+ }
31
+ }
32
+ /** A screen axis more than 1 degree off an anatomical axis also gets that axis's letter (the rule
33
+ * of 3D Slicer's GetDirectionLabel). */
34
+ const LABEL_TOL = Math.sin((1 * Math.PI) / 180);
35
+ /** At 45 degrees an axis is equally near two anatomical axes, so it has no nearest one. */
36
+ const AMBIGUOUS_COS = Math.cos((45 * Math.PI) / 180) + 1e-9;
37
+ /** NRRD space -> the per-component signs that turn its coordinates into LPS. */
38
+ const LPS_SIGNS = {
39
+ "left-posterior-superior": [1, 1, 1],
40
+ lps: [1, 1, 1],
41
+ "right-anterior-superior": [-1, -1, 1],
42
+ ras: [-1, -1, 1],
43
+ "left-anterior-superior": [1, -1, 1],
44
+ las: [1, -1, 1],
45
+ };
46
+ const TIME_SPACES = new Set(["rast", "last", "lpst"]);
47
+ const NON_ANATOMICAL_SPACES = new Set(["3d-right-handed", "3d-left-handed"]);
48
+ /** TOWARD letter -> [patient axis in LPS, sign]. */
49
+ const LETTERS = {
50
+ L: [0, 1], R: [0, -1], P: [1, 1], A: [1, -1], S: [2, 1], I: [2, -1],
51
+ };
52
+ /**
53
+ * Each view's screen-right and screen-down steps in canonical index space, as
54
+ * SliceRenderPipeline.flipDisplayImageByAxis draws them. A layout change there changes this
55
+ * table in the same commit.
56
+ */
57
+ const VIEW_LAYOUT = {
58
+ z: [[1, 0, 0], [0, 1, 0]], // axial: right = +i, down = +j
59
+ y: [[1, 0, 0], [0, 0, -1]], // coronal: right = +i, down = -k
60
+ x: [[0, 1, 0], [0, 0, -1]], // sagittal: right = +j, down = -k
61
+ };
62
+ /** The longest header looked for; NRRD headers are a few hundred bytes. */
63
+ const MAX_HEADER_BYTES = 64 * 1024;
64
+ /**
65
+ * The text header of an NRRD document: everything before the first blank line. Read here instead
66
+ * of taken from three's NRRDLoader, which fills in identity directions when a file has none and so
67
+ * makes "no orientation" indistinguishable from "identity".
68
+ */
69
+ function nrrdHeaderText(buffer) {
70
+ const bytes = new Uint8Array(buffer, 0, Math.min(buffer.byteLength, MAX_HEADER_BYTES));
71
+ if (String.fromCharCode(...bytes.subarray(0, 4)) !== "NRRD")
72
+ throw new Error("not an NRRD document (no NRRD magic)");
73
+ for (let n = 0; n < bytes.length - 1; n++) {
74
+ if (bytes[n] !== 0x0a)
75
+ continue;
76
+ const blankLf = bytes[n + 1] === 0x0a;
77
+ const blankCrlf = bytes[n + 1] === 0x0d && bytes[n + 2] === 0x0a;
78
+ if (blankLf || blankCrlf) {
79
+ const end = n > 0 && bytes[n - 1] === 0x0d ? n - 1 : n;
80
+ return new TextDecoder("latin1").decode(bytes.subarray(0, end));
81
+ }
82
+ }
83
+ throw new Error("NRRD header has no terminating blank line");
84
+ }
85
+ /** Reads the orientation fields from an NRRD header's text. Comments and `key:=value` pairs are skipped. */
86
+ function readNrrdOrientationFields(headerText) {
87
+ var _a;
88
+ const out = { space: null, sizes: [], spaceDirections: null, spaceOrigin: null };
89
+ for (const line of headerText.split(/\r?\n/)) {
90
+ if (line.startsWith("#"))
91
+ continue;
92
+ const colon = line.indexOf(":");
93
+ if (colon < 0 || line[colon + 1] === "=")
94
+ continue;
95
+ const name = line.slice(0, colon).trim().toLowerCase();
96
+ const value = line.slice(colon + 1).trim();
97
+ if (name === "space")
98
+ out.space = value;
99
+ else if (name === "sizes")
100
+ out.sizes = value.split(/\s+/).map((n) => parseInt(n, 10));
101
+ else if (name === "space directions")
102
+ out.spaceDirections = parseVectors(value);
103
+ else if (name === "space origin")
104
+ out.spaceOrigin = (_a = parseVectors(value)[0]) !== null && _a !== void 0 ? _a : null;
105
+ }
106
+ return out;
107
+ }
108
+ /** An NRRD's geometry in LPS. Throws OrientationError when its patient orientation cannot be established. */
109
+ function geometryFromNrrd(fields) {
110
+ var _a;
111
+ const space = (_a = fields.space) === null || _a === void 0 ? void 0 : _a.trim();
112
+ if (!space) {
113
+ throw new OrientationError("no_space", "the header has no 'space' field, so its patient orientation is unknown");
114
+ }
115
+ const name = space.toLowerCase();
116
+ if (name.endsWith("-time") || TIME_SPACES.has(name)) {
117
+ throw new OrientationError("time_space", `space '${space}' is a time series; only 3D volumes are supported`);
118
+ }
119
+ if (name === "scanner-xyz") {
120
+ throw new OrientationError("scanner_space", "space 'scanner-xyz' is in scanner coordinates, whose patient orientation depends on how the patient lay (breast MRI is acquired prone)");
121
+ }
122
+ if (NON_ANATOMICAL_SPACES.has(name)) {
123
+ throw new OrientationError("non_anatomical_space", `space '${space}' has no anatomical meaning`);
124
+ }
125
+ const signs = LPS_SIGNS[name];
126
+ if (!signs)
127
+ throw new OrientationError("unknown_space", `space '${space}' is not a recognised anatomical space`);
128
+ const vectors = fields.spaceDirections;
129
+ if (!vectors || vectors.length === 0)
130
+ throw new OrientationError("no_directions", "the header has no 'space directions'");
131
+ if (fields.sizes.length !== 3 || vectors.length !== 3 || vectors.some((v) => v === null || v.length !== 3)) {
132
+ throw new OrientationError("not_3d", `expected 3 spatial axes, got sizes [${fields.sizes.join(", ")}]`);
133
+ }
134
+ if (!fields.spaceOrigin || fields.spaceOrigin.length !== 3) {
135
+ throw new OrientationError("no_origin", "the header has no 'space origin', so the grid has no patient position");
136
+ }
137
+ // "+ 0" turns a negated zero into 0, so a converted axis compares equal to the literal.
138
+ const directions = vectors.map((v) => v.map((c, x) => c * signs[x] + 0));
139
+ const origin = fields.spaceOrigin.map((c, x) => c * signs[x] + 0);
140
+ return checked({ dims: [fields.sizes[0], fields.sizes[1], fields.sizes[2]], directions, origin });
141
+ }
142
+ /** The transform into the voxel order that `codes` names (TOWARD), e.g. "LPS" or "RAI". */
143
+ function orientationTransform(geometry, codes = "LPS") {
144
+ const target = parseCodes(codes);
145
+ const spacing = spacingOf(geometry);
146
+ const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
147
+ const nearest = units.map((u) => [0, 1, 2].reduce((best, x) => (Math.abs(u[x]) > Math.abs(u[best]) ? x : best), 0));
148
+ const strength = units.map((u, a) => Math.abs(u[nearest[a]]));
149
+ const obliquity = strength.map((s) => (Math.acos(Math.min(1, s)) * 180) / Math.PI);
150
+ if (strength.some((s) => s <= AMBIGUOUS_COS) || new Set(nearest).size !== 3) {
151
+ throw new OrientationError("ambiguous_oblique", `a voxel axis is ${Math.max(...obliquity).toFixed(1)} degrees from every anatomical axis, so it has no nearest one`);
152
+ }
153
+ const perm = [0, 0, 0];
154
+ const flip = [false, false, false];
155
+ const obliquityDeg = [0, 0, 0];
156
+ target.forEach(([patientAxis, sign], axis) => {
157
+ const native = nearest.indexOf(patientAxis);
158
+ perm[axis] = native;
159
+ flip[axis] = Math.sign(units[native][patientAxis]) !== sign;
160
+ obliquityDeg[axis] = obliquity[native];
161
+ });
162
+ return { perm, flip, obliquityDeg };
163
+ }
164
+ /** The transform into the canonical order (i->L, j->P, k->S). */
165
+ function canonicalTransform(geometry) {
166
+ return orientationTransform(geometry, "LPS");
167
+ }
168
+ function isIdentityTransform(transform) {
169
+ return transform.perm[0] === 0 && transform.perm[1] === 1 && transform.perm[2] === 2 && !transform.flip.some(Boolean);
170
+ }
171
+ /** The same grid described in the transform's voxel order. The origin moves to the new first voxel. */
172
+ function reorientedGeometry(geometry, transform) {
173
+ const origin = [...geometry.origin];
174
+ transform.perm.forEach((native, axis) => {
175
+ if (!transform.flip[axis])
176
+ return;
177
+ for (let x = 0; x < 3; x++)
178
+ origin[x] += (geometry.dims[native] - 1) * geometry.directions[native][x];
179
+ });
180
+ return {
181
+ dims: transform.perm.map((native) => geometry.dims[native]),
182
+ // "+ 0" turns a negated zero into 0 (see geometryFromNrrd).
183
+ directions: transform.perm.map((native, axis) => geometry.directions[native].map((c) => (transform.flip[axis] ? -c : c) + 0)),
184
+ origin,
185
+ };
186
+ }
187
+ /**
188
+ * Voxels (i fastest, as NRRD stores them) rewritten in the transform's order. The identity
189
+ * returns `data` itself, with no copy; any other transform returns a new array of the same type.
190
+ */
191
+ function reorientVoxels(data, dims, transform) {
192
+ if (data.length !== dims[0] * dims[1] * dims[2]) {
193
+ throw new Error(`voxel count ${data.length} does not fill a ${dims.join("x")} grid`);
194
+ }
195
+ if (isIdentityTransform(transform))
196
+ return data;
197
+ const nativeStride = [1, dims[0], dims[0] * dims[1]];
198
+ const outDims = transform.perm.map((native) => dims[native]);
199
+ const step = transform.perm.map((native, axis) => (transform.flip[axis] ? -1 : 1) * nativeStride[native]);
200
+ let start = 0;
201
+ transform.perm.forEach((native, axis) => {
202
+ if (transform.flip[axis])
203
+ start += (dims[native] - 1) * nativeStride[native];
204
+ });
205
+ const out = new data.constructor(data.length);
206
+ let n = 0;
207
+ for (let c2 = 0, base2 = start; c2 < outDims[2]; c2++, base2 += step[2]) {
208
+ for (let c1 = 0, base1 = base2; c1 < outDims[1]; c1++, base1 += step[1]) {
209
+ for (let c0 = 0, index = base1; c0 < outDims[0]; c0++, index += step[0]) {
210
+ out[n++] = data[index];
211
+ }
212
+ }
213
+ }
214
+ return out;
215
+ }
216
+ /** The orientation letters at each screen edge of a view of a canonical grid. */
217
+ function viewLabels(axis, geometry) {
218
+ const spacing = spacingOf(geometry);
219
+ const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
220
+ const along = (step) => [0, 1, 2].map((x) => step[0] * units[0][x] + step[1] * units[1][x] + step[2] * units[2][x]);
221
+ const [rightStep, downStep] = VIEW_LAYOUT[axis];
222
+ const right = along(rightStep);
223
+ const down = along(downStep);
224
+ const negate = (v) => v.map((c) => -c);
225
+ return { left: letters(negate(right)), right: letters(right), top: letters(negate(down)), bottom: letters(down) };
226
+ }
227
+ function spacingOf(geometry) {
228
+ return geometry.directions.map((d) => Math.hypot(d[0], d[1], d[2]));
229
+ }
230
+ function letters(direction) {
231
+ return [0, 1, 2]
232
+ .filter((x) => Math.abs(direction[x]) > LABEL_TOL)
233
+ .sort((a, b) => Math.abs(direction[b]) - Math.abs(direction[a]))
234
+ .map((x) => (direction[x] > 0 ? "LPS" : "RAI")[x])
235
+ .join("");
236
+ }
237
+ function parseCodes(codes) {
238
+ if (codes.length !== 3 || [...codes].some((c) => !(c in LETTERS))) {
239
+ throw new Error(`not a three-letter orientation code: '${codes}'`);
240
+ }
241
+ const target = [...codes].map((c) => LETTERS[c]);
242
+ if (new Set(target.map(([patientAxis]) => patientAxis)).size !== 3) {
243
+ throw new Error(`orientation code '${codes}' names a patient axis twice`);
244
+ }
245
+ return target;
246
+ }
247
+ function parseVectors(text) {
248
+ const out = [];
249
+ for (const match of text.matchAll(/\(([^)]*)\)|none/gi)) {
250
+ out.push(match[1] === undefined ? null : match[1].split(",").map((c) => parseFloat(c)));
251
+ }
252
+ return out;
253
+ }
254
+ function checked(geometry) {
255
+ const values = [...geometry.directions.flat(), ...geometry.origin];
256
+ if (values.some((v) => !Number.isFinite(v))) {
257
+ throw new OrientationError("degenerate", "the geometry contains non-finite values");
258
+ }
259
+ const spacing = spacingOf(geometry);
260
+ if (spacing.some((s) => s <= 1e-12) || geometry.dims.some((n) => !(n >= 1))) {
261
+ throw new OrientationError("degenerate", `a voxel axis has no extent (dims [${geometry.dims.join(", ")}], spacing [${spacing.join(", ")}])`);
262
+ }
263
+ return geometry;
264
+ }
265
+
266
+ exports.OrientationError = OrientationError;
267
+ exports.canonicalTransform = canonicalTransform;
268
+ exports.geometryFromNrrd = geometryFromNrrd;
269
+ exports.isIdentityTransform = isIdentityTransform;
270
+ exports.nrrdHeaderText = nrrdHeaderText;
271
+ exports.orientationTransform = orientationTransform;
272
+ exports.readNrrdOrientationFields = readNrrdOrientationFields;
273
+ exports.reorientVoxels = reorientVoxels;
274
+ exports.reorientedGeometry = reorientedGeometry;
275
+ exports.spacingOf = spacingOf;
276
+ exports.viewLabels = viewLabels;
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The canonical voxel order, and the rule that puts any volume into it.
3
+ *
4
+ * Canonical order: voxel index i increases toward the patient's Left, j toward Posterior, k
5
+ * toward Superior. Axis codes use the TOWARD convention of DICOM, nibabel and SimpleITK, so "LPS"
6
+ * names that order (legacy ITK and ITK-SNAP call the same order "RAI").
7
+ *
8
+ * Each native axis is assigned the anatomical axis it is nearest to and flipped when it points the
9
+ * other way. That is a permutation and flips, never a resampling, so obliquity stays in the
10
+ * geometry instead of being snapped away. With the voxels in this order, the fixed per-axis display
11
+ * mapping (SliceRenderPipeline.flipDisplayImageByAxis) shows every volume in the radiological
12
+ * convention, whatever order its file stores.
13
+ *
14
+ * The backend (app/geometry/canonical.py) implements the same rule for everything it reads and
15
+ * writes. The app holds both to one fixture, annotator-backend/tests/fixtures/orientation_cases.json.
16
+ *
17
+ * Pure: no DOM and no three, so it runs inside the NRRD worker as well as on the main thread.
18
+ */
19
+ /** A volume whose patient orientation cannot be established. It is refused, never guessed. */
20
+ class OrientationError extends Error {
21
+ constructor(code, detail) {
22
+ super(`${code}: ${detail}`);
23
+ this.name = "OrientationError";
24
+ this.code = code;
25
+ this.detail = detail;
26
+ }
27
+ }
28
+ /** A screen axis more than 1 degree off an anatomical axis also gets that axis's letter (the rule
29
+ * of 3D Slicer's GetDirectionLabel). */
30
+ const LABEL_TOL = Math.sin((1 * Math.PI) / 180);
31
+ /** At 45 degrees an axis is equally near two anatomical axes, so it has no nearest one. */
32
+ const AMBIGUOUS_COS = Math.cos((45 * Math.PI) / 180) + 1e-9;
33
+ /** NRRD space -> the per-component signs that turn its coordinates into LPS. */
34
+ const LPS_SIGNS = {
35
+ "left-posterior-superior": [1, 1, 1],
36
+ lps: [1, 1, 1],
37
+ "right-anterior-superior": [-1, -1, 1],
38
+ ras: [-1, -1, 1],
39
+ "left-anterior-superior": [1, -1, 1],
40
+ las: [1, -1, 1],
41
+ };
42
+ const TIME_SPACES = new Set(["rast", "last", "lpst"]);
43
+ const NON_ANATOMICAL_SPACES = new Set(["3d-right-handed", "3d-left-handed"]);
44
+ /** TOWARD letter -> [patient axis in LPS, sign]. */
45
+ const LETTERS = {
46
+ L: [0, 1], R: [0, -1], P: [1, 1], A: [1, -1], S: [2, 1], I: [2, -1],
47
+ };
48
+ /**
49
+ * Each view's screen-right and screen-down steps in canonical index space, as
50
+ * SliceRenderPipeline.flipDisplayImageByAxis draws them. A layout change there changes this
51
+ * table in the same commit.
52
+ */
53
+ const VIEW_LAYOUT = {
54
+ z: [[1, 0, 0], [0, 1, 0]], // axial: right = +i, down = +j
55
+ y: [[1, 0, 0], [0, 0, -1]], // coronal: right = +i, down = -k
56
+ x: [[0, 1, 0], [0, 0, -1]], // sagittal: right = +j, down = -k
57
+ };
58
+ /** The longest header looked for; NRRD headers are a few hundred bytes. */
59
+ const MAX_HEADER_BYTES = 64 * 1024;
60
+ /**
61
+ * The text header of an NRRD document: everything before the first blank line. Read here instead
62
+ * of taken from three's NRRDLoader, which fills in identity directions when a file has none and so
63
+ * makes "no orientation" indistinguishable from "identity".
64
+ */
65
+ function nrrdHeaderText(buffer) {
66
+ const bytes = new Uint8Array(buffer, 0, Math.min(buffer.byteLength, MAX_HEADER_BYTES));
67
+ if (String.fromCharCode(...bytes.subarray(0, 4)) !== "NRRD")
68
+ throw new Error("not an NRRD document (no NRRD magic)");
69
+ for (let n = 0; n < bytes.length - 1; n++) {
70
+ if (bytes[n] !== 0x0a)
71
+ continue;
72
+ const blankLf = bytes[n + 1] === 0x0a;
73
+ const blankCrlf = bytes[n + 1] === 0x0d && bytes[n + 2] === 0x0a;
74
+ if (blankLf || blankCrlf) {
75
+ const end = n > 0 && bytes[n - 1] === 0x0d ? n - 1 : n;
76
+ return new TextDecoder("latin1").decode(bytes.subarray(0, end));
77
+ }
78
+ }
79
+ throw new Error("NRRD header has no terminating blank line");
80
+ }
81
+ /** Reads the orientation fields from an NRRD header's text. Comments and `key:=value` pairs are skipped. */
82
+ function readNrrdOrientationFields(headerText) {
83
+ var _a;
84
+ const out = { space: null, sizes: [], spaceDirections: null, spaceOrigin: null };
85
+ for (const line of headerText.split(/\r?\n/)) {
86
+ if (line.startsWith("#"))
87
+ continue;
88
+ const colon = line.indexOf(":");
89
+ if (colon < 0 || line[colon + 1] === "=")
90
+ continue;
91
+ const name = line.slice(0, colon).trim().toLowerCase();
92
+ const value = line.slice(colon + 1).trim();
93
+ if (name === "space")
94
+ out.space = value;
95
+ else if (name === "sizes")
96
+ out.sizes = value.split(/\s+/).map((n) => parseInt(n, 10));
97
+ else if (name === "space directions")
98
+ out.spaceDirections = parseVectors(value);
99
+ else if (name === "space origin")
100
+ out.spaceOrigin = (_a = parseVectors(value)[0]) !== null && _a !== void 0 ? _a : null;
101
+ }
102
+ return out;
103
+ }
104
+ /** An NRRD's geometry in LPS. Throws OrientationError when its patient orientation cannot be established. */
105
+ function geometryFromNrrd(fields) {
106
+ var _a;
107
+ const space = (_a = fields.space) === null || _a === void 0 ? void 0 : _a.trim();
108
+ if (!space) {
109
+ throw new OrientationError("no_space", "the header has no 'space' field, so its patient orientation is unknown");
110
+ }
111
+ const name = space.toLowerCase();
112
+ if (name.endsWith("-time") || TIME_SPACES.has(name)) {
113
+ throw new OrientationError("time_space", `space '${space}' is a time series; only 3D volumes are supported`);
114
+ }
115
+ if (name === "scanner-xyz") {
116
+ throw new OrientationError("scanner_space", "space 'scanner-xyz' is in scanner coordinates, whose patient orientation depends on how the patient lay (breast MRI is acquired prone)");
117
+ }
118
+ if (NON_ANATOMICAL_SPACES.has(name)) {
119
+ throw new OrientationError("non_anatomical_space", `space '${space}' has no anatomical meaning`);
120
+ }
121
+ const signs = LPS_SIGNS[name];
122
+ if (!signs)
123
+ throw new OrientationError("unknown_space", `space '${space}' is not a recognised anatomical space`);
124
+ const vectors = fields.spaceDirections;
125
+ if (!vectors || vectors.length === 0)
126
+ throw new OrientationError("no_directions", "the header has no 'space directions'");
127
+ if (fields.sizes.length !== 3 || vectors.length !== 3 || vectors.some((v) => v === null || v.length !== 3)) {
128
+ throw new OrientationError("not_3d", `expected 3 spatial axes, got sizes [${fields.sizes.join(", ")}]`);
129
+ }
130
+ if (!fields.spaceOrigin || fields.spaceOrigin.length !== 3) {
131
+ throw new OrientationError("no_origin", "the header has no 'space origin', so the grid has no patient position");
132
+ }
133
+ // "+ 0" turns a negated zero into 0, so a converted axis compares equal to the literal.
134
+ const directions = vectors.map((v) => v.map((c, x) => c * signs[x] + 0));
135
+ const origin = fields.spaceOrigin.map((c, x) => c * signs[x] + 0);
136
+ return checked({ dims: [fields.sizes[0], fields.sizes[1], fields.sizes[2]], directions, origin });
137
+ }
138
+ /** The transform into the voxel order that `codes` names (TOWARD), e.g. "LPS" or "RAI". */
139
+ function orientationTransform(geometry, codes = "LPS") {
140
+ const target = parseCodes(codes);
141
+ const spacing = spacingOf(geometry);
142
+ const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
143
+ const nearest = units.map((u) => [0, 1, 2].reduce((best, x) => (Math.abs(u[x]) > Math.abs(u[best]) ? x : best), 0));
144
+ const strength = units.map((u, a) => Math.abs(u[nearest[a]]));
145
+ const obliquity = strength.map((s) => (Math.acos(Math.min(1, s)) * 180) / Math.PI);
146
+ if (strength.some((s) => s <= AMBIGUOUS_COS) || new Set(nearest).size !== 3) {
147
+ throw new OrientationError("ambiguous_oblique", `a voxel axis is ${Math.max(...obliquity).toFixed(1)} degrees from every anatomical axis, so it has no nearest one`);
148
+ }
149
+ const perm = [0, 0, 0];
150
+ const flip = [false, false, false];
151
+ const obliquityDeg = [0, 0, 0];
152
+ target.forEach(([patientAxis, sign], axis) => {
153
+ const native = nearest.indexOf(patientAxis);
154
+ perm[axis] = native;
155
+ flip[axis] = Math.sign(units[native][patientAxis]) !== sign;
156
+ obliquityDeg[axis] = obliquity[native];
157
+ });
158
+ return { perm, flip, obliquityDeg };
159
+ }
160
+ /** The transform into the canonical order (i->L, j->P, k->S). */
161
+ function canonicalTransform(geometry) {
162
+ return orientationTransform(geometry, "LPS");
163
+ }
164
+ function isIdentityTransform(transform) {
165
+ return transform.perm[0] === 0 && transform.perm[1] === 1 && transform.perm[2] === 2 && !transform.flip.some(Boolean);
166
+ }
167
+ /** The same grid described in the transform's voxel order. The origin moves to the new first voxel. */
168
+ function reorientedGeometry(geometry, transform) {
169
+ const origin = [...geometry.origin];
170
+ transform.perm.forEach((native, axis) => {
171
+ if (!transform.flip[axis])
172
+ return;
173
+ for (let x = 0; x < 3; x++)
174
+ origin[x] += (geometry.dims[native] - 1) * geometry.directions[native][x];
175
+ });
176
+ return {
177
+ dims: transform.perm.map((native) => geometry.dims[native]),
178
+ // "+ 0" turns a negated zero into 0 (see geometryFromNrrd).
179
+ directions: transform.perm.map((native, axis) => geometry.directions[native].map((c) => (transform.flip[axis] ? -c : c) + 0)),
180
+ origin,
181
+ };
182
+ }
183
+ /**
184
+ * Voxels (i fastest, as NRRD stores them) rewritten in the transform's order. The identity
185
+ * returns `data` itself, with no copy; any other transform returns a new array of the same type.
186
+ */
187
+ function reorientVoxels(data, dims, transform) {
188
+ if (data.length !== dims[0] * dims[1] * dims[2]) {
189
+ throw new Error(`voxel count ${data.length} does not fill a ${dims.join("x")} grid`);
190
+ }
191
+ if (isIdentityTransform(transform))
192
+ return data;
193
+ const nativeStride = [1, dims[0], dims[0] * dims[1]];
194
+ const outDims = transform.perm.map((native) => dims[native]);
195
+ const step = transform.perm.map((native, axis) => (transform.flip[axis] ? -1 : 1) * nativeStride[native]);
196
+ let start = 0;
197
+ transform.perm.forEach((native, axis) => {
198
+ if (transform.flip[axis])
199
+ start += (dims[native] - 1) * nativeStride[native];
200
+ });
201
+ const out = new data.constructor(data.length);
202
+ let n = 0;
203
+ for (let c2 = 0, base2 = start; c2 < outDims[2]; c2++, base2 += step[2]) {
204
+ for (let c1 = 0, base1 = base2; c1 < outDims[1]; c1++, base1 += step[1]) {
205
+ for (let c0 = 0, index = base1; c0 < outDims[0]; c0++, index += step[0]) {
206
+ out[n++] = data[index];
207
+ }
208
+ }
209
+ }
210
+ return out;
211
+ }
212
+ /** The orientation letters at each screen edge of a view of a canonical grid. */
213
+ function viewLabels(axis, geometry) {
214
+ const spacing = spacingOf(geometry);
215
+ const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
216
+ const along = (step) => [0, 1, 2].map((x) => step[0] * units[0][x] + step[1] * units[1][x] + step[2] * units[2][x]);
217
+ const [rightStep, downStep] = VIEW_LAYOUT[axis];
218
+ const right = along(rightStep);
219
+ const down = along(downStep);
220
+ const negate = (v) => v.map((c) => -c);
221
+ return { left: letters(negate(right)), right: letters(right), top: letters(negate(down)), bottom: letters(down) };
222
+ }
223
+ function spacingOf(geometry) {
224
+ return geometry.directions.map((d) => Math.hypot(d[0], d[1], d[2]));
225
+ }
226
+ function letters(direction) {
227
+ return [0, 1, 2]
228
+ .filter((x) => Math.abs(direction[x]) > LABEL_TOL)
229
+ .sort((a, b) => Math.abs(direction[b]) - Math.abs(direction[a]))
230
+ .map((x) => (direction[x] > 0 ? "LPS" : "RAI")[x])
231
+ .join("");
232
+ }
233
+ function parseCodes(codes) {
234
+ if (codes.length !== 3 || [...codes].some((c) => !(c in LETTERS))) {
235
+ throw new Error(`not a three-letter orientation code: '${codes}'`);
236
+ }
237
+ const target = [...codes].map((c) => LETTERS[c]);
238
+ if (new Set(target.map(([patientAxis]) => patientAxis)).size !== 3) {
239
+ throw new Error(`orientation code '${codes}' names a patient axis twice`);
240
+ }
241
+ return target;
242
+ }
243
+ function parseVectors(text) {
244
+ const out = [];
245
+ for (const match of text.matchAll(/\(([^)]*)\)|none/gi)) {
246
+ out.push(match[1] === undefined ? null : match[1].split(",").map((c) => parseFloat(c)));
247
+ }
248
+ return out;
249
+ }
250
+ function checked(geometry) {
251
+ const values = [...geometry.directions.flat(), ...geometry.origin];
252
+ if (values.some((v) => !Number.isFinite(v))) {
253
+ throw new OrientationError("degenerate", "the geometry contains non-finite values");
254
+ }
255
+ const spacing = spacingOf(geometry);
256
+ if (spacing.some((s) => s <= 1e-12) || geometry.dims.some((n) => !(n >= 1))) {
257
+ throw new OrientationError("degenerate", `a voxel axis has no extent (dims [${geometry.dims.join(", ")}], spacing [${spacing.join(", ")}])`);
258
+ }
259
+ return geometry;
260
+ }
261
+
262
+ export { OrientationError, canonicalTransform, geometryFromNrrd, isIdentityTransform, nrrdHeaderText, orientationTransform, readNrrdOrientationFields, reorientVoxels, reorientedGeometry, spacingOf, viewLabels };
@@ -53,10 +53,10 @@ export declare function computeFraming(box: THREE.Box3, fovDeg: number): Framing
53
53
  * distance comes from C5 auto-framing (the implicit 600 in the JSON is ignored).
54
54
  *
55
55
  * up must be Gram-Schmidt-orthogonalised against the view direction (decision D1):
56
- * OrbitControls uses camera.up as its polar axis, and nrrd_view_coronal.json's up
57
- * (0,1,-1) is not perpendicular to its own view direction (0,1,0) — feeding it raw
58
- * gives a 45-degree-tilted pole. The old trackball path got away with it only because
59
- * three's lookAt() orthogonalises internally.
56
+ * OrbitControls uses camera.up as its polar axis, and a preset whose up is not
57
+ * perpendicular to its own view direction would otherwise get a tilted pole. The
58
+ * old trackball path got away with that only because three's lookAt() orthogonalises
59
+ * internally.
60
60
  */
61
61
  export declare function resolveViewPose(preset: CameraViewPreset, pivot: THREE.Vector3, dist: number): ViewPose;
62
62
  /**