dicom-three 0.1.0 → 0.2.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.
@@ -1,4 +1,4 @@
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;
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,R,S){"use strict";var st=Object.defineProperty;var at=(f,P,R)=>P in f?st(f,P,{enumerable:!0,configurable:!0,writable:!0,value:R}):f[P]=R;var a=(f,P,R)=>at(f,typeof P!="symbol"?P+"":P,R);var J=typeof document<"u"?document.currentScript:null;function De(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=De(S);class K{constructor(t){a(this,"_dataSet");a(this,"_arrayBuffer");this._arrayBuffer=t.buffer;try{const e=new Uint8Array(this._arrayBuffer);this._dataSet=R.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 Fe 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 $(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=>$(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 Re=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=R.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),x=w==null?void 0:w[2],v=c.intString("x00200013"),T=c.uint16("x00280010")??-1,D=c.uint16("x00280011")??-1;if(T<=0||D<=0)throw new Error(`Invalid DICOM dimensions: rows=${T}, columns=${D}`);const F={file:s,SOPInstanceUID:d,rows:T,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:x,imagePosition:w,imageOrientation:_,modality:c.string("x00080060"),instanceNumber:v};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=Re(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 Ae{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 Ve(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 Oe(i,t,e,n){const{rows:r,columns:o,numberOfFrames:s,bitsAllocated:l,samplesPerPixel:c,signed:m}=t,d=Ve(l,m),g=new d(r*o*c*s);let w=0,_=0;for await(const x of i){e==null||e(x,_);const{imageFrame:v}=await x.extractPixelData(),T=x.numberOfFrames??1,D=r*o*c*T;if(v.byteLength<D*d.BYTES_PER_ELEMENT)throw new Error(`Pixel data length mismatch: expected ${D}, got ${v.length}`);const F=new d(v.buffer,v.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 k=.001,le=1e-4;function Ue(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 Le(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 ze(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,I)=>p-e.imagePosition[I]))<=k),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,I)=>Math.abs(p-g[I])>V)&&b("Inconsistent image orientations"),h.pixelSpacing&&h.pixelSpacing.some((p,I)=>!Le(p,w[I]))&&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,x=_[0];let v,T=x.spacingBetweenSlices??void 0;if(d){const h=oe(g);if(i.length>1){const p=x.imagePosition,I=_[_.length-1].imagePosition;v=p.map((E,Z)=>(I[Z]-E)/(i.length-1)),T=$(v,h),T<=k&&b("Duplicate or coplanar slice positions");const B=Math.max(k,Math.hypot(...v)*le);for(let E=1;E<_.length;E++){const Z=_[E].imagePosition;$(Z,h)-$(_[E-1].imagePosition,h)<=k&&b("Duplicate or coplanar slice positions"),Math.hypot(...Z.map((ot,Te)=>ot-p[Te]-E*v[Te]))>B&&b("Irregular slice positions")}}else{const p=T??x.sliceThickness??1;v=h.map(I=>I*p)}}else v=[0,0,0];const D={imageOrientation:g,imagePosition:[...x.imagePosition??[0,0,0]],pixelSpacing:[...w],sliceThickness:x.sliceThickness??1,spacingBetweenSlices:T,sliceStep:v,frameAxis:d?"space":"sequence",windowWidth:x.windowWidth,windowCenter:x.windowCenter,rescaleSlope:x.rescaleSlope,rescaleIntercept:x.rescaleIntercept,modality:x.modality,distanceSourceToDetector:x.distanceSourceToDetector,distanceSourceToPatient:x.distanceSourceToPatient,positionerPrimaryAngle:x.positionerPrimaryAngle,positionerSecondaryAngle:x.positionerSecondaryAngle},F=new Map(i.map((h,p)=>[h,p]));return{geometry:D,order:_.map(h=>F.get(h))}}function Ne(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 We(i,t,e){const n=[],r=await Oe(i,t,(l,c)=>{for(const m of Ue(l,c))n.push(m)}),{geometry:o,order:s}=ze(n);return Ne(r,s,t.rows*t.columns*t.samplesPerPixel),{...t,...o,pixelData:r}}function Be(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 Ae(this)}static async create(t){const e=Be(t);return new q([...t],await We(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,x=this.columns,v=new u.Vector3(w,0,0),T=new u.Vector3(0,0,-g),D=new u.Vector3((-x/2+.5)*w,-n,(_/2-.5)*g),F=v.clone().applyMatrix3(d),h=T.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 I=F.clone().normalize(),B=h.clone().normalize();this.imageOrientation=[I.x,I.y,I.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 M(i){return new S.Vector3(i.columns,i.rows,i.numberOfFrames)}function U(i){return M(i).subScalar(1).multiplyScalar(.5)}function ce(i){return new S.Box3(new S.Vector3(-.5,-.5,-.5),M(i).subScalar(.5))}function Q(i){const{min:t,max:e}=ce(i);return[new S.Vector3(t.x,t.y,t.z),new S.Vector3(e.x,t.y,t.z),new S.Vector3(e.x,e.y,t.z),new S.Vector3(t.x,e.y,t.z),new S.Vector3(t.x,t.y,e.z),new S.Vector3(e.x,t.y,e.z),new S.Vector3(e.x,e.y,e.z),new S.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 S.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 S.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 $e(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 qe=`in vec3 position;
2
2
 
3
3
  uniform mat4 modelViewMatrix;
4
4
  uniform mat4 projectionMatrix;
@@ -26,7 +26,7 @@ float windowRawValue(float rawValue) {
26
26
  float value = rawValue * uRescaleSlope + uRescaleIntercept;
27
27
  return clamp((value - uWindowCenter) / uWindowWidth + 0.5, 0.0, 1.0);
28
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`
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 je(i){const t=ge[i];if(!Object.prototype.hasOwnProperty.call(ge,i))throw new Error(`Unsupported oblique slice texture internalFormat: ${i}`);return`
30
30
  precision highp float;
31
31
  precision highp int;
32
32
  precision highp ${t.samplerType};
@@ -57,7 +57,7 @@ void main() {
57
57
 
58
58
  fragColor = vec4(pixelValue, pixelValue, pixelValue, 1.0);
59
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;
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 y(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 Ge{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 Xe 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 Ge(e);const s=this.intersection.intersect(this._plane);this.texture=e.textureFactory.data3DTexture;const l=je(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){y(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){y(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:M(this.stack)},...n},vertexShader:qe,fragmentShader:e,side:u.DoubleSide})}}var Ye=`in vec3 position;
61
61
 
62
62
  uniform mat4 modelViewMatrix;\r
63
63
  uniform mat4 projectionMatrix;
@@ -67,7 +67,7 @@ out vec3 vPosition;
67
67
  void main() {\r
68
68
  vPosition = position;\r
69
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)=>`
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 Ze(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,l)=>`
71
71
  precision highp float;
72
72
  precision highp int;
73
73
  precision highp ${e};
@@ -75,6 +75,7 @@ precision highp ${e};
75
75
  uniform ${e} map;
76
76
  uniform int ${o};
77
77
  uniform vec3 uSize;
78
+ uniform bool uLinearInterpolation;
78
79
 
79
80
  in vec3 vPosition;
80
81
  out vec4 fragColor;
@@ -82,15 +83,39 @@ out vec4 fragColor;
82
83
  ${ee}
83
84
  ${fe}
84
85
 
86
+ float sampleRaw(ivec3 index) {
87
+ ${n} texel = texelFetch(map, index, 0);
88
+ return float(texel.r);
89
+ }
90
+
91
+ float sampleLinear(vec3 dataPosition) {
92
+ vec3 position = clamp(dataPosition, vec3(0.0), uSize - vec3(1.0));
93
+ ivec3 lower = ivec3(floor(position));
94
+ ivec3 upper = min(lower + ivec3(1), ivec3(uSize) - ivec3(1));
95
+ vec2 weight = fract(position.${l});
96
+
97
+ ivec3 lowerRight = lower;
98
+ lowerRight.${l[0]} = upper.${l[0]};
99
+ ivec3 upperLeft = lower;
100
+ upperLeft.${l[1]} = upper.${l[1]};
101
+ ivec3 upperRight = lower;
102
+ upperRight.${l} = upper.${l};
103
+
104
+ float firstRow = mix(sampleRaw(lower), sampleRaw(lowerRight), weight.x);
105
+ float secondRow = mix(sampleRaw(upperLeft), sampleRaw(upperRight), weight.x);
106
+ return mix(firstRow, secondRow, weight.y);
107
+ }
108
+
85
109
  void main() {
86
110
  // Geometry is embedded in IJK; the mesh translates only along the selected axis.
87
111
  vec3 dataPosition = ${s};
88
- ivec3 index = nearestVoxelIndex(dataPosition, uSize);
89
- ${n} texel = texelFetch(map, index, 0);
90
- float pixelValue = windowRawValue(float(texel.r));
112
+ float rawValue = uLinearInterpolation
113
+ ? sampleLinear(dataPosition)
114
+ : sampleRaw(nearestVoxelIndex(dataPosition, uSize));
115
+ float pixelValue = windowRawValue(rawValue);
91
116
  fragColor = vec4(pixelValue, pixelValue, pixelValue, 1.0);
92
117
  }
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;
118
+ `;return{fragmentX:r("ix","vec3(float(ix), vPosition.y, vPosition.z)","yz"),fragmentY:r("iy","vec3(vPosition.x, float(iy), vPosition.z)","xz"),fragmentZ:r("iz","vec3(vPosition.x, vPosition.y, float(iz))","xy")}}const xe={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(xe,n))throw new Error(`Unsupported slice axis: ${n}; expected x, y or z`);de(e),this.stack=e,this.axis=n,this.config=xe[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),s=ye(r.interpolation??"nearest");this.texture=e.textureFactory.data3DTexture;const l=Ze(String(this.texture.internalFormat));this.mesh=new u.Mesh(this.config.geometry(e),this.createMaterial(l[this.config.fragment],o,s)),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){y(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}get interpolation(){return this.material.uniforms.uLinearInterpolation.value?"linear":"nearest"}set interpolation(e){y(this,"Slice");const n=ye(e);n!==this.material.uniforms.uLinearInterpolation.value&&(this.material.uniforms.uLinearInterpolation.value=n,this.dispatchEvent({type:"change",reason:"interpolation"}))}setWindow(e,n){y(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,r){return new u.RawShaderMaterial({glslVersion:u.GLSL3,uniforms:{map:{value:this.texture},uSize:{value:M(this.stack)},uLinearInterpolation:{value:r},...this.config.uniforms(this._index),...n},vertexShader:Ye,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}`)}}function ye(i){if(i!=="nearest"&&i!=="linear")throw new Error(`Unsupported slice interpolation: ${i}`);return i==="linear"}class Je 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){y(this,"OrthoSlicer"),this.sliceX.index=e}get ix(){return this.sliceX.index}set iy(e){y(this,"OrthoSlicer"),this.sliceY.index=e}get iy(){return this.sliceY.index}set iz(e){y(this,"OrthoSlicer"),this.sliceZ.index=e}get iz(){return this.sliceZ.index}setWindow(e,n){y(this,"OrthoSlicer");const r=[this.sliceX,this.sliceY,this.sliceZ];for(const o of r)y(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 ve={"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:ve[i]}const ne={mip:0,composite:1,iso:2};var Ke=`in vec3 position;
94
119
 
95
120
  uniform mat4 modelViewMatrix;
96
121
  uniform mat4 projectionMatrix;
@@ -100,7 +125,7 @@ out vec3 vPosition;
100
125
  void main() {
101
126
  vPosition = position;
102
127
  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`
128
+ }`;const He={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 Qe(i,{maxSteps:t,maxTransferPoints:e}){const n=He[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
129
  precision highp float;
105
130
  precision highp int;
106
131
  precision highp ${n.samplerType};
@@ -424,4 +449,4 @@ void castIso(vec3 startLoc, vec3 stepVec, int nsteps, vec3 viewRay) {
424
449
  loc += stepVec;
425
450
  }
426
451
  }
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"})});
452
+ `}const C=8,_e=1024,et={ambient:.22,diffuse:.78,specular:.16,shininess:32};class tt 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",{...et});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??_e));const r=Pe(e);this._window=[...r],this._threshold=r[0]+(r[1]-r[0])*.65,this._transferFunction=re(r);const o=Qe(String(this.texture.internalFormat),{maxSteps:this.maxSteps,maxTransferPoints:C}),s={map:{value:this.texture},uCameraLocalPosition:{value:new u.Vector3},uCameraLocalDirection:{value:new u.Vector3(0,0,-1)},uOrthographicCamera:{value:!1},uSize:{value:M(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:Ie(this._lighting)},uTransferPointCount:{value:this._transferFunction.length},uTransferPoints:{value:nt()},uOpacityPoints:{value:rt()}},l=new u.RawShaderMaterial({glslVersion:u.GLSL3,uniforms:s,vertexShader:Ke,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,_,x)=>{this.updateCameraUniforms(x)},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){y(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){y(this,"VolumeRaycaster");const n=be(e);this._window=n,this.mesh.material.uniforms.uWindow.value.set(n[0],n[1])}get window(){return[...this._window]}set threshold(e){if(y(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(y(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(y(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){y(this,"VolumeRaycaster"),this._lightingEnabled=e,this.mesh.material.uniforms.uLightingEnabled.value=e}get lightingEnabled(){return this._lightingEnabled}set lighting(e){y(this,"VolumeRaycaster"),this._lighting={...this._lighting,...e},this.mesh.material.uniforms.uLighting.value.copy(Ie(this._lighting))}get lighting(){return{...this._lighting}}set transferFunction(e){y(this,"VolumeRaycaster"),this._transferFunction=it(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<C;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){y(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(){y(this,"VolumeRaycaster");const e=Pe(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]=be(i);return[{value:t,color:[0,0,0],opacity:0},{value:e,color:[1,1,1],opacity:1}]}function Pe(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 be(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 it(i){if(i.length===0)throw new Error("Volume transferFunction must contain at least one point");if(i.length>C)throw new Error(`Volume transferFunction supports up to ${C} 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 nt(){return Array.from({length:C},()=>new u.Vector4)}function rt(){return Array.from({length:C},()=>new u.Vector2)}function Ie(i){return new u.Vector4(i.ambient,i.diffuse,i.specular,i.shininess)}f.DEFAULT_VOLUME_MAX_STEPS=_e,f.DicomLoader=Fe,f.DicomParser=K,f.DicomWorkerLoader=Ee,f.MAX_VOLUME_TRANSFER_POINTS=C,f.ObliqueSlice=Xe,f.OrthoSlicer=Je,f.Slice=A,f.Stack=q,f.VOLUME_RENDERING_MODE_VALUES=ne,f.VOLUME_RENDERING_PRESETS=ve,f.VolumeRaycaster=tt,f.convertSlicePlane=X,f.createWindowTransferFunction=re,f.dicomPreloader=Ce,f.getSliceOffsetRange=ke,f.getStackBounds=ce,f.getStackCenter=U,f.getStackCorners=Q,f.getStackSize=M,f.normalizeSlicePlane=G,f.offsetSlicePlane=$e,f.resolveVolumeRenderingPreset=Se,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
@@ -1,9 +1,9 @@
1
1
  import { Stack } from '../../stack';
2
- import { Slice, SliceAxis } from '../slice/slice';
2
+ import { Slice, SliceAxis, SliceEventMap } from '../slice/slice';
3
3
  import * as THREE from 'three';
4
4
  export interface OrthoSlicerEventMap extends THREE.Object3DEventMap {
5
5
  change: {
6
- reason: 'index' | 'window' | 'dispose';
6
+ reason: SliceEventMap['change']['reason'] | 'dispose';
7
7
  axis?: SliceAxis;
8
8
  };
9
9
  dispose: {};
@@ -1,14 +1,16 @@
1
1
  import { Stack } from '../../stack';
2
2
  import * as THREE from 'three';
3
3
  export type SliceAxis = 'x' | 'y' | 'z';
4
+ export type SliceInterpolation = 'nearest' | 'linear';
4
5
  export interface SliceOptions {
5
6
  index?: number;
6
7
  windowCenter?: number;
7
8
  windowWidth?: number;
9
+ interpolation?: SliceInterpolation;
8
10
  }
9
11
  export interface SliceEventMap extends THREE.Object3DEventMap {
10
12
  change: {
11
- reason: 'index' | 'window';
13
+ reason: 'index' | 'window' | 'interpolation';
12
14
  };
13
15
  dispose: {};
14
16
  }
@@ -32,6 +34,8 @@ export declare class Slice extends THREE.Object3D<SliceEventMap> {
32
34
  set windowWidth(value: number);
33
35
  get geometry(): THREE.BufferGeometry;
34
36
  get material(): THREE.RawShaderMaterial;
37
+ get interpolation(): SliceInterpolation;
38
+ set interpolation(value: SliceInterpolation);
35
39
  setWindow(center: number, width: number): void;
36
40
  get isDisposed(): boolean;
37
41
  dispose(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dicom-three",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",