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
@@ -0,0 +1,427 @@
1
+ (function(f,P){typeof exports=="object"&&typeof module<"u"?P(exports,require("@cornerstonejs/dicom-codec"),require("dicom-parser"),require("three")):typeof define=="function"&&define.amd?define(["exports","@cornerstonejs/dicom-codec","dicom-parser","three"],P):(f=typeof globalThis<"u"?globalThis:f||self,P(f.DicomThree={},f.dicomCodec,f.dicomParser,f.THREE))})(this,function(f,P,C,v){"use strict";var ot=Object.defineProperty;var st=(f,P,C)=>P in f?ot(f,P,{enumerable:!0,configurable:!0,writable:!0,value:C}):f[P]=C;var a=(f,P,C)=>st(f,typeof P!="symbol"?P+"":P,C);var J=typeof document<"u"?document.currentScript:null;function Ie(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const u=Ie(v);class K{constructor(t){a(this,"_dataSet");a(this,"_arrayBuffer");this._arrayBuffer=t.buffer;try{const e=new Uint8Array(this._arrayBuffer);this._dataSet=C.parseDicom(e)}catch(e){throw console.log(e),new Error("parsers.dicom could not parse the file")}}get seriesInstanceUID(){return this._dataSet.string("x0020000e")??null}get frameOfReferenceUID(){return this._dataSet.string("x00200052")??null}temporalPosition(t=0){var e;return((e=this._findInGroupSequence("x52009230","x00209111",t))==null?void 0:e.uint32("x00209128"))??this._dataSet.intString("x00200100")??null}stackId(t=0){var e;return((e=this._findInGroupSequence("x52009230","x00209111",t))==null?void 0:e.string("x00209056"))??null}get studyInstanceUID(){return this._dataSet.string("x0020000d")??null}get modality(){return this._dataSet.string("x00080060")??null}get segmentationType(){return this._dataSet.string("x00620001")??null}get segmentationSegments(){const t=[],e=this._dataSet.elements.x00620002;if(!e||!e.items)return t;for(const n of e.items){if(!n.dataSet)continue;const r=this._recommendedDisplayCIELab({dataSet:n.dataSet}),o=this._segmentationCode({dataSet:n.dataSet}),s=n.dataSet.uint16("x00620004"),l=n.dataSet.string("x00620005"),c=n.dataSet.string("x00620008");t.push({recommendedDisplayCIELab:r,segmentationCodeDesignator:o.segmentationCodeDesignator,segmentationCodeValue:o.segmentationCodeValue,segmentationCodeMeaning:o.segmentationCodeMeaning,segmentNumber:s||null,segmentLabel:l||null,segmentAlgorithmType:c||null})}return t}_segmentationCode(t){const e=t.dataSet.elements.x00082218;if(e&&e.items&&e.items.length>0){const n=e.items[0].dataSet;if(n)return{segmentationCodeDesignator:n.string("x00080102")||"unknown",segmentationCodeValue:n.string("x00080100")||"unknown",segmentationCodeMeaning:n.string("x00080104")||"unknown"}}return{segmentationCodeDesignator:"unknown",segmentationCodeValue:"unknown",segmentationCodeMeaning:"unknown"}}_recommendedDisplayCIELab(t){if(!t.dataSet.elements.x0062000d)return null;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);for(let l=0;l<n/2;l++)o[l]=(r[2*l+1]<<8)+r[2*l];return[o[0]/65535*100,o[1]/65535*255-128,o[2]/65535*255-128]}get rawHeader(){return this._dataSet}sopInstanceUID(t=0){return this._findStringEverywhere("x2005140f","x00080018",t)}get transferSyntaxUID(){return this._dataSet.string("x00020010")??null}get studyDate(){return this._dataSet.string("x00080020")??null}get studyDescription(){return this._dataSet.string("x00081030")??null}get seriesDate(){return this._dataSet.string("x00080021")??null}get seriesDescription(){return this._dataSet.string("x0008103e")??null}get patientName(){return this._dataSet.string("x00100010")??null}get patientID(){return this._dataSet.string("x00100020")??null}get patientBirthdate(){return this._dataSet.string("x00100030")??null}get patientSex(){return this._dataSet.string("x00100040")??null}get patientAge(){return this._dataSet.string("x00101010")??null}get photometricInterpretation(){return this._dataSet.string("x00280004")??null}get planarConfiguration(){return this._dataSet.uint16("x00280006")??null}get samplesPerPixel(){return this._dataSet.uint16("x00280002")??null}get numberOfFrames(){return this._dataSet.intString("x00280008")}get numberOfChannels(){let t=1,e=this.photometricInterpretation;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}invert(){return this.photometricInterpretation==="MONOCHROME1"}imageOrientation(t=0){const e=this._findStringEverywhere("x00209116","x00200037",t);return e?e.split("\\").map(parseFloat):null}referencedSegmentNumber(t=0){let e=this._findInGroupSequence("x52009230","x0062000a",t);return e?e.uint16("x0062000b"):-1}get pixelAspectRatio(){const t=[this._dataSet.intString("x00280034",0),this._dataSet.intString("x00280034",1)];if(!(typeof t[0]>"u"))return t}imagePosition(t=0){const e=this._findStringEverywhere("x00209113","x00200032",t);return e?e.split("\\").map(parseFloat):null}hasPerFrameImagePosition(t=0){var e;return((e=this._findInGroupSequence("x52009230","x00209113",t))==null?void 0:e.string("x00200032"))!==void 0}instanceNumber(t=0){var r,o;let e=null;const n=this._dataSet.elements.x52009230;if(n!=null&&n.items&&((r=n.items[t])!=null&&r.dataSet)){const s=n.items[t].dataSet.elements.x2005140f;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}else e=this._dataSet.intString("x00200013")??null;return e}pixelSpacing(t=0){const e=this._findStringEverywhere("x00289110","x00280030",t),n=this._dataSet.string("x00181164"),r=e||n||null;if(r){const o=r.split("\\");return o.length!==2?(console.error(`DICOM spacing format is not supported (could not split string on "\\"): ${r}`),null):o.map(parseFloat)}return null}ultrasoundRegions(t=0){const e=this._dataSet.elements.x00186011;if(!(e!=null&&e.items))return[];const n=[];return e.items.forEach(r=>{r.dataSet&&n.push({x0:r.dataSet.uint32("x00186018")??null,y0:r.dataSet.uint32("x0018601a")??null,x1:r.dataSet.uint32("x0018601c")??null,y1:r.dataSet.uint32("x0018601e")??null,axisX:r.dataSet.int32("x00186020")??null,axisY:r.dataSet.int32("x00186022")??null,unitsX:this._getUnitsName(r.dataSet.uint16("x00186024")??0),unitsY:this._getUnitsName(r.dataSet.uint16("x00186026")??0),deltaX:r.dataSet.double("x0018602c")??null,deltaY:r.dataSet.double("x0018602e")??null})}),n}get frameTime(){const t=this._dataSet.uint16("x00280009",1);let e=this._dataSet.intString("x00082144");if(typeof t=="number"){const n=t.toString(16),r=this._dataSet.floatString("x0018"+n);if(r!==void 0)return r}if(typeof e=="number")return 1e3/e}get rows(){return this._dataSet.uint16("x00280010")}get columns(){return this._dataSet.uint16("x00280011")}get pixelType(){return 0}get pixelRepresentation(){return this._dataSet.uint16("x00280103")}get pixelPaddingValue(){return this._dataSet.int16("x00280120")}get bitsAllocated(){return this._dataSet.uint16("x00280100")}get highBit(){return this._dataSet.uint16("x00280102")}rescaleIntercept(t=0){return this._findFloatStringInFrameGroupSequence("x00289145","x00281052",t)}rescaleSlope(t=0){return this._findFloatStringInFrameGroupSequence("x00289145","x00281053",t)}windowCenter(t=0){return this._findFloatStringInFrameGroupSequence("x00289132","x00281050",t)}windowWidth(t=0){return this._findFloatStringInFrameGroupSequence("x00289132","x00281051",t)}sliceThickness(t=0){return this._findFloatStringInFrameGroupSequence("x00289110","x00180050",t)}spacingBetweenSlices(t=0){return this._findFloatStringInFrameGroupSequence("x00289110","x00180088",t)}dimensionIndexValues(t=0){var r,o;let e=null;const n=this._dataSet.elements.x52009230;if(n!=null&&n.items&&((r=n.items[t])!=null&&r.dataSet)){const s=n.items[t].dataSet.elements.x00209111;if(s!=null&&s.items&&((o=s.items[0])!=null&&o.dataSet)){const l=s.items[0].dataSet.elements.x00209157;if(l){const c=l.length/4;e=[];for(let m=0;m<c;m++)e.push(s.items[0].dataSet.uint32("x00209157",m)??0)}}}return e}inStackPositionNumber(t=0){var r,o;let e=null;const n=this._dataSet.elements.x52009230;if(n!=null&&n.items&&((r=n.items[t])!=null&&r.dataSet)){const s=n.items[t].dataSet.elements.x00209111;s!=null&&s.items&&((o=s.items[0])!=null&&o.dataSet)&&(e=s.items[0].dataSet.uint32("x00209057")??null)}return e}stackID(t=0){var r,o,s;let e=null;const n=this._dataSet.elements.x52009230;if(n!=null&&n.items&&((r=n.items[t])!=null&&r.dataSet)){const l=n.items[t].dataSet.elements.x00209111;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)}return e}get distanceSourceToDetector(){return this._dataSet.floatString("x00181110")}get distanceSourceToPatient(){return this._dataSet.floatString("x00181111")}get positionerPrimaryAngle(){return this._dataSet.floatString("x00181510")}get positionerSecondaryAngle(){return this._dataSet.floatString("x00181511")}async extractPixelData(){return await this._decodePixelData()}_findInGroupSequence(t,e,n){var o,s;const r=this._dataSet.elements[t];if(r!=null&&r.items&&((o=r.items[n])!=null&&o.dataSet)){const l=r.items[n].dataSet.elements[e];if(l!=null&&l.items&&((s=l.items[0])!=null&&s.dataSet))return l.items[0].dataSet}return null}_findStringInGroupSequence(t,e,n,r){const o=this._findInGroupSequence(t,e,r);return(o==null?void 0:o.string(n))??null}_findStringInFrameGroupSequence(t,e,n){return this._findStringInGroupSequence("x52009230",t,e,n)??this._findStringInGroupSequence("x52009229",t,e,0)}_findStringEverywhere(t,e,n){let r=this._findStringInFrameGroupSequence(t,e,n);return r||(r=this._findStringInSequence("x00540022",e)),r||(r=this._dataSet.string(e)??null),r}_findStringInSequence(t,e){var r;const n=this._dataSet.elements[t];return n!=null&&n.items&&((r=n.items[0])!=null&&r.dataSet)?n.items[0].dataSet.string(e)??null:null}_findFloatStringInFrameGroupSequence(t,e,n){var r,o;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}async _decodePixelData(){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;return await P.decode(n,{rows:s,columns:o,bitsAllocated:r,samplesPerPixel:l,signed:c},t)}_interpretAsRGB(t){return["RGB","YBR_RCT","YBR_ICT","YBR_FULL_422"].indexOf(t)!==-1}_convertColorSpace(t){let e=null;const n=this.photometricInterpretation;let r=this.planarConfiguration;r===null&&(r=0,window.console.log("Planar Configuration was not set and was defaulted to 0"));const o=n?this._interpretAsRGB(n):!1;if(o&&r===0)e=t;else if(o&&r===1){if(t instanceof Int8Array)e=new Int8Array(t.length);else if(t instanceof Uint8Array)e=new Uint8Array(t.length);else if(t instanceof Int16Array)e=new Int16Array(t.length);else if(t instanceof Uint16Array)e=new Uint16Array(t.length);else throw new Error(`Unsupported typed array: ${t}`);let s=t.length/3,l=0,c=0,m=s,d=s*2;for(let g=0;g<s;g++)e[l++]=t[c++],e[l++]=t[m++],e[l++]=t[d++]}else if(n==="YBR_FULL"){if(t instanceof Int8Array)e=new Int8Array(t.length);else if(t instanceof Uint8Array)e=new Uint8Array(t.length);else if(t instanceof Int16Array)e=new Int16Array(t.length);else if(t instanceof Uint16Array)e=new Uint16Array(t.length);else throw new Error(`unsuported typed array: ${t}`);let s=t.length/3,l=0,c=0;for(let m=0;m<s;m++){let d=t[l++],g=t[l++],w=t[l++];e[c++]=d+1.402*(w-128),e[c++]=d-.34414*(g-128)-.71414*(w-128),e[c++]=d+1.772*(g-128)}}else throw new Error(`photometric interpolation not supported: ${n}`);return e}_getUnitsName(t){return{0:"none",1:"percent",2:"dB",3:"cm",4:"seconds",5:"hertz",6:"dB/seconds",7:"cm/sec",8:"cm2",9:"cm2/sec",10:"cm3",11:"cm3/sec",12:"degrees"}[t]??"none"}}class De extends u.Loader{constructor(t){super(t)}load(t,e,n,r){const o=new u.FileLoader(this.manager);o.setResponseType("arraybuffer"),o.load(t,s=>{try{const l=new K({buffer:s});e==null||e(l)}catch(l){console.error("Ошибка парсинга DICOM:",l),r==null||r(l)}},n,r)}async loadAsync(t){const e=new u.FileLoader(this.manager);return e.setResponseType("arraybuffer"),new Promise((n,r)=>{e.load(t,o=>{try{n(new K({buffer:o}))}catch(s){r(s)}},void 0,r)})}async loadMultipleAsync(t){const e=t.map(async r=>{const o=URL.createObjectURL(r);try{const s=await this.loadAsync(o);return console.log(`✅ DICOM загружен: ${r.name}`),s}catch(s){return console.error(`❌ Ошибка загрузки файла ${r.name}:`,s),null}finally{URL.revokeObjectURL(o)}});return(await Promise.all(e)).filter(r=>r!==null)}async loadMultipleSeriesAsync(t){const e=t.map(async r=>{const o=r.dicomFiles.map(s=>s.file);return this.loadMultipleAsync(o)});return(await Promise.all(e)).filter(r=>r.length>0)}}const V=1e-4;function O(i){if(i.length!==6||!i.every(Number.isFinite))throw new Error("Invalid ImageOrientationPatient");const t=Math.hypot(...i.slice(0,3)),e=Math.hypot(...i.slice(3));if(Math.abs(t-1)>V||Math.abs(e-1)>V||Math.abs(i[0]*i[3]+i[1]*i[4]+i[2]*i[5])>V)throw new Error("ImageOrientationPatient must contain orthonormal direction cosines");return i.map((n,r)=>n/(r<3?t:e))}function oe(i){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);return t.map(n=>n/e)}function k(i,t){return i[0]*t[0]+i[1]*t[1]+i[2]*t[2]}function H(i,t=!0){let e;if(t&&i.length&&i.every(r=>{var o;return((o=r.imagePosition)==null?void 0:o.length)===3&&r.imagePosition.every(Number.isFinite)&&r.imageOrientation}))try{const r=i.reduce((s,l)=>s.id<l.id?s:l),o=O(r.imageOrientation);i.every(s=>O(s.imageOrientation).every((l,c)=>Math.abs(l-o[c])<=V))&&(e=oe(o))}catch{}const n=e?r=>k(r.imagePosition,e):i.every(r=>Number.isFinite(r.instanceNumber))?r=>r.instanceNumber:i.every(r=>Number.isFinite(r.sliceLocation))?r=>r.sliceLocation:()=>0;return[...i].sort((r,o)=>n(r)-n(o)||(r.id<o.id?-1:r.id>o.id?1:0))}const Fe=i=>{const t=i.every(e=>{var n;return((n=e.modality)==null?void 0:n.toUpperCase())!=="XA"&&e.numberOfFrames===1});return H(i.map(e=>({...e,id:`${e.SOPInstanceUID}:${e.file.name}`})),t).map(({id:e,...n})=>n)};function se(i,t,e){var n,r,o,s,l,c,m;for(const d of["x52009230","x52009229"]){const g=(o=(r=(n=i.elements[d])==null?void 0:n.items)==null?void 0:r[0])==null?void 0:o.dataSet,w=(m=(c=(l=(s=g==null?void 0:g.elements[t])==null?void 0:s.items)==null?void 0:l[0])==null?void 0:c.dataSet)==null?void 0:m.string(e);if(w!==void 0)return w}return i.string(e)}const Ce=async i=>{var n,r,o;const t=new Map;for(const s of Array.from(i))try{const l=await s.arrayBuffer(),c=C.parseDicom(new Uint8Array(l),{untilTag:"x7fe00010"}),m=c.string("x0020000e")||"unknown",d=c.string("x00080018")||"unknown",g=c.floatString("x00201041"),w=(n=se(c,"x00209113","x00200032"))==null?void 0:n.split("\\").map(parseFloat),_=(r=se(c,"x00209116","x00200037"))==null?void 0:r.split("\\").map(parseFloat),y=w==null?void 0:w[2],S=c.intString("x00200013"),I=c.uint16("x00280010")??-1,D=c.uint16("x00280011")??-1;if(I<=0||D<=0)throw new Error(`Invalid DICOM dimensions: rows=${I}, columns=${D}`);const F={file:s,SOPInstanceUID:d,rows:I,columns:D,numberOfFrames:c.intString("x00280008")??1,bitsAllocated:c.uint16("x00280100")??16,pixelRepresentation:c.uint16("x00280103")??0,samplesPerPixel:c.uint16("x00280002")??1,sliceLocation:g,imagePositionZ:y,imagePosition:w,imageOrientation:_,modality:c.string("x00080060"),instanceNumber:S};t.has(m)||t.set(m,[]),(o=t.get(m))==null||o.push(F)}catch(l){console.error(`Error parsing DICOM file: ${s.name}`,l)}const e=[];return t.forEach((s,l)=>{const c=Fe(s);e.push({seriesInstanceUID:l,dicomFiles:c})}),e};function ae(){const i=new Error("DICOM loading was aborted");return i.name="AbortError",i}class Ee{constructor(t={}){a(this,"workerFactory");a(this,"worker");a(this,"activeRequest");a(this,"nextRequestId",1);a(this,"disposed",!1);a(this,"handleMessage",t=>{var o;const e=t.data,n=this.activeRequest;if(!n||e.requestId!==n.requestId)return;if(e.type==="progress"){(o=n.onProgress)==null||o.call(n,{completed:e.completed,total:e.total,fileName:e.fileName});return}if(this.clearActiveRequest(),e.type==="success"){n.resolve(e.data);return}const r=new Error(e.error.message);r.name=e.error.name,r.stack=e.error.stack,n.reject(r)});a(this,"handleWorkerError",t=>{this.rejectActiveRequest(t.error instanceof Error?t.error:new Error(t.message)),this.terminateWorker()});a(this,"handleMessageError",()=>{this.rejectActiveRequest(new Error("Failed to deserialize a message from the DICOM worker")),this.terminateWorker()});this.workerFactory=t.workerFactory??(()=>new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/dicom.worker-_n6H46nx.js").href:new URL("assets/dicom.worker-_n6H46nx.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:J&&J.tagName.toUpperCase()==="SCRIPT"&&J.src||new URL("dicom3.umd.cjs",document.baseURI).href),{type:"module"}))}loadSeries(t,e={}){var o;if(this.disposed)return Promise.reject(new Error("DicomWorkerLoader has been disposed"));if(this.activeRequest)return Promise.reject(new Error("DicomWorkerLoader is already loading a series"));if(t.dicomFiles.length===0)return Promise.reject(new Error("Cannot load an empty DICOM series"));if((o=e.signal)!=null&&o.aborted)return Promise.reject(ae());const n=this.getWorker(),r=this.nextRequestId++;return new Promise((s,l)=>{const c={requestId:r,resolve:s,reject:l,onProgress:e.onProgress,signal:e.signal};e.signal&&(c.abortHandler=()=>this.abortActiveRequest(),e.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.activeRequest=c;const m={type:"load",requestId:r,files:t.dicomFiles};try{n.postMessage(m)}catch(d){this.clearActiveRequest(),l(d instanceof Error?d:new Error(String(d)))}})}dispose(){this.disposed||(this.disposed=!0,this.rejectActiveRequest(new Error("DicomWorkerLoader has been disposed")),this.terminateWorker())}getWorker(){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}abortActiveRequest(){this.rejectActiveRequest(ae()),this.terminateWorker()}rejectActiveRequest(t){const e=this.activeRequest;e&&(this.clearActiveRequest(),e.reject(t))}clearActiveRequest(){const t=this.activeRequest;t!=null&&t.signal&&t.abortHandler&&t.signal.removeEventListener("abort",t.abortHandler),this.activeRequest=void 0}terminateWorker(){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)}}const Me=new Map([["8_false_1",{format:u.RedIntegerFormat,internalFormat:"R8UI",textureType:u.UnsignedByteType}],["8_true_1",{format:u.RedIntegerFormat,internalFormat:"R8I",textureType:u.ByteType}],["8_false_3",{format:u.RGBIntegerFormat,internalFormat:"RGB8UI",textureType:u.UnsignedByteType}],["8_true_3",{format:u.RGBIntegerFormat,internalFormat:"RGB8I",textureType:u.ByteType}],["16_false_1",{format:u.RedIntegerFormat,internalFormat:"R16UI",textureType:u.UnsignedShortType}],["16_true_1",{format:u.RedIntegerFormat,internalFormat:"R16I",textureType:u.ShortType}],["16_false_3",{format:u.RGBIntegerFormat,internalFormat:"RGB16UI",textureType:u.UnsignedShortType}],["16_true_3",{format:u.RGBIntegerFormat,internalFormat:"RGB16I",textureType:u.ShortType}],["32_false_1",{format:u.RedFormat,internalFormat:"R32F",textureType:u.FloatType}],["32_true_1",{format:u.RedFormat,internalFormat:"R32F",textureType:u.FloatType}]]);class Re{constructor(t){a(this,"_data3DTexture");this.stack=t}get data3DTexture(){if(this._data3DTexture)return this._data3DTexture;const{pixelData:t,columns:e,rows:n,numberOfFrames:r,bitsAllocated:o,signed:s,samplesPerPixel:l}=this.stack,{format:c,internalFormat:m,textureType:d}=Me.get(`${o}_${s}_${l}`)??{format:u.RedIntegerFormat,internalFormat:"R16UI",textureType:u.UnsignedShortType};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}dispose(){const t=this._data3DTexture;this._data3DTexture=void 0,t==null||t.dispose()}}function Ae(i,t){switch(i){case 8:return t?Int8Array:Uint8Array;case 12:case 16:return t?Int16Array:Uint16Array;case 32:return Float32Array;default:throw new Error(`Unsupported bitsAllocated: ${i}`)}}async function Ve(i,t,e,n){const{rows:r,columns:o,numberOfFrames:s,bitsAllocated:l,samplesPerPixel:c,signed:m}=t,d=Ae(l,m),g=new d(r*o*c*s);let w=0,_=0;for await(const y of i){e==null||e(y,_);const{imageFrame:S}=await y.extractPixelData(),I=y.numberOfFrames??1,D=r*o*c*I;if(S.byteLength<D*d.BYTES_PER_ELEMENT)throw new Error(`Pixel data length mismatch: expected ${D}, got ${S.length}`);const F=new d(S.buffer,S.byteOffset,D);g.set(F,w),w+=F.length}if(w!==g.length)throw new Error(`Pixel data length mismatch: expected ${g.length}, got ${w}`);return g}const $=.001,le=1e-4;function Oe(i,t){const e=i.numberOfFrames??1;return Array.from({length:e},(n,r)=>{var o;return{sourceIndex:t,frameIndex:r,sourceFrameCount:e,perFramePosition:i.hasPerFrameImagePosition(r),id:`${i.sopInstanceUID()??""}:${String(r).padStart(10,"0")}`,seriesUID:i.seriesInstanceUID,referenceUID:i.frameOfReferenceUID,stackId:i.stackId(r),temporalPosition:i.temporalPosition(r),frameTime:i.frameTime,instanceNumber:i.instanceNumber(r),sliceLocation:i.rawHeader.floatString("x00201041"),imagePosition:i.imagePosition(r),imageOrientation:i.imageOrientation(r),pixelSpacing:i.pixelSpacing(r),sliceThickness:i.sliceThickness(r),spacingBetweenSlices:i.spacingBetweenSlices(r),windowWidth:i.windowWidth(r)??300,windowCenter:i.windowCenter(r)??50,rescaleSlope:i.rescaleSlope(r)??1,rescaleIntercept:i.rescaleIntercept(r)??0,modality:(o=i.modality)==null?void 0:o.toUpperCase(),distanceSourceToDetector:i.distanceSourceToDetector,distanceSourceToPatient:i.distanceSourceToPatient,positionerPrimaryAngle:i.positionerPrimaryAngle,positionerSecondaryAngle:i.positionerSecondaryAngle}})}function Ue(i,t){return Math.abs(i-t)<=1e-6+le*Math.max(Math.abs(i),Math.abs(t))}function b(i){throw new Error(`${i}; a regular 3D texture cannot represent this series. Split the series or resample it before loading`)}function Le(i){if(!i.length)throw new Error("No DICOM frames provided");const t=H(i,!1),e=i.reduce((h,p)=>h.id<p.id?h:p);for(const h of["seriesUID","referenceUID","stackId","modality"])new Set(i.map(p=>p[h]).filter(p=>p!=null)).size>1&&b(`Inconsistent ${h} in series`),i.some(p=>p[h]!=null)&&i.some(p=>p[h]==null)&&b(`Incomplete ${h} in series`);for(const h of["imagePosition","imageOrientation","pixelSpacing"])i.some(p=>p[h]!=null)&&i.some(p=>p[h]==null)&&b("Incomplete spatial metadata in part of the series");const n=new Set;for(const h of i){if(!h.id.startsWith(":")&&n.has(h.id)&&b("Duplicate SOP instance/frame"),n.add(h.id),h.temporalPosition!=null&&(!Number.isSafeInteger(h.temporalPosition)||h.temporalPosition<1))throw new Error("Invalid temporal position");if(h.imagePosition&&(h.imagePosition.length!==3||!h.imagePosition.every(Number.isFinite)))throw new Error("Invalid ImagePositionPatient");if(h.imageOrientation&&O(h.imageOrientation),h.pixelSpacing&&(h.pixelSpacing.length!==2||!h.pixelSpacing.every(p=>Number.isFinite(p)&&p>0)))throw new Error("Invalid PixelSpacing");if(h.sliceThickness!=null&&(!Number.isFinite(h.sliceThickness)||h.sliceThickness<=0))throw new Error("Invalid SliceThickness");if(h.spacingBetweenSlices!=null&&(!Number.isFinite(h.spacingBetweenSlices)||h.spacingBetweenSlices===0))throw new Error("Invalid SpacingBetweenSlices");(!Number.isFinite(h.rescaleSlope)||!Number.isFinite(h.rescaleIntercept)||h.rescaleSlope!==e.rescaleSlope||h.rescaleIntercept!==e.rescaleIntercept)&&b("Varying or invalid rescale parameters")}const r=i.map(h=>!!(h.imagePosition&&h.imageOrientation&&h.pixelSpacing));r.some(Boolean)&&!r.every(Boolean)&&b("Incomplete spatial metadata in part of the series");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,T)=>p-e.imagePosition[T]))<=$),m=i.length>1&&c&&i.every(h=>h.sourceFrameCount>1&&!h.perFramePosition),d=!o&&r.every(Boolean)&&!m&&!(l&&c);s.size>1&&d&&i.length>1&&b("Mixed spatial and temporal dimensions");const g=e.imageOrientation?O(e.imageOrientation):[1,0,0,0,1,0],w=e.pixelSpacing??[1,1];for(const h of i)h.imageOrientation&&O(h.imageOrientation).some((p,T)=>Math.abs(p-g[T])>V)&&b("Inconsistent image orientations"),h.pixelSpacing&&h.pixelSpacing.some((p,T)=>!Ue(p,w[T]))&&b("Inconsistent pixel spacing"),o&&["distanceSourceToDetector","distanceSourceToPatient","positionerPrimaryAngle","positionerSecondaryAngle"].some(p=>h[p]!==e[p])&&b("Varying XA detector geometry");const _=d?H(i):t,y=_[0];let S,I=y.spacingBetweenSlices??void 0;if(d){const h=oe(g);if(i.length>1){const p=y.imagePosition,T=_[_.length-1].imagePosition;S=p.map((M,Z)=>(T[Z]-M)/(i.length-1)),I=k(S,h),I<=$&&b("Duplicate or coplanar slice positions");const B=Math.max($,Math.hypot(...S)*le);for(let M=1;M<_.length;M++){const Z=_[M].imagePosition;k(Z,h)-k(_[M-1].imagePosition,h)<=$&&b("Duplicate or coplanar slice positions"),Math.hypot(...Z.map((rt,Te)=>rt-p[Te]-M*S[Te]))>B&&b("Irregular slice positions")}}else{const p=I??y.sliceThickness??1;S=h.map(T=>T*p)}}else S=[0,0,0];const D={imageOrientation:g,imagePosition:[...y.imagePosition??[0,0,0]],pixelSpacing:[...w],sliceThickness:y.sliceThickness??1,spacingBetweenSlices:I,sliceStep:S,frameAxis:d?"space":"sequence",windowWidth:y.windowWidth,windowCenter:y.windowCenter,rescaleSlope:y.rescaleSlope,rescaleIntercept:y.rescaleIntercept,modality:y.modality,distanceSourceToDetector:y.distanceSourceToDetector,distanceSourceToPatient:y.distanceSourceToPatient,positionerPrimaryAngle:y.positionerPrimaryAngle,positionerSecondaryAngle:y.positionerSecondaryAngle},F=new Map(i.map((h,p)=>[h,p]));return{geometry:D,order:_.map(h=>F.get(h))}}function ze(i,t,e){if(t.every((o,s)=>o===s))return;const n=i.slice(0,e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++){if(r[o]||t[o]===o)continue;n.set(i.subarray(o*e,(o+1)*e));let s=o;for(;t[s]!==o;){const l=t[s];i.copyWithin(s*e,l*e,(l+1)*e),r[s]=1,s=l}i.set(n,s*e),r[s]=1}}async function Ne(i,t,e){const n=[],r=await Ve(i,t,(l,c)=>{for(const m of Oe(l,c))n.push(m)}),{geometry:o,order:s}=Le(n);return ze(r,s,t.rows*t.columns*t.samplesPerPixel),{...t,...o,pixelData:r}}function We(i){if(i.length===0)throw new Error("No DICOM parsers provided");const t=i[0],e=t.rows??-1,n=t.columns??-1,r=t.pixelRepresentation===1,o=t.bitsAllocated??16,s=t.samplesPerPixel??1;if(!Number.isSafeInteger(e)||!Number.isSafeInteger(n)||e<=0||n<=0)throw new Error(`Invalid DICOM dimensions: rows=${e}, columns=${n}`);for(const l of i){if(!Number.isSafeInteger(l.numberOfFrames??1)||(l.numberOfFrames??1)<=0)throw new Error("Invalid number of frames");if(l.rows!==e||l.columns!==n)throw new Error("Inconsistent image dimensions in series");if(l.bitsAllocated!==o)throw new Error("Inconsistent bits per pixel in series");if(l.pixelRepresentation!==(r?1:0))throw new Error("Inconsistent pixel signedness in series");if(l.samplesPerPixel!==s)throw new Error("Inconsistent samples per pixel in series")}return{rows:e,columns:n,numberOfFrames:i.reduce((l,c)=>l+(c.numberOfFrames??1),0),signed:r,bitsAllocated:o,samplesPerPixel:s}}class q{constructor(t,e){a(this,"rows");a(this,"columns");a(this,"numberOfFrames");a(this,"bitsAllocated");a(this,"signed");a(this,"bytesPerPixel");a(this,"samplesPerPixel");a(this,"pixelData");a(this,"windowWidth");a(this,"windowCenter");a(this,"rescaleSlope");a(this,"rescaleIntercept");a(this,"textureFactory");a(this,"imageOrientation",[1,0,0,0,1,0]);a(this,"imagePosition",[0,0,0]);a(this,"pixelSpacing");a(this,"sliceThickness");a(this,"spacingBetweenSlices");a(this,"sliceStep");a(this,"frameAxis");a(this,"modality");a(this,"distanceSourceToDetector");a(this,"distanceSourceToPatient");a(this,"positionerPrimaryAngle");a(this,"positionerSecondaryAngle");a(this,"ijk2lps",new u.Matrix4);a(this,"lps2ijk",null);a(this,"spatialRank",3);var g,w;this.parsers=t;const{rows:n,bitsAllocated:r,columns:o,numberOfFrames:s,signed:l,samplesPerPixel:c}=e,m=n*o*s*c;if(e.pixelData.length!==m)throw new Error(`Pixel data length mismatch: expected ${m}, got ${e.pixelData.length}`);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=((g=e.modality)==null?void 0:g.toUpperCase())==="XA"?"sequence":e.frameAxis??"space",e.frameAxis!==void 0&&e.frameAxis!=="space"&&e.frameAxis!=="sequence")throw new Error("Invalid frameAxis");if(e.spacingBetweenSlices!==void 0&&(!Number.isFinite(e.spacingBetweenSlices)||e.spacingBetweenSlices===0))throw new Error("Invalid spacingBetweenSlices");if(e.sliceStep!==void 0&&(e.sliceStep.length!==3||!e.sliceStep.every(Number.isFinite)))throw new Error("Invalid sliceStep");const d=new u.Vector3().crossVectors(new u.Vector3(...this.imageOrientation.slice(0,3)),new u.Vector3(...this.imageOrientation.slice(3)));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");if(e.sliceStep&&this.frameAxis==="space"&&d.dot(new u.Vector3(...this.sliceStep))===0)throw new Error("Spatial sliceStep must have a nonzero component along the slice normal");switch(this.modality=e.modality,this.distanceSourceToDetector=e.distanceSourceToDetector,this.distanceSourceToPatient=e.distanceSourceToPatient,this.positionerPrimaryAngle=e.positionerPrimaryAngle,this.positionerSecondaryAngle=e.positionerSecondaryAngle,(w=this.modality)==null?void 0:w.toUpperCase()){case"XA":this._computeAngioMath();break;default:this._computeDefaultMath()}this.textureFactory=new Re(this)}static async create(t){const e=We(t);return new q([...t],await Ne(t,e))}static fromData(t){return new q([],t)}hasSpatialVolume(){return this.spatialRank===3&&this.lps2ijk!==null}voxelToLps(t,e,n){return new u.Vector3(t,e,n).applyMatrix4(this.ijk2lps)}lpsToVoxel(t){if(!this.lps2ijk)throw new Error("Stack geometry is not invertible");return t.clone().applyMatrix4(this.lps2ijk)}_computeAngioMath(){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),[g,w]=this.pixelSpacing,_=this.rows,y=this.columns,S=new u.Vector3(w,0,0),I=new u.Vector3(0,0,-g),D=new u.Vector3((-y/2+.5)*w,-n,(_/2-.5)*g),F=S.clone().applyMatrix3(d),h=I.clone().applyMatrix3(d),p=D.clone().applyMatrix3(d);this.ijk2lps.makeBasis(F,h,new u.Vector3).setPosition(p),this.lps2ijk=null,this.spatialRank=2;const T=F.clone().normalize(),B=h.clone().normalize();this.imageOrientation=[T.x,T.y,T.z,B.x,B.y,B.z],this.imagePosition=[p.x,p.y,p.z]}_computeDefaultMath(){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];this.ijk2lps.makeBasis(t.clone().multiplyScalar(r),e.clone().multiplyScalar(n),new u.Vector3(...this.sliceStep)).setPosition(new u.Vector3(this.imagePosition[0],this.imagePosition[1],this.imagePosition[2]));const o=this.ijk2lps.determinant();if(!Number.isFinite(o)||o===0){this.lps2ijk=null,this.spatialRank=2;return}this.lps2ijk=this.ijk2lps.clone().invert(),this.spatialRank=this.lps2ijk.elements.every(Number.isFinite)?3:2,this.spatialRank===2&&(this.lps2ijk=null)}}function R(i){return new v.Vector3(i.columns,i.rows,i.numberOfFrames)}function U(i){return R(i).subScalar(1).multiplyScalar(.5)}function ce(i){return new v.Box3(new v.Vector3(-.5,-.5,-.5),R(i).subScalar(.5))}function Q(i){const{min:t,max:e}=ce(i);return[new v.Vector3(t.x,t.y,t.z),new v.Vector3(e.x,t.y,t.z),new v.Vector3(e.x,e.y,t.z),new v.Vector3(t.x,e.y,t.z),new v.Vector3(t.x,t.y,e.z),new v.Vector3(e.x,t.y,e.z),new v.Vector3(e.x,e.y,e.z),new v.Vector3(t.x,e.y,e.z)]}function ue(i){if(i!=="data"&&i!=="lps")throw new Error(`Unsupported slice plane space: ${i}; expected data or lps`)}function j(i,t){if(!i||![i.x,i.y,i.z].every(Number.isFinite))throw new Error(`Slice plane ${t} must have finite components`)}function he(i){j(i,"normal");const t=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));if(t===0)throw new Error("Slice plane normal must be non-zero");return new v.Vector3(i.x/t,i.y/t,i.z/t).normalize()}function me(i){const t=i.lps2ijk;if(!t||!t.elements.every(Number.isFinite)||!i.ijk2lps.elements.every(Number.isFinite)||i.ijk2lps.determinant()===0)throw new Error("LPS slice planes require an invertible stack geometry");return t}function G(i){if(!i)throw new Error("Slice plane is required");const t=i.space===void 0?"data":i.space;return ue(t),j(i.origin,"origin"),{origin:i.origin.clone(),normal:he(i.normal),space:t}}function X(i,t,e){ue(e);const n=G(t),r=n.space==="lps"||e==="lps"?me(i):null;if(n.space===e)return n;const o=e==="lps"?i.ijk2lps:r,s=new v.Matrix3().setFromMatrix4(e==="lps"?r:i.ijk2lps).transpose();return n.origin.applyMatrix4(o),j(n.origin,"origin"),{origin:n.origin,normal:he(n.normal.applyMatrix3(s)),space:e}}function Be(i,t){if(!Number.isFinite(t))throw new Error(`Slice plane offset must be finite, got ${t}`);const e=G(i);return e.origin.addScaledVector(e.normal,t),j(e.origin,"origin"),e}function ke(i,t){const e=G(t);if(![i.columns,i.rows,i.numberOfFrames].every(o=>Number.isSafeInteger(o)&&o>0))throw new Error("Slice stack dimensions must be positive integers");e.space==="lps"&&me(i);let n=1/0,r=-1/0;for(const o of Q(i)){e.space==="lps"&&o.applyMatrix4(i.ijk2lps);const s=o.sub(e.origin).dot(e.normal);if(!Number.isFinite(s))throw new Error("Slice offset range exceeds the finite numeric range");n=Math.min(n,s),r=Math.max(r,s)}return{min:n,max:r,space:e.space,unit:e.space==="lps"?"mm":"data"}}var $e=`in vec3 position;
2
+
3
+ uniform mat4 modelViewMatrix;
4
+ uniform mat4 projectionMatrix;
5
+
6
+ out vec3 vDataPosition;
7
+
8
+ void main() {
9
+ vDataPosition = position;
10
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
11
+ }`;const ee=`
12
+ vec3 dataToTexture(vec3 dataPosition, vec3 size) {
13
+ return (dataPosition + vec3(0.5)) / size;
14
+ }
15
+
16
+ ivec3 nearestVoxelIndex(vec3 dataPosition, vec3 size) {
17
+ return ivec3(clamp(floor(dataPosition + vec3(0.5)), vec3(0.0), size - vec3(1.0)));
18
+ }
19
+ `;function Y(i){return Number.isFinite(i)&&Number.isFinite(Math.fround(i))}function de(i){if(i.samplesPerPixel!==1)throw new Error("Slices support scalar data only (samplesPerPixel=1); RGB is not supported");const t=i.bitsAllocated===8?i.signed?Int8Array:Uint8Array:i.bitsAllocated===16?i.signed?Int16Array:Uint16Array:i.bitsAllocated===32?Float32Array:void 0;if(!t)throw new Error(`Unsupported slice bitsAllocated: ${i.bitsAllocated}; expected 8, 16 or 32`);if(!(i.pixelData instanceof t))throw new Error(`Slice pixelData must be ${t.name} for this stack format`);if(![i.columns,i.rows,i.numberOfFrames].every(e=>Number.isSafeInteger(e)&&e>0))throw new Error("Slice stack dimensions must be positive integers");if(!i.ijk2lps.elements.every(Number.isFinite))throw new Error("Slice stack geometry must be finite");pe(i)}function pe(i){if(!Y(i.rescaleSlope)||Math.fround(i.rescaleSlope)===0||!Y(i.rescaleIntercept))throw new Error("Slice rescaleSlope must be finite and non-zero; rescaleIntercept must be finite (Float32 range)")}function L(i,t,e){if(!Y(t)||!Y(e)||!(Math.fround(e)>0))throw new Error(`Slice window must be finite with positive width (Float32 range), got center=${t}, width=${e}`);return pe(i),{uWindowCenter:{value:t},uWindowWidth:{value:e},uRescaleSlope:{value:i.rescaleSlope},uRescaleIntercept:{value:i.rescaleIntercept}}}const fe=`
20
+ uniform float uWindowCenter;
21
+ uniform float uWindowWidth;
22
+ uniform float uRescaleSlope;
23
+ uniform float uRescaleIntercept;
24
+
25
+ float windowRawValue(float rawValue) {
26
+ float value = rawValue * uRescaleSlope + uRescaleIntercept;
27
+ return clamp((value - uWindowCenter) / uWindowWidth + 0.5, 0.0, 1.0);
28
+ }
29
+ `,ge={R8I:{samplerType:"isampler3D",texelType:"ivec4"},R8UI:{samplerType:"usampler3D",texelType:"uvec4"},R16I:{samplerType:"isampler3D",texelType:"ivec4"},R16UI:{samplerType:"usampler3D",texelType:"uvec4"},R32F:{samplerType:"sampler3D",texelType:"vec4"}};function qe(i){const t=ge[i];if(!Object.prototype.hasOwnProperty.call(ge,i))throw new Error(`Unsupported oblique slice texture internalFormat: ${i}`);return`
30
+ precision highp float;
31
+ precision highp int;
32
+ precision highp ${t.samplerType};
33
+
34
+ uniform ${t.samplerType} map;
35
+ uniform vec3 uSize;
36
+
37
+ in vec3 vDataPosition;
38
+ out vec4 fragColor;
39
+
40
+ ${ee}
41
+ ${fe}
42
+
43
+ void main() {
44
+ vec3 minPosition = vec3(-0.5);
45
+ vec3 maxPosition = uSize - vec3(0.5);
46
+
47
+ // Allow interpolation roundoff at a face, but discard genuinely external positions.
48
+ const float boundaryTolerance = 0.00001;
49
+ if (any(lessThan(vDataPosition, minPosition - vec3(boundaryTolerance))) ||
50
+ any(greaterThan(vDataPosition, maxPosition + vec3(boundaryTolerance)))) {
51
+ discard;
52
+ }
53
+
54
+ ivec3 index = nearestVoxelIndex(vDataPosition, uSize);
55
+ ${t.texelType} texel = texelFetch(map, index, 0);
56
+ float pixelValue = windowRawValue(float(texel.r));
57
+
58
+ fragColor = vec4(pixelValue, pixelValue, pixelValue, 1.0);
59
+ }
60
+ `}function z(i){let t=!1,e;for(const n of i)try{n()}catch(r){t||(e=r),t=!0}if(t)throw e}function x(i,t){if(i.isDisposed)throw new Error(`${t} has been disposed`)}const N=1e-6,W=6,te=[0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7];class je{constructor(t){a(this,"corners");a(this,"distances",new Float64Array(8));a(this,"pool",Array.from({length:20},()=>new u.Vector3));a(this,"points",[]);a(this,"candidate",new u.Vector3);a(this,"center",new u.Vector3);a(this,"u",new u.Vector3);a(this,"v",new u.Vector3);a(this,"left",new u.Vector3);a(this,"right",new u.Vector3);this.corners=Q(t)}intersect(t){const{origin:e,normal:n}=t,{points:r,corners:o,distances:s}=this;r.length=0;for(let c=0;c<o.length;c++){const m=this.candidate.subVectors(o[c],e).dot(n);if(!Number.isFinite(m))throw new Error("Oblique slice plane distance exceeds the finite numeric range");s[c]=Math.abs(m)<=N?0:m}for(let c=0;c<te.length;c+=2){const m=te[c],d=te[c+1],g=s[m],w=s[d];g===0&&this.pushUnique(o[m]),w===0&&this.pushUnique(o[d]),(g<0&&w>0||g>0&&w<0)&&this.pushUnique(this.candidate.copy(o[m]).lerp(o[d],g/(g-w)))}if(r.length<3)return r.length=0,r;this.center.set(0,0,0);for(const c of r)this.center.add(c);this.center.multiplyScalar(1/r.length),this.candidate.set(0,Math.abs(n.z)<.9?0:1,Math.abs(n.z)<.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));let l=0;for(let c=1;c<r.length-1;c++)l+=this.left.subVectors(r[c],r[0]).cross(this.right.subVectors(r[c+1],r[0])).dot(n);if(l<=N*N)return r.length=0,r;if(r.length>W)throw new Error("Oblique slice intersection exceeds the six-vertex capacity");for(const c of r)if(!Number.isFinite(Math.fround(c.x))||!Number.isFinite(Math.fround(c.y))||!Number.isFinite(Math.fround(c.z)))throw new Error("Oblique slice intersection exceeds the Float32 geometry range");return r}pushUnique(t){this.points.some(e=>e.distanceToSquared(t)<=N*N)||this.points.push(this.pool[this.points.length].copy(t))}angle(t){return this.candidate.subVectors(t,this.center),Math.atan2(this.candidate.dot(this.v),this.candidate.dot(this.u))}}class ie extends u.BufferGeometry{constructor(){super();a(this,"vertexCount",0);a(this,"point",new u.Vector3);this.setAttribute("position",new u.BufferAttribute(new Float32Array(W*3),3).setUsage(u.DynamicDrawUsage)),this.setAttribute("normal",new u.BufferAttribute(new Float32Array(W*3),3).setUsage(u.DynamicDrawUsage)),this.setIndex(new u.BufferAttribute(new Uint16Array((W-2)*3),1).setUsage(u.DynamicDrawUsage)),this.boundingBox=new u.Box3,this.boundingSphere=new u.Sphere,this.setDrawRange(0,0)}update(e,n){const r=this.getAttribute("position"),o=this.getAttribute("normal"),s=this.getIndex();this.vertexCount=e.length;for(let c=0;c<W;c++){const m=e[c]??e[0];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)}const l=Math.max(0,e.length-2)*3;for(let c=0;c<s.count;c+=3)s.setX(c,0),s.setX(c+1,c<l?c/3+1:0),s.setX(c+2,c<l?c/3+2:0);this.setDrawRange(0,l),this.computeBoundingBox(),this.computeBoundingSphere(),r.needsUpdate=!0,o.needsUpdate=!0,s.needsUpdate=!0}computeBoundingBox(){this.boundingBox??(this.boundingBox=new u.Box3),this.boundingBox.makeEmpty();const e=this.getAttribute("position");for(let n=0;n<this.vertexCount;n++)this.boundingBox.expandByPoint(this.point.fromBufferAttribute(e,n))}computeBoundingSphere(){if(this.boundingSphere??(this.boundingSphere=new u.Sphere),this.boundingSphere.makeEmpty(),this.vertexCount===0)return;this.computeBoundingBox(),this.boundingBox.getCenter(this.boundingSphere.center);let e=0;const n=this.getAttribute("position");for(let r=0;r<this.vertexCount;r++)e=Math.max(e,this.point.fromBufferAttribute(n,r).distanceToSquared(this.boundingSphere.center));this.boundingSphere.radius=Math.sqrt(e)}copy(e){return super.copy(e),this.vertexCount=e instanceof ie?e.vertexCount:0,this}}class Ge extends u.Object3D{constructor(e,n,r={}){super();a(this,"stack");a(this,"texture");a(this,"mesh");a(this,"intersection");a(this,"sliceGeometry");a(this,"_plane");a(this,"_windowCenter");a(this,"_windowWidth");a(this,"_disposed",!1);de(e),this.stack=e,this._plane=X(e,n,"data"),this._windowCenter=r.windowCenter===void 0?e.windowCenter:r.windowCenter,this._windowWidth=r.windowWidth===void 0?e.windowWidth:r.windowWidth;const o=L(e,this._windowCenter,this._windowWidth);this.intersection=new je(e);const s=this.intersection.intersect(this._plane);this.texture=e.textureFactory.data3DTexture;const l=qe(String(this.texture.internalFormat));this.sliceGeometry=new ie,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)}get plane(){return this.getPlane()}set plane(e){x(this,"ObliqueSlice");const n=X(this.stack,e,"data");if(n.origin.distanceToSquared(this._plane.origin)<=1e-24&&n.normal.distanceToSquared(this._plane.normal)<=1e-24)return;const r=this.intersection.intersect(n);this.sliceGeometry.update(r,n.normal),this._plane=n,this.dispatchEvent({type:"change",reason:"plane"})}get hasIntersection(){return!this._disposed&&this.vertexCount>0}get vertexCount(){return this.sliceGeometry.vertexCount}getPlane(e="data"){return X(this.stack,this._plane,e)}get windowCenter(){return this._windowCenter}set windowCenter(e){this.setWindow(e,this._windowWidth)}get windowWidth(){return this._windowWidth}set windowWidth(e){this.setWindow(this._windowCenter,e)}get geometry(){return this.mesh.geometry}get material(){return this.mesh.material}setPlane(e){this.plane=e}setWindow(e,n){x(this,"ObliqueSlice");const r=L(this.stack,e,n);if(!(e===this._windowCenter&&n===this._windowWidth&&Object.entries(r).every(([o,s])=>this.material.uniforms[o].value===s.value))){this._windowCenter=e,this._windowWidth=n;for(const[o,s]of Object.entries(r))this.material.uniforms[o].value=s.value;this.dispatchEvent({type:"change",reason:"window"})}}get isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this._disposed=!0,this.visible=!1;const{geometry:e,material:n}=this.mesh;z([()=>this.mesh.removeFromParent(),()=>this.removeFromParent(),()=>this.clear(),()=>e.dispose(),()=>n.dispose(),()=>this.dispatchEvent({type:"dispose"})])}createMaterial(e,n){return new u.RawShaderMaterial({glslVersion:u.GLSL3,uniforms:{map:{value:this.texture},uSize:{value:R(this.stack)},...n},vertexShader:$e,fragmentShader:e,side:u.DoubleSide})}}var Xe=`in vec3 position;
61
+
62
+ uniform mat4 modelViewMatrix;\r
63
+ uniform mat4 projectionMatrix;
64
+
65
+ out vec3 vPosition;
66
+
67
+ void main() {\r
68
+ vPosition = position;\r
69
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\r
70
+ }`;const we={R8I:{samplerType:"isampler3D",texelType:"ivec4"},R8UI:{samplerType:"usampler3D",texelType:"uvec4"},R16I:{samplerType:"isampler3D",texelType:"ivec4"},R16UI:{samplerType:"usampler3D",texelType:"uvec4"},R32F:{samplerType:"sampler3D",texelType:"vec4"}};function Ye(i){const t=we[i];if(!Object.prototype.hasOwnProperty.call(we,i))throw new Error(`Unsupported slice texture internalFormat: ${i}`);const{samplerType:e,texelType:n}=t,r=(o,s)=>`
71
+ precision highp float;
72
+ precision highp int;
73
+ precision highp ${e};
74
+
75
+ uniform ${e} map;
76
+ uniform int ${o};
77
+ uniform vec3 uSize;
78
+
79
+ in vec3 vPosition;
80
+ out vec4 fragColor;
81
+
82
+ ${ee}
83
+ ${fe}
84
+
85
+ void main() {
86
+ // Geometry is embedded in IJK; the mesh translates only along the selected axis.
87
+ vec3 dataPosition = ${s};
88
+ ivec3 index = nearestVoxelIndex(dataPosition, uSize);
89
+ ${n} texel = texelFetch(map, index, 0);
90
+ float pixelValue = windowRawValue(float(texel.r));
91
+ fragColor = vec4(pixelValue, pixelValue, pixelValue, 1.0);
92
+ }
93
+ `;return{fragmentX:r("ix","vec3(float(ix), vPosition.y, vPosition.z)"),fragmentY:r("iy","vec3(vPosition.x, float(iy), vPosition.z)"),fragmentZ:r("iz","vec3(vPosition.x, vPosition.y, float(iz))")}}const ye={x:{fragment:"fragmentX",indexUniform:"ix",positionComponent:"x",size:i=>i.columns,defaultIndex:i=>Math.trunc(i.columns/2),geometry:i=>{const t=U(i);return new u.PlaneGeometry(i.numberOfFrames,i.rows).rotateY(-Math.PI/2).translate(0,t.y,t.z)},uniforms:i=>({ix:{value:i}})},y:{fragment:"fragmentY",indexUniform:"iy",positionComponent:"y",size:i=>i.rows,defaultIndex:i=>Math.trunc(i.rows/2),geometry:i=>{const t=U(i);return new u.PlaneGeometry(i.columns,i.numberOfFrames).rotateX(Math.PI/2).translate(t.x,0,t.z)},uniforms:i=>({iy:{value:i}})},z:{fragment:"fragmentZ",indexUniform:"iz",positionComponent:"z",size:i=>i.numberOfFrames,defaultIndex:i=>Math.trunc(i.numberOfFrames/2),geometry:i=>{const t=U(i);return new u.PlaneGeometry(i.columns,i.rows).translate(t.x,t.y,0)},uniforms:i=>({iz:{value:i}})}};class A extends u.Object3D{constructor(e,n,r={}){super();a(this,"stack");a(this,"axis");a(this,"texture");a(this,"mesh");a(this,"config");a(this,"_index");a(this,"_windowCenter");a(this,"_windowWidth");a(this,"_disposed",!1);if(!Object.prototype.hasOwnProperty.call(ye,n))throw new Error(`Unsupported slice axis: ${n}; expected x, y or z`);de(e),this.stack=e,this.axis=n,this.config=ye[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;const o=L(e,this._windowCenter,this._windowWidth);this.texture=e.textureFactory.data3DTexture;const s=Ye(String(this.texture.internalFormat));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}static fromAxis(e,n,r,o={}){return new A(e,n,{...o,index:r===void 0?o.index:r})}get index(){return this._index}set index(e){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"}))}get windowCenter(){return this._windowCenter}set windowCenter(e){this.setWindow(e,this._windowWidth)}get windowWidth(){return this._windowWidth}set windowWidth(e){this.setWindow(this._windowCenter,e)}get geometry(){return this.mesh.geometry}get material(){return this.mesh.material}setWindow(e,n){x(this,"Slice");const r=L(this.stack,e,n);if(!(e===this._windowCenter&&n===this._windowWidth&&Object.entries(r).every(([o,s])=>this.material.uniforms[o].value===s.value))){this._windowCenter=e,this._windowWidth=n;for(const[o,s]of Object.entries(r))this.material.uniforms[o].value=s.value;this.dispatchEvent({type:"change",reason:"window"})}}get isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this._disposed=!0,this.visible=!1;const{geometry:e,material:n}=this.mesh;z([()=>this.mesh.removeFromParent(),()=>this.removeFromParent(),()=>this.clear(),()=>e.dispose(),()=>n.dispose(),()=>this.dispatchEvent({type:"dispose"})])}createMaterial(e,n){return new u.RawShaderMaterial({glslVersion:u.GLSL3,uniforms:{map:{value:this.texture},uSize:{value:R(this.stack)},...this.config.uniforms(this._index),...n},vertexShader:Xe,fragmentShader:e,side:u.DoubleSide})}validateIndex(e){if(!(Number.isInteger(e)&&e>=0&&e<this.config.size(this.stack)))throw new Error(`Slice index must be an integer in [0, ${this.config.size(this.stack)-1}], got ${e}`)}}class Ze extends u.Object3D{constructor(e){super();a(this,"stack");a(this,"nx");a(this,"ny");a(this,"nz");a(this,"size");a(this,"lx");a(this,"ly");a(this,"lz");a(this,"hx");a(this,"hy");a(this,"hz");a(this,"sliceX");a(this,"sliceY");a(this,"sliceZ");a(this,"_disposed",!1);a(this,"windowUpdateDepth",0);a(this,"windowChanged",!1);a(this,"onSliceChange",e=>{if(!this._disposed){if(this.windowUpdateDepth>0&&e.reason==="window"){this.windowChanged=!0;return}this.dispatchEvent({type:"change",reason:e.reason,axis:e.target.axis})}});a(this,"onSliceDispose",e=>{this._disposed||this.dispatchEvent({type:"change",reason:"dispose",axis:e.target.axis})});if(!e.hasSpatialVolume())throw new Error("OrthoSlicer requires a spatial volume; use Slice Z for a frame sequence");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=A.fromAxis(e,"x"),this.sliceY=A.fromAxis(e,"y"),this.sliceZ=A.fromAxis(e,"z"),this.add(this.sliceX,this.sliceY,this.sliceZ);for(const n of[this.sliceX,this.sliceY,this.sliceZ])n.addEventListener("change",this.onSliceChange),n.addEventListener("dispose",this.onSliceDispose)}set ix(e){x(this,"OrthoSlicer"),this.sliceX.index=e}get ix(){return this.sliceX.index}set iy(e){x(this,"OrthoSlicer"),this.sliceY.index=e}get iy(){return this.sliceY.index}set iz(e){x(this,"OrthoSlicer"),this.sliceZ.index=e}get iz(){return this.sliceZ.index}setWindow(e,n){x(this,"OrthoSlicer");const r=[this.sliceX,this.sliceY,this.sliceZ];for(const o of r)x(o,"Slice");L(this.stack,e,n),this.windowUpdateDepth++;try{z(r.map(o=>()=>o.setWindow(e,n)))}finally{this.windowUpdateDepth--,this.windowUpdateDepth===0&&this.windowChanged&&(this.windowChanged=!1,this._disposed||this.dispatchEvent({type:"change",reason:"window"}))}}get isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this._disposed=!0,this.visible=!1;const e=[this.sliceX,this.sliceY,this.sliceZ];for(const n of e)n.removeEventListener("change",this.onSliceChange),n.removeEventListener("dispose",this.onSliceDispose);z([()=>this.removeFromParent(),...e.map(n=>()=>n.dispose()),()=>this.clear(),()=>this.dispatchEvent({type:"dispose"})])}}const xe={"ct-soft-tissue":{name:"CT soft tissue",mode:"composite",window:[-160,240],threshold:40,sampleDistance:1,opacityScale:.72,lightingEnabled:!0,transferFunction:[{value:-1e3,color:[0,0,0],opacity:0},{value:-200,color:[.35,.18,.12],opacity:0},{value:-80,color:[.72,.36,.24],opacity:.05},{value:40,color:[.9,.52,.42],opacity:.18},{value:180,color:[1,.76,.68],opacity:.28},{value:420,color:[1,.95,.86],opacity:.12}]},"ct-bone":{name:"CT bone",mode:"composite",window:[150,1800],threshold:320,sampleDistance:.85,opacityScale:1.25,lightingEnabled:!0,lighting:{ambient:.18,diffuse:.82,specular:.22,shininess:36},transferFunction:[{value:-3024,color:[0,0,0],opacity:0},{value:120,color:[.56,.32,.28],opacity:0},{value:300,color:[.78,.58,.42],opacity:.08},{value:641,color:[.91,.82,.56],opacity:.72},{value:1250,color:[.98,.95,.88],opacity:.86},{value:3071,color:[1,1,1],opacity:.92}]},"ct-bone-mip":{name:"CT bone MIP",mode:"mip",window:[120,2200],threshold:320,sampleDistance:1,opacityScale:1,lightingEnabled:!1,transferFunction:[{value:120,color:[.05,.05,.05],opacity:0},{value:420,color:[.72,.69,.62],opacity:.2},{value:1e3,color:[.96,.92,.82],opacity:.75},{value:2200,color:[1,1,1],opacity:1}]},"ct-lung":{name:"CT lung",mode:"composite",window:[-1e3,250],threshold:-650,sampleDistance:1,opacityScale:.95,lightingEnabled:!0,transferFunction:[{value:-1e3,color:[0,0,0],opacity:0},{value:-900,color:[.42,.55,.68],opacity:.08},{value:-720,color:[.62,.72,.82],opacity:.32},{value:-520,color:[.72,.78,.84],opacity:.16},{value:-260,color:[.88,.74,.64],opacity:.04},{value:80,color:[1,.86,.78],opacity:0}]},"ct-fat":{name:"CT fat",mode:"composite",window:[-220,120],threshold:-95,sampleDistance:.9,opacityScale:1.05,lightingEnabled:!0,transferFunction:[{value:-1e3,color:[0,0,0],opacity:0},{value:-190,color:[.7,.52,.18],opacity:0},{value:-125,color:[.95,.76,.28],opacity:.36},{value:-70,color:[1,.86,.46],opacity:.42},{value:-20,color:[.92,.64,.3],opacity:.06},{value:120,color:[.72,.38,.28],opacity:0}]},"ct-air":{name:"CT air",mode:"composite",window:[-1100,-450],threshold:-900,sampleDistance:1,opacityScale:.8,lightingEnabled:!1,transferFunction:[{value:-1100,color:[.05,.1,.16],opacity:.26},{value:-1e3,color:[.12,.2,.28],opacity:.2},{value:-820,color:[.3,.42,.52],opacity:.08},{value:-600,color:[.62,.68,.72],opacity:.02},{value:-450,color:[.9,.9,.86],opacity:0}]}};function Se(i){return typeof i!="string"?i:xe[i]}const ne={mip:0,composite:1,iso:2};var Je=`in vec3 position;
94
+
95
+ uniform mat4 modelViewMatrix;
96
+ uniform mat4 projectionMatrix;
97
+
98
+ out vec3 vPosition;
99
+
100
+ void main() {
101
+ vPosition = position;
102
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
103
+ }`;const Ke={R8I:{samplerType:"isampler3D",texelType:"ivec4"},R8UI:{samplerType:"usampler3D",texelType:"uvec4"},R16I:{samplerType:"isampler3D",texelType:"ivec4"},R16UI:{samplerType:"usampler3D",texelType:"uvec4"},R32F:{samplerType:"sampler3D",texelType:"vec4"},RGB8I:{samplerType:"isampler3D",texelType:"ivec4"},RGB8UI:{samplerType:"usampler3D",texelType:"uvec4"},RGB16I:{samplerType:"isampler3D",texelType:"ivec4"},RGB16UI:{samplerType:"usampler3D",texelType:"uvec4"}};function He(i,{maxSteps:t,maxTransferPoints:e}){const n=Ke[i];if(!n)throw new Error(`Unsupported volume texture internalFormat: ${i}`);const r=Math.max(1,Math.trunc(t)),o=Math.max(2,Math.trunc(e));return`
104
+ precision highp float;
105
+ precision highp int;
106
+ precision highp ${n.samplerType};
107
+
108
+ uniform ${n.samplerType} map;
109
+ uniform vec3 uCameraLocalPosition;
110
+ uniform vec3 uCameraLocalDirection;
111
+ uniform bool uOrthographicCamera;
112
+ uniform vec3 uSize;
113
+ uniform float uRescaleSlope;
114
+ uniform float uRescaleIntercept;
115
+ uniform int uMode;
116
+ uniform vec2 uWindow;
117
+ uniform float uThreshold;
118
+ uniform float uSampleDistance;
119
+ uniform float uOpacityScale;
120
+ uniform bool uLightingEnabled;
121
+ uniform vec4 uLighting;
122
+ uniform int uTransferPointCount;
123
+ uniform vec4 uTransferPoints[${o}];
124
+ uniform vec2 uOpacityPoints[${o}];
125
+
126
+ in vec3 vPosition;
127
+
128
+ out vec4 fragColor;
129
+
130
+ const int MAX_STEPS = ${r};
131
+ const int MAX_TRANSFER_POINTS = ${o};
132
+ const int REFINEMENT_STEPS = 4;
133
+
134
+ ${ee}
135
+
136
+ float windowValue(float value);
137
+ float safeDirection(float value);
138
+ vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 boxMin, vec3 boxMax);
139
+ float sampleRaw(vec3 texcoords);
140
+ float sampleValue(vec3 texcoords);
141
+ vec3 transferColor(float value);
142
+ float transferOpacity(float value);
143
+ vec4 applyTransfer(float value);
144
+ vec4 applyLighting(float value, vec3 loc, vec3 viewRay);
145
+ void castMip(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay);
146
+ void castComposite(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay);
147
+ void castIso(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay);
148
+
149
+ void main() {
150
+ vec3 localCameraPosition = uCameraLocalPosition;
151
+ vec3 rayDirection = normalize(vPosition - localCameraPosition);
152
+
153
+ if (uOrthographicCamera) {
154
+ rayDirection = normalize(uCameraLocalDirection);
155
+ localCameraPosition = vPosition - rayDirection * max(max(uSize.x, uSize.y), uSize.z) * 2.0;
156
+ }
157
+
158
+ vec2 hit = intersectBox(localCameraPosition, rayDirection, vec3(-0.5), uSize - vec3(0.5));
159
+ hit.x = max(hit.x, 0.0);
160
+
161
+ if (hit.x >= hit.y) {
162
+ discard;
163
+ }
164
+
165
+ vec3 startPosition = localCameraPosition + hit.x * rayDirection;
166
+ vec3 endPosition = localCameraPosition + hit.y * rayDirection;
167
+ float travelDistance = distance(startPosition, endPosition);
168
+ int nsteps = int(travelDistance / max(uSampleDistance, 0.01) + 0.5);
169
+
170
+ if (nsteps < 1) {
171
+ discard;
172
+ }
173
+
174
+ nsteps = min(nsteps, MAX_STEPS);
175
+
176
+ vec3 stepVec = ((endPosition - startPosition) / uSize) / float(nsteps);
177
+ vec3 startLoc = dataToTexture(startPosition, uSize);
178
+
179
+ fragColor = vec4(0.0);
180
+
181
+ if (uMode == 0) {
182
+ castMip(startLoc, stepVec, nsteps, -rayDirection);
183
+ } else if (uMode == 2) {
184
+ castIso(startLoc, stepVec, nsteps, -rayDirection);
185
+ } else {
186
+ castComposite(startLoc, stepVec, nsteps, -rayDirection);
187
+ }
188
+
189
+ if (fragColor.a <= 0.01) {
190
+ discard;
191
+ }
192
+ }
193
+
194
+ float windowValue(float value) {
195
+ return clamp((value - uWindow.x) / max(uWindow.y - uWindow.x, 0.0001), 0.0, 1.0);
196
+ }
197
+
198
+ float safeDirection(float value) {
199
+ if (abs(value) < 0.000001) {
200
+ return value < 0.0 ? -0.000001 : 0.000001;
201
+ }
202
+
203
+ return value;
204
+ }
205
+
206
+ vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 boxMin, vec3 boxMax) {
207
+ vec3 safeRayDirection = vec3(
208
+ safeDirection(rayDirection.x),
209
+ safeDirection(rayDirection.y),
210
+ safeDirection(rayDirection.z)
211
+ );
212
+ vec3 invDirection = 1.0 / safeRayDirection;
213
+ vec3 t0 = (boxMin - rayOrigin) * invDirection;
214
+ vec3 t1 = (boxMax - rayOrigin) * invDirection;
215
+ vec3 tMin = min(t0, t1);
216
+ vec3 tMax = max(t0, t1);
217
+ float tNear = max(max(tMin.x, tMin.y), tMin.z);
218
+ float tFar = min(min(tMax.x, tMax.y), tMax.z);
219
+
220
+ return vec2(tNear, tFar);
221
+ }
222
+
223
+ float sampleRaw(vec3 texcoords) {
224
+ vec3 clampedCoords = clamp(texcoords, vec3(0.0), vec3(1.0));
225
+ ivec3 index = nearestVoxelIndex(clampedCoords * uSize - vec3(0.5), uSize);
226
+ ${n.texelType} texel = texelFetch(map, index, 0);
227
+
228
+ return float(texel.r);
229
+ }
230
+
231
+ float sampleValue(vec3 texcoords) {
232
+ return sampleRaw(texcoords) * uRescaleSlope + uRescaleIntercept;
233
+ }
234
+
235
+ vec3 transferColor(float value) {
236
+ if (uTransferPointCount <= 0) {
237
+ return vec3(windowValue(value));
238
+ }
239
+
240
+ vec4 previousPoint = uTransferPoints[0];
241
+
242
+ if (value <= previousPoint.x) {
243
+ return previousPoint.yzw;
244
+ }
245
+
246
+ for (int i = 1; i < MAX_TRANSFER_POINTS; i++) {
247
+ if (i >= uTransferPointCount) {
248
+ break;
249
+ }
250
+
251
+ vec4 currentPoint = uTransferPoints[i];
252
+
253
+ if (value <= currentPoint.x) {
254
+ float rangeValue = max(currentPoint.x - previousPoint.x, 0.0001);
255
+ float t = clamp((value - previousPoint.x) / rangeValue, 0.0, 1.0);
256
+ return mix(previousPoint.yzw, currentPoint.yzw, t);
257
+ }
258
+
259
+ previousPoint = currentPoint;
260
+ }
261
+
262
+ return previousPoint.yzw;
263
+ }
264
+
265
+ float transferOpacity(float value) {
266
+ if (uTransferPointCount <= 0) {
267
+ return windowValue(value);
268
+ }
269
+
270
+ vec2 previousPoint = uOpacityPoints[0];
271
+
272
+ if (value <= previousPoint.x) {
273
+ return previousPoint.y;
274
+ }
275
+
276
+ for (int i = 1; i < MAX_TRANSFER_POINTS; i++) {
277
+ if (i >= uTransferPointCount) {
278
+ break;
279
+ }
280
+
281
+ vec2 currentPoint = uOpacityPoints[i];
282
+
283
+ if (value <= currentPoint.x) {
284
+ float rangeValue = max(currentPoint.x - previousPoint.x, 0.0001);
285
+ float t = clamp((value - previousPoint.x) / rangeValue, 0.0, 1.0);
286
+ return mix(previousPoint.y, currentPoint.y, t);
287
+ }
288
+
289
+ previousPoint = currentPoint;
290
+ }
291
+
292
+ return previousPoint.y;
293
+ }
294
+
295
+ vec4 applyTransfer(float value) {
296
+ return vec4(transferColor(value), clamp(transferOpacity(value) * uOpacityScale, 0.0, 1.0));
297
+ }
298
+
299
+ vec4 applyLighting(float value, vec3 loc, vec3 viewRay) {
300
+ vec4 baseColor = applyTransfer(value);
301
+
302
+ if (!uLightingEnabled || baseColor.a <= 0.0) {
303
+ return baseColor;
304
+ }
305
+
306
+ vec3 gradientStep = 1.5 / max(uSize, vec3(1.0));
307
+ vec3 normal;
308
+ normal.x = sampleValue(loc + vec3(-gradientStep.x, 0.0, 0.0)) - sampleValue(loc + vec3(gradientStep.x, 0.0, 0.0));
309
+ normal.y = sampleValue(loc + vec3(0.0, -gradientStep.y, 0.0)) - sampleValue(loc + vec3(0.0, gradientStep.y, 0.0));
310
+ normal.z = sampleValue(loc + vec3(0.0, 0.0, -gradientStep.z)) - sampleValue(loc + vec3(0.0, 0.0, gradientStep.z));
311
+
312
+ if (length(normal) <= 0.0001) {
313
+ return baseColor;
314
+ }
315
+
316
+ vec3 viewDirection = normalize(viewRay);
317
+ normal = normalize(normal);
318
+
319
+ if (dot(normal, viewDirection) < 0.0) {
320
+ normal = -normal;
321
+ }
322
+
323
+ float lambert = clamp(dot(normal, viewDirection), 0.0, 1.0);
324
+ float specular = pow(max(dot(normal, viewDirection), 0.0), max(uLighting.w, 1.0));
325
+ vec3 litColor = baseColor.rgb * (uLighting.x + uLighting.y * lambert) + vec3(uLighting.z * specular);
326
+
327
+ return vec4(clamp(litColor, vec3(0.0), vec3(1.0)), baseColor.a);
328
+ }
329
+
330
+ void castMip(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
331
+ float maxValue = -1e20;
332
+ vec3 maxLoc = startLoc;
333
+ vec3 loc = startLoc;
334
+
335
+ for (int iter = 0; iter < MAX_STEPS; iter++) {
336
+ if (iter >= nsteps) {
337
+ break;
338
+ }
339
+
340
+ float value = sampleValue(loc);
341
+
342
+ if (value > maxValue) {
343
+ maxValue = value;
344
+ maxLoc = loc;
345
+ }
346
+
347
+ loc += stepVec;
348
+ }
349
+
350
+ vec3 refineStep = stepVec / float(REFINEMENT_STEPS);
351
+ loc = maxLoc - 0.5 * stepVec;
352
+
353
+ for (int i = 0; i < REFINEMENT_STEPS; i++) {
354
+ float value = sampleValue(loc);
355
+
356
+ if (value > maxValue) {
357
+ maxValue = value;
358
+ maxLoc = loc;
359
+ }
360
+
361
+ loc += refineStep;
362
+ }
363
+
364
+ float intensity = windowValue(maxValue);
365
+ vec4 color = applyTransfer(maxValue);
366
+ fragColor = vec4(color.rgb * max(intensity, 0.2), max(color.a, intensity));
367
+ }
368
+
369
+ void castComposite(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
370
+ vec4 accumulated = vec4(0.0);
371
+ vec3 loc = startLoc;
372
+ float stepLength = max(length(stepVec * uSize), 0.01);
373
+
374
+ for (int iter = 0; iter < MAX_STEPS; iter++) {
375
+ if (iter >= nsteps || accumulated.a >= 0.98) {
376
+ break;
377
+ }
378
+
379
+ float value = sampleValue(loc);
380
+ vec4 sampleColor = applyLighting(value, loc, viewRay);
381
+ sampleColor.a = clamp(sampleColor.a * stepLength, 0.0, 1.0);
382
+
383
+ accumulated.rgb += (1.0 - accumulated.a) * sampleColor.rgb * sampleColor.a;
384
+ accumulated.a += (1.0 - accumulated.a) * sampleColor.a;
385
+
386
+ loc += stepVec;
387
+ }
388
+
389
+ if (accumulated.a > 0.0) {
390
+ accumulated.rgb /= accumulated.a;
391
+ }
392
+
393
+ fragColor = accumulated;
394
+ }
395
+
396
+ void castIso(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
397
+ vec3 loc = startLoc;
398
+ float lowThreshold = uThreshold - 0.02 * max(uWindow.y - uWindow.x, 1.0);
399
+
400
+ for (int iter = 0; iter < MAX_STEPS; iter++) {
401
+ if (iter >= nsteps) {
402
+ break;
403
+ }
404
+
405
+ float value = sampleValue(loc);
406
+
407
+ if (value > lowThreshold) {
408
+ vec3 refineLoc = loc - 0.5 * stepVec;
409
+ vec3 refineStep = stepVec / float(REFINEMENT_STEPS);
410
+
411
+ for (int i = 0; i < REFINEMENT_STEPS; i++) {
412
+ value = sampleValue(refineLoc);
413
+
414
+ if (value >= uThreshold) {
415
+ fragColor = applyLighting(value, refineLoc, viewRay);
416
+ fragColor.a = max(fragColor.a, 0.95);
417
+ return;
418
+ }
419
+
420
+ refineLoc += refineStep;
421
+ }
422
+ }
423
+
424
+ loc += stepVec;
425
+ }
426
+ }
427
+ `}const E=8,ve=1024,Qe={ambient:.22,diffuse:.78,specular:.16,shininess:32};class et extends u.Object3D{constructor(e,n={}){var g;super();a(this,"stack");a(this,"nx");a(this,"ny");a(this,"nz");a(this,"size");a(this,"lx");a(this,"ly");a(this,"lz");a(this,"hx");a(this,"hy");a(this,"hz");a(this,"texture");a(this,"mesh");a(this,"maxSteps");a(this,"_mode","composite");a(this,"_window");a(this,"_threshold");a(this,"_sampleDistance",1);a(this,"_opacityScale",1);a(this,"_lightingEnabled",!0);a(this,"_lighting",{...Qe});a(this,"_transferFunction");a(this,"_disposed",!1);a(this,"_inverseMatrixWorld",new u.Matrix4);a(this,"_cameraWorldPosition",new u.Vector3);a(this,"_cameraWorldDirection",new u.Vector3);if(!e.hasSpatialVolume())throw new Error("VolumeRaycaster requires a spatial volume; use Slice Z for a frame sequence");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??ve));const r=_e(e);this._window=[...r],this._threshold=r[0]+(r[1]-r[0])*.65,this._transferFunction=re(r);const o=He(String(this.texture.internalFormat),{maxSteps:this.maxSteps,maxTransferPoints:E}),s={map:{value:this.texture},uCameraLocalPosition:{value:new u.Vector3},uCameraLocalDirection:{value:new u.Vector3(0,0,-1)},uOrthographicCamera:{value:!1},uSize:{value:R(e)},uRescaleSlope:{value:e.rescaleSlope},uRescaleIntercept:{value:e.rescaleIntercept},uMode:{value:ne[this._mode]},uWindow:{value:new u.Vector2(this._window[0],this._window[1])},uThreshold:{value:this._threshold},uSampleDistance:{value:this._sampleDistance},uOpacityScale:{value:this._opacityScale},uLightingEnabled:{value:this._lightingEnabled},uLighting:{value:be(this._lighting)},uTransferPointCount:{value:this._transferFunction.length},uTransferPoints:{value:it()},uOpacityPoints:{value:nt()}},l=new u.RawShaderMaterial({glslVersion:u.GLSL3,uniforms:s,vertexShader:Je,fragmentShader:o,side:u.BackSide,transparent:!0,depthWrite:!1}),c=new u.BoxGeometry(this.nx,this.ny,this.nz),m=U(e);c.translate(m.x,m.y,m.z),this.mesh=new u.Mesh(c,l),this.mesh.onBeforeRender=(w,_,y)=>{this.updateCameraUniforms(y)},this.add(this.mesh),this.transferFunction=this._transferFunction;const d=n.preset??(((g=e.modality)==null?void 0:g.toUpperCase())==="CT"?"ct-soft-tissue":void 0);d&&this.setPreset(d),this.applyOptions(n),this.matrixAutoUpdate=!1,this.matrix.copy(e.ijk2lps)}set mode(e){x(this,"VolumeRaycaster");const n=ne[e];if(n===void 0)throw new Error(`Unsupported volume rendering mode: ${e}`);this._mode=e,this.mesh.material.uniforms.uMode.value=n}get mode(){return this._mode}set window(e){x(this,"VolumeRaycaster");const n=Pe(e);this._window=n,this.mesh.material.uniforms.uWindow.value.set(n[0],n[1])}get window(){return[...this._window]}set threshold(e){if(x(this,"VolumeRaycaster"),!Number.isFinite(e))throw new Error(`Volume threshold must be finite, got: ${e}`);this._threshold=e,this.mesh.material.uniforms.uThreshold.value=e}get threshold(){return this._threshold}set sampleDistance(e){if(x(this,"VolumeRaycaster"),!(Number.isFinite(e)&&e>0))throw new Error(`Volume sampleDistance must be positive, got: ${e}`);this._sampleDistance=e,this.mesh.material.uniforms.uSampleDistance.value=e}get sampleDistance(){return this._sampleDistance}set opacityScale(e){if(x(this,"VolumeRaycaster"),!(Number.isFinite(e)&&e>=0))throw new Error(`Volume opacityScale must be non-negative, got: ${e}`);this._opacityScale=e,this.mesh.material.uniforms.uOpacityScale.value=e}get opacityScale(){return this._opacityScale}set lightingEnabled(e){x(this,"VolumeRaycaster"),this._lightingEnabled=e,this.mesh.material.uniforms.uLightingEnabled.value=e}get lightingEnabled(){return this._lightingEnabled}set lighting(e){x(this,"VolumeRaycaster"),this._lighting={...this._lighting,...e},this.mesh.material.uniforms.uLighting.value.copy(be(this._lighting))}get lighting(){return{...this._lighting}}set transferFunction(e){x(this,"VolumeRaycaster"),this._transferFunction=tt(e);const n=this.mesh.material.uniforms.uTransferPoints.value,r=this.mesh.material.uniforms.uOpacityPoints.value,o=this._transferFunction[this._transferFunction.length-1];for(let s=0;s<E;s++){const l=this._transferFunction[s]??o;n[s].set(l.value,l.color[0],l.color[1],l.color[2]),r[s].set(l.value,l.opacity)}this.mesh.material.uniforms.uTransferPointCount.value=this._transferFunction.length}get transferFunction(){return this._transferFunction.map(e=>({value:e.value,color:[...e.color],opacity:e.opacity}))}setPreset(e){x(this,"VolumeRaycaster");const n=Se(e);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)}resetToStackWindow(){x(this,"VolumeRaycaster");const e=_e(this.stack);this.window=e,this.threshold=e[0]+(e[1]-e[0])*.65,this.transferFunction=re(e)}get isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this._disposed=!0,this.visible=!1,this.mesh.onBeforeRender=()=>{};const{geometry:e,material:n}=this.mesh;z([()=>this.mesh.removeFromParent(),()=>this.removeFromParent(),()=>this.clear(),()=>e.dispose(),()=>n.dispose()])}applyOptions(e){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)}updateCameraUniforms(e){this._inverseMatrixWorld.copy(this.mesh.matrixWorld).invert(),e.getWorldPosition(this._cameraWorldPosition),e.getWorldDirection(this._cameraWorldDirection);const n=this.mesh.material.uniforms;n.uCameraLocalPosition.value.copy(this._cameraWorldPosition).applyMatrix4(this._inverseMatrixWorld),n.uCameraLocalDirection.value.copy(this._cameraWorldDirection).transformDirection(this._inverseMatrixWorld),n.uOrthographicCamera.value=e.isOrthographicCamera===!0}}function re(i){const[t,e]=Pe(i);return[{value:t,color:[0,0,0],opacity:0},{value:e,color:[1,1,1],opacity:1}]}function _e(i){const t=Number.isFinite(i.windowWidth)&&i.windowWidth>0?i.windowWidth:1,e=Number.isFinite(i.windowCenter)?i.windowCenter:0;return[e-t/2,e+t/2]}function Pe(i){const[t,e]=i;if(!(Number.isFinite(t)&&Number.isFinite(e)&&t<e))throw new Error(`Volume window must be [finite lower, finite upper], got: [${t}, ${e}]`);return[t,e]}function tt(i){if(i.length===0)throw new Error("Volume transferFunction must contain at least one point");if(i.length>E)throw new Error(`Volume transferFunction supports up to ${E} points, got: ${i.length}`);return[...i].sort((t,e)=>t.value-e.value).map(t=>{if(!Number.isFinite(t.value))throw new Error(`Volume transferFunction point value must be finite, got: ${t.value}`);return{value:t.value,color:[u.MathUtils.clamp(t.color[0],0,1),u.MathUtils.clamp(t.color[1],0,1),u.MathUtils.clamp(t.color[2],0,1)],opacity:u.MathUtils.clamp(t.opacity,0,1)}})}function it(){return Array.from({length:E},()=>new u.Vector4)}function nt(){return Array.from({length:E},()=>new u.Vector2)}function be(i){return new u.Vector4(i.ambient,i.diffuse,i.specular,i.shininess)}f.DEFAULT_VOLUME_MAX_STEPS=ve,f.DicomLoader=De,f.DicomParser=K,f.DicomWorkerLoader=Ee,f.MAX_VOLUME_TRANSFER_POINTS=E,f.ObliqueSlice=Ge,f.OrthoSlicer=Ze,f.Slice=A,f.Stack=q,f.VOLUME_RENDERING_MODE_VALUES=ne,f.VOLUME_RENDERING_PRESETS=xe,f.VolumeRaycaster=et,f.convertSlicePlane=X,f.createWindowTransferFunction=re,f.dicomPreloader=Ce,f.getSliceOffsetRange=ke,f.getStackBounds=ce,f.getStackCenter=U,f.getStackCorners=Q,f.getStackSize=R,f.normalizeSlicePlane=G,f.offsetSlicePlane=Be,f.resolveVolumeRenderingPreset=Se,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
@@ -0,0 +1,5 @@
1
+ export * from './parsers';
2
+ export * from './loaders';
3
+ export * from './stack';
4
+ export * from './viewers';
5
+ export * from './utils';
@@ -0,0 +1 @@
1
+ export * from './typedArrayConstructor';
@@ -0,0 +1,9 @@
1
+ import { TypedArray } from 'three';
2
+ export type TypedArrayConstructor = {
3
+ new (): TypedArray;
4
+ new (elements: Iterable<number>): TypedArray;
5
+ new (length: number): TypedArray;
6
+ new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): TypedArray;
7
+ new (array: ArrayLike<number> | ArrayBufferLike): TypedArray;
8
+ BYTES_PER_ELEMENT: number;
9
+ };
@@ -0,0 +1,38 @@
1
+ import { DicomParser } from '../parsers';
2
+ import * as THREE from 'three';
3
+ /**
4
+ * DicomLoader - загрузчик DICOM-файлов, наследуемый от THREE.Loader.
5
+ */
6
+ export declare class DicomLoader extends THREE.Loader {
7
+ constructor(manager?: THREE.LoadingManager);
8
+ /**
9
+ * Load dicom file
10
+ * @param url url
11
+ * @param onLoad Коллбэк при успешной загрузке (получает DicomParser)
12
+ * @param onProgress Коллбэк прогресса загрузки
13
+ * @param onError Коллбэк ошибки загрузки
14
+ */
15
+ load(url: string, onLoad?: (parser: DicomParser) => void, onProgress?: (progress: ProgressEvent) => void, onError?: (error: any) => void): void;
16
+ /**
17
+ * Load dicom file async
18
+ * @param url URL DICOM-файла.
19
+ * @returns Промис с объектом DicomParser.
20
+ */
21
+ loadAsync(url: string): Promise<DicomParser>;
22
+ /**
23
+ * Загружает несколько DICOM-файлов асинхронно.
24
+ * @param files dicom file array
25
+ * @returns Промис с массивом объектов DicomParser.
26
+ */
27
+ loadMultipleAsync(files: File[]): Promise<DicomParser[]>;
28
+ /**
29
+ * Загружает несколько серий DICOM-файлов асинхронно.
30
+ * @param series Массив серий DICOM (каждая серия - массив файлов).
31
+ * @returns Промис с массивом массивов объектов DicomParser (соответствует входным сериям).
32
+ */
33
+ loadMultipleSeriesAsync(series: {
34
+ dicomFiles: {
35
+ file: File;
36
+ }[];
37
+ }[]): Promise<DicomParser[][]>;
38
+ }
@@ -0,0 +1,28 @@
1
+ import { ImageOrientation, ImagePosition } from '../stack/seriesOrder';
2
+ export interface DicomFile {
3
+ file: File;
4
+ SOPInstanceUID: string;
5
+ rows: number;
6
+ columns: number;
7
+ numberOfFrames: number;
8
+ bitsAllocated: number;
9
+ pixelRepresentation: number;
10
+ samplesPerPixel: number;
11
+ sliceLocation?: number;
12
+ /** Compatibility field only; ordering uses the complete position and orientation. */
13
+ imagePositionZ?: number;
14
+ imagePosition?: ImagePosition;
15
+ imageOrientation?: ImageOrientation;
16
+ modality?: string;
17
+ instanceNumber?: number;
18
+ }
19
+ export interface Series {
20
+ seriesInstanceUID: string;
21
+ dicomFiles: DicomFile[];
22
+ }
23
+ /**
24
+ * Allows to group dicom files into series and order then within a series
25
+ * @param files dicom file array
26
+ * @returns promise with series
27
+ */
28
+ export declare const dicomPreloader: (files: FileList | File[]) => Promise<Series[]>;