Math.max(b,D))continue;f.invalidated&&this._throttledCalculateCachedStats(f,n);let O=!1;if((P===b||P===D)&&(O=!0),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let A;if(!ii(u))continue;!mi(u)&&!this.editData&&y!==null&&O&&(A=[m[y]]),A&&ur(i,u,"0",A,{color:C});let V=x;if(O||(V=2),Tm(i,u,"0",m[0],m[3],{color:C,lineDash:V,lineWidth:w}),o=!0,this.configuration.showTextBox){const R=this.getLinkedTextBoxStyle(c,f);if(!R.visibility){d.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const N=this.configuration.getTextLines(d,{metadata:h});if(!N||N.length===0)continue;if(!d.handles.textBox.hasMoved){const Ie=Aa(m);d.handles.textBox.worldPosition=a.canvasToWorld(Ie)}const F=a.worldToCanvas(d.handles.textBox.worldPosition),X=uo(i,u,"1",N,F,m,{},R),{x:te,y:fe,width:le,height:de}=X;d.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([te,fe]),topRight:a.canvasToWorld([te+le,fe]),bottomLeft:a.canvasToWorld([te,fe+de]),bottomRight:a.canvasToWorld([te+le,fe+de])}}}return o},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=qo(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=qh(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_computeProjectionPoints(e,r){const{data:n,metadata:i}=e,{viewPlaneNormal:o,spacingInNormal:a}=i,{imageData:s}=r,{startCoordinate:c,endCoordinate:l}=n,{points:f}=n.handles,u=Pg(s,f[0]),d=Pg(s,f[0]),h=Ge();s.indexToWorldVec3(u,h);const g=Ge();s.indexToWorldVec3(d,g),this._getIndexOfCoordinatesForViewplaneNormal(o)==2?(h[2]=c,g[2]=l):this._getIndexOfCoordinatesForViewplaneNormal(o)==0?(h[0]=c,g[0]=l):this._getIndexOfCoordinatesForViewplaneNormal(o)==1&&(h[1]=c,g[1]=l);const p=no(h,g),v=[];for(let y=0;y{const w=Ge();return An(w,m,o,y),Array.from(w)}));n.cachedStats.projectionPoints=v}_computePointsInsideVolume(e,r,n,i){var S,T,_;const{data:o,metadata:a}=e,{viewPlaneNormal:s,viewUp:c}=a,{viewport:l}=i,f=o.cachedStats.projectionPoints,u=[[]],d=this.getTargetImageData(r),h=o.handles.points[0],g=o.handles.points[3],{worldWidth:p,worldHeight:v}=Bw(s,c,h,g),y=La(d,o.habdles),m=Math.abs(p*v)/(y.scale*y.scale),w={isPreScaled:ql(l,r),isSuvScaled:this.isSuvScaled(l,r,e.metadata.referencedImageId)},x=Xl(a.Modality,e.metadata.referencedImageId,w);for(let E=0;E{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Se(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getTargetId(l);let p,v;if(l instanceof mr)p=g.split("imageId:")[1];else{v=Jc(g);const x=Fe.getVolume(v);p=Vl(x,s,d)}const y=l.getFrameOfReferenceUID(),m={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...d],enabledElement:c,viewUp:[...h],FrameOfReferenceUID:y,referencedImageId:p,toolName:this.getToolName(),volumeId:v},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:null,worldBoundingBox:null},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},segmentationId:null}};ln(m,a);const w=Ot(a,this.getToolName());return this.editData={annotation:m,viewportIdsToRender:w,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ft(a),n.preventDefault(),Ne(w),m},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=pn(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(S));l.annotationUID=d;const y=this.getStyle("lineWidth",l,u),m=this.getStyle("lineDash",l,u),w=this.getStyle("color",l,u);if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;cn(u,s);let x;if(!ii(d))continue;!mi(d)&&!this.editData&&p!==null&&(x=[v[p]]),x&&ur(i,d,"0",x,{color:w}),Tm(i,d,"0",v[0],v[3],{color:w,lineDash:m,lineWidth:y}),o=!0}return o}}}C8.toolName="RectangleROIThreshold";function MG(t,e,r={}){const n=[];return t.forEach(o=>{var h,g;const{data:a}=o,{points:s}=a.handles,{imageData:c,dimensions:l}=e;let f=s;if((h=a.cachedStats)!=null&&h.projectionPoints){const{projectionPoints:p}=a.cachedStats;f=[].concat(...p)}const u=f.map(p=>ei(c,p));let d=ef(u,l);r.numSlicesToProject&&!((g=a.cachedStats)!=null&&g.projectionPoints)&&(d=oG(d,r.numSlicesToProject)),n.push(d)}),n.length===1?n[0]:n.reduce((o,a)=>({iMin:Math.min(o.iMin,a.iMin),jMin:Math.min(o.jMin,a.jMin),kMin:Math.min(o.kMin,a.kMin),iMax:Math.max(o.iMax,a.iMax),jMax:Math.max(o.jMax,a.jMax),kMax:Math.max(o.kMax,a.kMax)}),{iMin:1/0,jMin:1/0,kMin:1/0,iMax:-1/0,jMax:-1/0,kMax:-1/0})}function uxe(t,e,r,n){const i=t.map(s=>Zr.getAnnotation(s));fxe(i);let o;for(let s=0;s{if(!Yt(f,t[0].dimensions)||!Yt(l,t[0].direction)||!Yt(d,t[0].spacing)||!Yt(u,t[0].origin))throw new Error("labelmaps must have the same size and shape")});const n=t[0],i=n.voxelManager.getConstructor(),o=new i(n.voxelManager.getScalarDataLength());t.forEach(l=>{const f=l.voxelManager,u=f.getScalarDataLength();for(let d=0;d0;)g(f.pop());return{flooded:u};function g(_){const E=_.currentArgs,b=_.previousArgs;p(E)||(v(E),y(E)?(m(E),x(E)):w(b))}function p(_){const[E,b,D=0]=_,I=E+32768+65536*(b+32768+65536*(D+32768));return d.has(I)}function v(_){const[E,b,D=0]=_,I=E+32768+65536*(b+32768+65536*(D+32768));d.add(I)}function y(_){const E=C(_);return o?o(E,c):E===c}function m(_){u.push(_),n&&n(..._)}function w(_){const[E,b,D=0]=_,I=E+32768+65536*(b+32768+65536*(D+32768));h==null||h.set(I,_),i&&i(..._)}function x(_){for(let E=0;E{const{segmentIndex:e,previewSegmentIndex:r,segmentationVoxelManager:n,centerIJK:i,viewPlaneNormal:o,segmentationImageData:a,configuration:s}=t;if(!(s!=null&&s.useCenterSegmentIndex))return;let c=!1,l=!1;const f=[...n.getBoundsIJK()];Math.abs(o[0])>.8?f[0]=[i[0],i[0]]:Math.abs(o[1])>.8?f[1]=[i[1],i[1]]:Math.abs(o[2])>.8&&(f[2]=[i[2],i[2]]);const u=({value:h})=>{c||(c=h===e),l||(l=h===r)};if(n.forEach(u,{imageData:a,isInObject:t.isInObject,boundsIJK:f}),!c&&!l){t.centerSegmentIndexInfo.segmentIndex=null;return}const d=n.getAtIJKPoint(i);t.centerSegmentIndexInfo.segmentIndex=d,t.centerSegmentIndexInfo.hasSegmentIndex=c,t.centerSegmentIndexInfo.hasPreviewIndex=l}},mxe={[It.Initialize]:t=>{var y;const{operationName:e,centerIJK:r,segmentationVoxelManager:n,imageVoxelManager:i,configuration:o,segmentIndex:a,viewport:s}=t;if(!((y=o==null?void 0:o.threshold)!=null&&y.isDynamic)||!r||!a||e===It.RejectPreview||e===It.OnInteractionEnd)return;const c=n.getBoundsIJK(),{range:l,dynamicRadius:f=0}=o.threshold,u=l?0:f,{viewPlaneNormal:d}=s.getCamera(),h=c.map((m,w)=>{const[x,C]=m;return[Math.max(x,r[w]-u),Math.min(C,r[w]+u)]});Math.abs(d[0])>.8?h[0]=[r[0],r[0]]:Math.abs(d[1])>.8?h[1]=[r[1],r[1]]:Math.abs(d[2])>.8&&(h[2]=[r[2],r[2]]);const g=l||[1/0,-1/0],p=u*u,v=({value:m,pointIJK:w})=>{if(oS(r,w)>p)return;const C=Array.isArray(m)?mh(m):m;g[0]=Math.min(C,g[0]),g[1]=Math.max(C,g[1])};i.forEach(v,{boundsIJK:h}),o.threshold.range=g},[It.OnInteractionStart]:t=>{var r;const{configuration:e}=t;(r=e==null?void 0:e.threshold)!=null&&r.isDynamic&&(e.threshold.range=null)},[It.ComputeInnerCircleRadius]:t=>{const{configuration:e,viewport:r}=t,{dynamicRadius:n=0,isDynamic:i}=e.threshold;if(!i){e.threshold.dynamicRadiusInCanvas=0;return}if(n===0)return;const o=r.getImageData();if(!o)return;const{spacing:a}=o,s=[r.element.clientWidth/2,r.element.clientHeight/2],c=n*a[0],f=r.canvasToWorld(s).map(h=>h+c),u=r.worldToCanvas(f),d=Math.abs(s[0]-u[0]);e.threshold.dynamicRadiusInCanvas||(e.threshold.dynamicRadiusInCanvas=0),e.threshold.dynamicRadiusInCanvas=3+d}},vxe={[It.Initialize]:t=>{t.segmentIndex=0}},{isEqual:I3}=Vn,YI={toIJK:t=>t,fromIJK:t=>t,type:"acquistion"},yxe={toIJK:([t,e,r])=>[r,t,e],fromIJK:([t,e,r])=>[e,r,t],type:"jk"},wxe={toIJK:([t,e,r])=>[t,r,e],fromIJK:([t,e,r])=>[t,r,e],type:"ik"};function RG(t,e){if(!(t instanceof Or))return{...YI,boundsIJKPrime:e};const{viewPlaneNormal:r}=t.getCamera(),n=I3(Math.abs(r[0]),1)&&yxe||I3(Math.abs(r[1]),1)&&wxe||I3(Math.abs(r[2]),1)&&YI;return n?{...n,boundsIJKPrime:n.fromIJK(e)}:{toIJK:null,boundsIJKPrime:null,fromIJK:null,error:`Only mappings orthogonal to acquisition plane are permitted, but requested ${r}`}}const{RLEVoxelMap:xxe,VoxelManager:Cxe}=Vn,Sxe=65535;var yo;(function(t){t[t.SEGMENT=-1]="SEGMENT",t[t.ISLAND=-2]="ISLAND",t[t.INTERIOR=-3]="INTERIOR",t[t.EXTERIOR=-4]="EXTERIOR",t[t.INTERIOR_SMALL=-5]="INTERIOR_SMALL",t[t.INTERIOR_TEST=-6]="INTERIOR_TEST"})(yo||(yo={}));class Od{constructor(e){this.fillInternalEdge=!1,this.maxInternalRemove=128,this.maxInternalRemove=(e==null?void 0:e.maxInternalRemove)??this.maxInternalRemove,this.fillInternalEdge=(e==null?void 0:e.fillInternalEdge)??this.fillInternalEdge}initialize(e,r,n){const i=!!r.sourceVoxelManager,o=i?r.sourceVoxelManager:r,a=i?r:Cxe.createRLEHistoryVoxelManager(o),{segmentIndex:s=1,previewSegmentIndex:c=1}=n,l=n.points||o.getPoints();if(!(l!=null&&l.length))return;const f=o.getBoundsIJK().map((x,C)=>[Math.min(x[0],...l.map(S=>S[C])),Math.max(x[1],...l.map(S=>S[C]))]);if(f.find(x=>x[0]<0||x[1]>Sxe))return;const{toIJK:u,fromIJK:d,boundsIJKPrime:h,error:g}=RG(e,f);if(g){console.warn("Not performing island removal for planes not orthogonal to acquisition plane",g);return}const[p,v,y]=d(o.dimensions),m=new xxe(p,v,y),w=(x,C,S)=>{const T=o.toIndex(u([x,C,S])),_=o.getAtIndex(T);if(_===c||_===s)return yo.SEGMENT};return m.fillFrom(w,h),m.normalizer={toIJK:u,fromIJK:d,boundsIJKPrime:h},this.segmentSet=m,this.previewVoxelManager=a,this.segmentIndex=s,this.previewSegmentIndex=c??s,this.selectedPoints=l,!0}floodFillSegmentIsland(){const{selectedPoints:e,segmentSet:r}=this;let n=0;const{fromIJK:i}=r.normalizer;return e.forEach(o=>{const a=i(o),s=r.toIndex(a),[c,l,f]=a;r.get(s)===yo.SEGMENT&&(n+=r.floodFill(c,l,f,yo.ISLAND))}),n}removeExternalIslands(){const{previewVoxelManager:e,segmentSet:r}=this,{toIJK:n}=r.normalizer,i=(o,a)=>{const[,s,c]=r.toIJK(o);if(a.value!==yo.ISLAND)for(let l=a.start;l{let f;for(const u of[...l])if(u.value===yo.ISLAND){if(!f){if(this.fillInternalEdge&&u.start>0)for(let d=0;d{if(l.value!==yo.INTERIOR)return;const[,f,u]=e.toIJK(c),d=f>0?e.getRun(f-1,u):null,h=f+12&&(!v||!y)&&e.floodFill(l.start,f,u,yo.EXTERIOR,{singlePlane:!0})}),e.forEach((c,l)=>{if(l.value!==yo.INTERIOR)return;const[,f,u]=e.toIJK(c),g=e.floodFill(l.start,f,u,yo.INTERIOR_TEST)>this.maxInternalRemove?yo.EXTERIOR:yo.INTERIOR_SMALL;e.floodFill(l.start,f,u,g)}),e.forEach((c,l)=>{if(l.value===yo.INTERIOR_SMALL)for(let f=l.start;f=o.start&&n=i))return!0;return!1}}const Txe={[It.OnInteractionEnd]:t=>{const{previewSegmentIndex:e,segmentIndex:r,viewport:n,segmentationVoxelManager:i,activeStrategy:o,memo:a}=t;if(o!=="THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL"||r===null)return;const s=new Od,c=(a==null?void 0:a.voxelManager)||i;if(!s.initialize(n,c,{previewSegmentIndex:e,segmentIndex:r}))return;s.floodFillSegmentIsland(),s.removeExternalIslands(),s.removeInternalIslands();const l=c.getArrayOfModifiedSlices();l&&bo(t.segmentationId,l,e)}},_xe={[It.Preview]:function(t){var o,a;const{previewSegmentIndex:e,configuration:r,enabledElement:n}=t;if(!e||!r)return;(o=this.onInteractionStart)==null||o.call(this,n,t);const i=this.fill(n,t);return i&&((a=this.onInteractionEnd)==null||a.call(this,n,t)),i},[It.Initialize]:t=>{const{segmentIndex:e,previewColor:r,previewSegmentIndex:n}=t;if(n==null||e==null)return;const i=Zh(t.segmentationId);i==null||i.forEach(o=>{fB(o,t.segmentationId,n,r)})},[It.AcceptPreview]:t=>{const{previewSegmentIndex:e,segmentationVoxelManager:r,memo:n,segmentIndex:i,centerSegmentIndexInfo:o}=t||{},{changedIndices:a}=o||{},s=n,c=({index:l})=>{const f=r.getAtIndex(l);(a==null?void 0:a.length)>0?a.includes(l)&&s.voxelManager.setAtIndex(l,0):f===e&&s.voxelManager.setAtIndex(l,i)};r.forEach(c),bo(t.segmentationId,r.getArrayOfModifiedSlices(),i),t.centerSegmentIndexInfo.changedIndices=[]},[It.RejectPreview]:t=>{t&&gV.undoIf(e=>{const r=e;if(!(r!=null&&r.voxelManager))return!1;const{segmentationVoxelManager:n}=r;let i=!1;const o=({value:a})=>{a===t.previewSegmentIndex&&(i=!0)};return n.forEach(o),i})}},Exe={[It.Fill]:t=>{var l;const{segmentsLocked:e,segmentationImageData:r,segmentationVoxelManager:n,brushStrategy:i,centerIJK:o}=t,a=(l=i.createIsInThreshold)==null?void 0:l.call(i,t),{setValue:s}=i,c=a?f=>{const{value:u,index:d}=f;e.includes(u)||!a(d)||s(t,f)}:f=>s(t,f);n.forEach(c,{imageData:r,isInObject:t.isInObject,boundsIJK:t.isInObjectBoundsIJK}),n.addPoint(o)}};function bxe({operationData:t,existingValue:e,index:r}){const{previewSegmentIndex:n,memo:i,centerSegmentIndexInfo:o,previewOnHover:a,segmentIndex:s}=t,{hasPreviewIndex:c,hasSegmentIndex:l,segmentIndex:f}=o;if(f===0&&l&&c){if(e===s||a)return;if(e===n){i.voxelManager.setAtIndex(r,0);return}return}if(f===0&&l&&!c){if(e===0||e!==s)return;i.voxelManager.setAtIndex(r,n),o.changedIndices.push(r);return}if(f===0&&!l&&c){if(e===s||a)return;if(e===n){i.voxelManager.setAtIndex(r,0);return}return}if(f===0&&!l&&!c){if(e===s)return;if(e===n){i.voxelManager.setAtIndex(r,n);return}return}if(f===n&&l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===n&&!l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===s&&l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===s&&l&&!c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}}const Dxe={[It.INTERNAL_setValue]:(t,{value:e,index:r})=>{const{segmentsLocked:n,previewSegmentIndex:i,memo:o,segmentationVoxelManager:a,centerSegmentIndexInfo:s,segmentIndex:c}=t,l=a.getAtIndex(r);if(!n.includes(e)&&!(!s&&l===c)&&!((s==null?void 0:s.segmentIndex)!==0&&l===c)){if((s==null?void 0:s.segmentIndex)===null){o.voxelManager.setAtIndex(r,i??c);return}if(!i){let f=c;s&&(f=s.segmentIndex),o.voxelManager.setAtIndex(r,f);return}bxe({operationData:t,existingValue:l,index:r})}}},Ixe={[It.CreateIsInThreshold]:t=>{const{imageVoxelManager:e,segmentIndex:r,configuration:n}=t;if(!(!n||!r))return i=>{var c;const o=e.getAtIndex(i),a=Array.isArray(o)?sa(o):o,{threshold:s}=n||{};return(c=s==null?void 0:s.range)!=null&&c.length?s.range[0]<=a&&a<=s.range[1]:!0}}},JI=10;function v5(){return{maxIJKs:[]}}function LG(t,e){const{value:r}=e,{maxIJKs:n}=t,i=n.length;if(typeof r!="number"||i>=JI&&r=n[i-1].value)n.push(o);else for(let a=0;a=JI&&n.splice(0,1)}function AG(t,e,r){const{spacing:n,calibration:i}=r,{volumeUnit:o}=La({calibration:i,hasPixelSpacing:!0},[]),a=n?n[0]*n[1]*n[2]:1;return e.volume={value:Array.isArray(e.count.value)?e.count.value.map(s=>s*a):e.count.value*a,unit:o,name:"volume",label:"Volume"},e.maxIJKs=t.maxIJKs.filter(s=>s.pointIJK!==void 0),e.array.push(e.volume),t.maxIJKs=[],e}const eb=class eb extends jc{static statsInit(e){super.statsInit(e),this.volumetricState=v5()}static statsCallback(e){super.statsCallback(e),LG(this.volumetricState,e)}static getStatistics(e){const r={...e,unit:(e==null?void 0:e.unit)||"none",calibration:e==null?void 0:e.calibration,hasPixelSpacing:e==null?void 0:e.hasPixelSpacing},n=super.getStatistics(r);return AG(this.volumetricState,n,r)}};eb.volumetricState=v5();let fd=eb;class ZI extends DU{constructor(e){super(e),this.volumetricState=v5()}statsInit(e){super.statsInit(e),this.volumetricState=v5()}statsCallback(e){super.statsCallback(e),LG(this.volumetricState,e)}getStatistics(e){const r={...e,unit:(e==null?void 0:e.unit)||"none",calibration:e==null?void 0:e.calibration,hasPixelSpacing:e==null?void 0:e.hasPixelSpacing},n=super.getStatistics(r);return AG(this.volumetricState,n,r)}}const Oxe=Math.pow(3*1e3/(4*Math.PI),1/3);async function NG({segmentationId:t,segmentIndices:e,mode:r="collective"}){Hw(),Kc(Ja.COMPUTE_STATISTICS,0);const n=_G(t,e);if(!n)return;const{operationData:i,segVolumeId:o,segImageIds:a,reconstructableVolume:s,indices:c}=n,{refImageId:l,modalityUnitOptions:f}=exe(o,a),u=gB(l,f);return s?await Mxe({operationData:i,indices:c,unit:u,mode:r}):await Pxe({segImageIds:a,indices:c,unit:u,mode:r})}async function Mxe({operationData:t,indices:e,unit:r,mode:n}){var p;const i=EG(t),{segmentationVoxelManager:o,imageVoxelManager:a,segmentationImageData:s,imageData:c}=i;if(!o||!s)return;const l=s.getSpacing(),{boundsIJK:f}=o;if(!f)return fd.getStatistics({spacing:l});const d={scalarData:o.getCompleteScalarDataArray(),dimensions:s.getDimensions(),spacing:s.getSpacing(),origin:s.getOrigin(),direction:s.getDirection()},h={scalarData:a.getCompleteScalarDataArray(),dimensions:c.getDimensions(),spacing:c.getSpacing(),origin:c.getOrigin(),direction:c.getDirection()};if(!((p=h.scalarData)!=null&&p.length))return;const g=await Yc().executeTask("compute","calculateSegmentsStatisticsVolume",{segmentationInfo:d,imageInfo:h,indices:e,unit:r,mode:n});if(Kc(Ja.COMPUTE_STATISTICS,100),n==="collective")return y5({stats:g,unit:r,spacing:l,segmentationImageData:s,imageVoxelManager:a});{const v={};return Object.entries(g).forEach(([y,m])=>{v[y]=y5({stats:m,unit:r,spacing:l,segmentationImageData:s,imageVoxelManager:a})}),v}}const O3=(t,e)=>{if(!t.array)return;const r=t.array.findIndex(n=>n.name===e.name);r!==-1?t.array[r]=e:t.array.push(e)},y5=({stats:t,unit:e,spacing:r,segmentationImageData:n,imageVoxelManager:i})=>{if(t.mean.unit=e,t.max.unit=e,t.min.unit=e,e!=="SUV")return t;const o=r.map(a=>Math.max(1,Math.round(1.1*Oxe/a)));for(const a of t.maxIJKs){const s=Rxe(a,o,n,i,r);if(!s)continue;const{mean:c}=s;(!t.peakValue||t.peakValue.value<=c.value)&&(t.peakValue={name:"peakValue",label:"Peak Value",value:c.value,unit:e},t.peakPoint={name:"peakLPS",label:"Peak SUV Point",value:a.pointLPS?[...a.pointLPS]:null,unit:null},O3(t,t.peakValue),O3(t,t.peakPoint))}if(t.volume&&t.mean){const a=t.volume.value,s=t.mean.value;t.lesionGlycolysis={name:"lesionGlycolysis",label:"Lesion Glycolysis",value:a*s,unit:`${t.volume.unit}·${e}`},O3(t,t.lesionGlycolysis)}return t};async function Pxe({segImageIds:t,indices:e,unit:r,mode:n}){Kc(Ja.COMPUTE_STATISTICS,0);const{segmentationInfo:i,imageInfo:o}=bG(t),a=await Yc().executeTask("compute","calculateSegmentsStatisticsStack",{segmentationInfo:i,imageInfo:o,indices:e,mode:n});Kc(Ja.COMPUTE_STATISTICS,100);const s=i[0].spacing,c=i[0],l=o[0].voxelManager;if(n==="collective")return y5({stats:a,unit:r,spacing:s,segmentationImageData:c,imageVoxelManager:l});{const f={};return Object.entries(a).forEach(([u,d])=>{f[u]=y5({stats:d,unit:r,spacing:s,segmentationImageData:c,imageVoxelManager:l})}),f}}function Rxe(t,e,r,n,i){const{pointIJK:o,pointLPS:a}=t;if(!o)return;const s=o.map((f,u)=>[f-e[u],f+e[u]]),c=(f,u)=>{const d=(u[0]-o[0])/e[0],h=(u[1]-o[1])/e[1],g=(u[2]-o[2])/e[2];return d*d+h*h+g*g<=1},l=({pointIJK:f,pointLPS:u})=>{const d=n.getAtIJKPoint(f);d!==void 0&&fd.statsCallback({value:d,pointLPS:u,pointIJK:f})};return fd.statsInit({storePointData:!1}),G4(r,{pointInShapeFn:c,callback:l,boundsIJK:s}),fd.getStatistics({spacing:i})}const Lxe={[It.GetStatistics]:function(t,e,r){const{indices:n}=r,{segmentationId:i,viewport:o}=e;NG({segmentationId:i,segmentIndices:n})}},Sn={determineSegmentIndex:pxe,dynamicThreshold:mxe,erase:vxe,islandRemoval:Txe,preview:_xe,regionFill:Exe,setValue:Dxe,threshold:Ixe,labelmapStatistics:Lxe,ensureSegmentationVolumeFor3DManipulation:SG,ensureImageVolumeFor3DManipulation:TG},Yf=class Yf{constructor(e,...r){this._initialize=[],this._fill=[],this._onInteractionStart=[],this.fill=(n,i)=>{const o=this.initialize(n,i,It.Fill);if(!o)return;this._fill.forEach(c=>c(o));const{segmentationVoxelManager:a,segmentIndex:s}=o;return bo(o.segmentationId,a.getArrayOfModifiedSlices(),s),o},this.onInteractionStart=(n,i)=>{const o=this.initialize(n,i);o&&this._onInteractionStart.forEach(a=>a.call(this,o))},this.addPreview=(n,i)=>{const o=this.initialize(n,i,It.AddPreview);if(o)return o},this.configurationName=e,this.compositions=r,r.forEach(n=>{const i=typeof n=="function"?n():n;if(i)for(const o in i){if(!Yf.childFunctions[o])throw new Error(`Didn't find ${o} as a brush strategy`);Yf.childFunctions[o](this,i[o])}}),this.strategyFunction=(n,i)=>this.fill(n,i);for(const n of Object.keys(Yf.childFunctions))this.strategyFunction[n]=this[n]}initialize(e,r,n){const{viewport:i}=e,o=w8({operationData:r,viewport:i,strategy:this});if(!o)return null;const{imageVoxelManager:a,segmentationVoxelManager:s,segmentationImageData:c}=o,l=r.createMemo(r.segmentationId,s),f={operationName:n,...r,segmentIndex:r.segmentIndex,enabledElement:e,imageVoxelManager:a,segmentationVoxelManager:s,segmentationImageData:c,viewport:i,centerWorld:null,isInObject:null,isInObjectBoundsIJK:null,brushStrategy:this,memo:l};return this._initialize.forEach(u=>u(f)),f}};Yf.COMPOSITIONS=Sn,Yf.childFunctions={[It.OnInteractionStart]:ks(It.OnInteractionStart,It.Initialize),[It.OnInteractionEnd]:ks(It.OnInteractionEnd,It.Initialize),[It.Fill]:ks(It.Fill),[It.Initialize]:ks(It.Initialize),[It.CreateIsInThreshold]:G2(It.CreateIsInThreshold),[It.Interpolate]:ks(It.Interpolate,It.Initialize),[It.AcceptPreview]:ks(It.AcceptPreview,It.Initialize),[It.RejectPreview]:ks(It.RejectPreview,It.Initialize),[It.INTERNAL_setValue]:G2(It.INTERNAL_setValue),[It.Preview]:G2(It.Preview,!1),[It.ComputeInnerCircleRadius]:ks(It.ComputeInnerCircleRadius),[It.EnsureSegmentationVolumeFor3DManipulation]:ks(It.EnsureSegmentationVolumeFor3DManipulation),[It.EnsureImageVolumeFor3DManipulation]:ks(It.EnsureImageVolumeFor3DManipulation),[It.AddPreview]:ks(It.AddPreview),[It.GetStatistics]:G2(It.GetStatistics),compositions:null};let sc=Yf;function ks(t,e){const r=`_${t}`;return(n,i)=>{n[r]||(n[r]=[]),n[r].push(i),n[t]||(n[t]=e?(o,a,...s)=>{const c=n[e](o,a,t);let l;return n[r].forEach(f=>{const u=f.call(n,c,...s);l||(l=u)}),l}:(o,...a)=>{n[r].forEach(s=>s.call(n,o,...a))})}}function G2(t,e=!0){return(r,n)=>{if(r[t])throw new Error(`The singleton method ${t} already exists`);r[t]=e?n:(i,o,...a)=>(o.enabledElement=i,n.call(r,o,...a))}}function kG(t,e){const{center:r,radius:n}=t,i=t.radius2||n*n;return(e[0]-r[0])*(e[0]-r[0])+(e[1]-r[1])*(e[1]-r[1])+(e[2]-r[2])*(e[2]-r[2])<=i}const{transformWorldToIndex:QI,isEqual:M3}=Vn,VG={[It.Initialize]:t=>{const{points:e,viewport:r,segmentationImageData:n}=t;if(!e)return;const i=At(0,0,0);e.forEach(d=>{di(i,i,d)}),Nr(i,i,1/e.length),t.centerWorld=i,t.centerIJK=QI(n,i);const o=e.map(d=>r.worldToCanvas(d)),[a,s]=i5(o),c=r.canvasToWorld(a),l=r.canvasToWorld(s),f=e.map(d=>QI(n,d)),u=ef(f,n.getDimensions());t.isInObject=FG({topLeftWorld:c,bottomRightWorld:l,center:i}),t.isInObjectBoundsIJK=u}};function FG(t){const{topLeftWorld:e,bottomRightWorld:r,center:n}=t,i=Math.abs(e[0]-r[0])/2,o=Math.abs(e[1]-r[1])/2,a=Math.abs(e[2]-r[2])/2,s=Math.max(i,o,a);if(M3(i,s)&&M3(o,s)&&M3(a,s)){const f={center:n,radius:s,radius2:s*s};return u=>kG(f,u)}const c={center:n,xRadius:i,yRadius:o,zRadius:a},{precalculated:l}=zE(c,{});return l}const UG=new sc("Circle",Sn.regionFill,Sn.setValue,VG,Sn.determineSegmentIndex,Sn.preview,Sn.labelmapStatistics),Axe=new sc("CircleThreshold",Sn.regionFill,Sn.setValue,VG,Sn.determineSegmentIndex,Sn.dynamicThreshold,Sn.threshold,Sn.preview,Sn.islandRemoval,Sn.labelmapStatistics),Xw=UG.strategyFunction,Nxe=Axe.strategyFunction;function kxe(){throw new Error("Not yet implemented")}const{transformWorldToIndex:Vxe}=Vn,Fxe={[It.Initialize]:t=>{const{points:e,viewport:r,segmentationImageData:n}=t;if(!e)return;const i=At(0,0,0);e.forEach(c=>{di(i,i,c)}),Nr(i,i,1/e.length),t.centerWorld=i,t.centerIJK=Vxe(n,i);const{boundsIJK:o,topLeftWorld:a,bottomRightWorld:s}=Iwe(e.slice(0,2),n,r);t.isInObjectBoundsIJK=o,t.isInObject=FG({topLeftWorld:a,bottomRightWorld:s,center:i})}},Yw=new sc("Sphere",Sn.regionFill,Sn.setValue,Fxe,Sn.determineSegmentIndex,Sn.preview,Sn.labelmapStatistics,Sn.ensureSegmentationVolumeFor3DManipulation),BG=Yw.strategyFunction,Uxe=new sc("SphereThreshold",...Yw.compositions,Sn.dynamicThreshold,Sn.threshold,Sn.ensureSegmentationVolumeFor3DManipulation,Sn.ensureImageVolumeFor3DManipulation),Bxe=new sc("SphereThreshold",...Yw.compositions,Sn.dynamicThreshold,Sn.threshold,Sn.islandRemoval,Sn.ensureSegmentationVolumeFor3DManipulation,Sn.ensureImageVolumeFor3DManipulation),Gxe=Uxe.strategyFunction,Wxe=Bxe.strategyFunction,zxe=new sc("EraseSphere",Sn.erase,...Yw.compositions),GG=zxe.strategyFunction,$xe=new sc("EraseCircle",Sn.erase,...UG.compositions),WG=$xe.strategyFunction,{VoxelManager:XS,RLEVoxelMap:jxe}=Vn;function YS(t,e){return $G(t,e)}function zG(t){const{segmentationVoxelManager:e,undoVoxelManager:r,redoVoxelManager:n}=this,i=t===!1?n:r;i.forEach(({value:a,pointIJK:s})=>{e.setAtIJKPoint(s,a)});const o=i.getArrayOfModifiedSlices();bo(this.segmentationId,o)}function $G(t,e){const r=XS.createRLEHistoryVoxelManager(e);return{segmentationId:t,restoreMemo:zG,commitMemo:Hxe,segmentationVoxelManager:e,voxelManager:r,id:kn(),operationType:"labelmap"}}function Hxe(){if(this.redoVoxelManager)return!0;if(!this.voxelManager.modifiedSlices.size)return!1;const{segmentationVoxelManager:t}=this,e=XS.createRLEHistoryVoxelManager(t);jxe.copyMap(e.map,this.voxelManager.map);for(const n of this.voxelManager.modifiedSlices.keys())e.modifiedSlices.add(n);this.undoVoxelManager=e;const r=XS.createRLEVolumeVoxelManager({dimensions:this.segmentationVoxelManager.dimensions});return this.redoVoxelManager=r,e.forEach(({index:n,pointIJK:i,value:o})=>{const a=t.getAtIJKPoint(i);a!==o&&r.setAtIndex(n,a)}),!0}const Kxe=Object.freeze(Object.defineProperty({__proto__:null,createLabelmapMemo:YS,createRleMemo:$G,restoreMemo:zG},Symbol.toStringTag,{value:"Module"})),{isEqual:W2}=Vn,qxe=At(1,0,0),Xxe=At(0,1,0),Yxe=At(0,0,1),e7=[qxe,Xxe,Yxe];function jG(t){const e=Qn(Ge(),t[0],t[1]),r=Qn(Ge(),t[0],t[2]),n=t7(e,e7),i=t7(r,e7);return[...n,...i].every(a=>W2(a,0)||W2(a,90)||W2(a,180)||W2(a,270))}function t7(t,e){return e.map(r=>r4(t,r)*180/Math.PI)}const{transformWorldToIndex:HG}=Vn,KG={[It.Initialize]:t=>{const{points:e,imageVoxelManager:r,viewport:n,segmentationImageData:i,segmentationVoxelManager:o}=t;if(!e)return;const a=At(0,0,0);e.forEach(l=>{di(a,a,l)}),Nr(a,a,1/e.length),t.centerWorld=a,t.centerIJK=HG(i,a);const{boundsIJK:s,pointInShapeFn:c}=Jxe(n,e,i);t.isInObject=c,t.isInObjectBoundsIJK=s}};function Jxe(t,e,r){let n=e.map(w=>HG(r,w));n=n.map(w=>w.map(x=>Math.round(x)));const i=ef(n,r.getDimensions()),a=t instanceof mr||jG(n),s=r.getDirection(),c=r.getSpacing(),{viewPlaneNormal:l}=t.getCamera(),f=hf({direction:s,spacing:c},l),u=eU(e);let[[d,h],[g,p],[v,y]]=u;return d-=f,h+=f,g-=f,p+=f,v-=f,y+=f,{boundsIJK:i,pointInShapeFn:a?()=>!0:w=>{const[x,C,S]=w,T=x>=d&&x<=h,_=C>=g&&C<=p,E=S>=v&&S<=y;return T&&_&&E}}}const Zxe=new sc("Rectangle",Sn.regionFill,Sn.setValue,KG,Sn.determineSegmentIndex,Sn.preview,Sn.labelmapStatistics),Qxe=new sc("RectangleThreshold",Sn.regionFill,Sn.setValue,KG,Sn.determineSegmentIndex,Sn.dynamicThreshold,Sn.threshold,Sn.preview,Sn.islandRemoval,Sn.labelmapStatistics),T8=Zxe.strategyFunction,e3e=Qxe.strategyFunction,t3e=Object.freeze(Object.defineProperty({__proto__:null,fillInsideCircle:Xw,fillInsideRectangle:T8,fillOutsideCircle:kxe,thresholdInsideRectangle:e3e},Symbol.toStringTag,{value:"Module"})),Lp=class Lp extends Ci{constructor(e,r){super(e,r),this.memoMap=new Map,this.acceptedMemoIds=new Map,this.centerSegmentIndexInfo={segmentIndex:null,hasSegmentIndex:!1,hasPreviewIndex:!1,changedIndices:[]}}_historyRedoHandler(e){const{id:r,operationType:n}=e.detail;if(n==="labelmap"){if(this.acceptedMemoIds.has(r)){this._hoverData=null;const i=this.acceptedMemoIds.get(r),o=i==null?void 0:i.element,a=this.getOperationData(o);a.segmentIndex=i==null?void 0:i.segmentIndex,o&&this.applyActiveStrategyCallback(Se(o),a,It.AcceptPreview)}this._previewData.isDrag=!0}}get _previewData(){return Lp.previewData}createMemo(e,r){const n=r.id;if(this.memo&&this.memo.segmentationVoxelManager===r)return this.memo;let i=this.memoMap.get(n);return i?i.redoVoxelManager&&(i=YS(e,r),this.memoMap.set(n,i)):(i=YS(e,r),this.memoMap.set(n,i)),this.memo=i,i}createEditData(e){const r=Se(e),{viewport:n}=r,i=Dd(n.id);if(!i){const l=new CustomEvent(Ze.ERROR_EVENT,{detail:{type:"Segmentation",message:"No active segmentation detected, create a segmentation representation before using the brush tool"},cancelable:!0});return Je.dispatchEvent(l),null}const{segmentationId:o}=i,a=Gd(o),{representationData:s}=zn(o);return this.getEditData({viewport:n,representationData:s,segmentsLocked:a,segmentationId:o})}getEditData({viewport:e,representationData:r,segmentsLocked:n,segmentationId:i}){var o,a,s;if(e instanceof Or){const{volumeId:c}=r[Lt.Labelmap],l=e.getActors();if(e instanceof mr){const g=new CustomEvent(Ze.ERROR_EVENT,{detail:{type:"Segmentation",message:"Cannot perform brush operation on the selected viewport"},cancelable:!0});return Je.dispatchEvent(g),null}const u=l.map(g=>Fe.getVolume(g.referencedId)),d=Fe.getVolume(c),h=((o=u.find(g=>Yt(g.dimensions,d.dimensions)))==null?void 0:o.volumeId)||((a=u[0])==null?void 0:a.volumeId);return{volumeId:c,referencedVolumeId:((s=this.configuration.threshold)==null?void 0:s.volumeId)??h,segmentsLocked:n}}else{const c=mf(e.id,i);return c?{imageId:c,segmentsLocked:n}:void 0}}createHoverData(e,r){const n=Se(e),{viewport:i}=n,o=i.getCamera(),{viewPlaneNormal:a,viewUp:s}=o,c=[i.id],{segmentIndex:l,segmentationId:f,segmentColor:u}=this.getActiveSegmentationData(i)||{};return{brushCursor:{metadata:{viewPlaneNormal:[...a],viewUp:[...s],FrameOfReferenceUID:i.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:u},data:{}},centerCanvas:r,segmentIndex:l,viewport:i,segmentationId:f,segmentColor:u,viewportIdsToRender:c}}getActiveSegmentationData(e){const r=e.id,n=Dd(r);if(!n)return;const{segmentationId:i}=n,o=Ra(i);if(!o)return;const a=zl(r,i,o);return{segmentIndex:o,segmentationId:i,segmentColor:a}}getOperationData(e){var v,y,m,w;const r=this._editData||this.createEditData(e),{segmentIndex:n,segmentationId:i,brushCursor:o}=this._hoverData||this.createHoverData(e),{data:a,metadata:s={}}=o||{},{viewPlaneNormal:c,viewUp:l}=s,f=(y=(v=this.configuration.preview)==null?void 0:v.previewColors)==null?void 0:y[n],{viewport:u}=Se(e),d=zl(u.id,i,n);if(!f&&!d)return;let h=null,g=null;return(m=this.configuration.preview)!=null&&m.enabled&&(h=f||n3e(...d),g=255),{...r,points:(w=a==null?void 0:a.handles)==null?void 0:w.points,segmentIndex:n,viewPlaneNormal:c,previewOnHover:!this._previewData.isDrag,toolGroupId:this.toolGroupId,segmentationId:i,viewUp:l,centerSegmentIndexInfo:this.centerSegmentIndexInfo,activeStrategy:this.configuration.activeStrategy,configuration:this.configuration,previewColor:h,previewSegmentIndex:g,createMemo:this.createMemo.bind(this)}}addPreview(e=this._previewData.element,r){const{_previewData:n}=this,i=r==null?void 0:r.acceptReject;i===!0?this.acceptPreview(e):i===!1&&this.rejectPreview(e);const o=Se(e),a=this.applyActiveStrategyCallback(o,this.getOperationData(e),It.AddPreview);return n.isDrag=!0,a}rejectPreview(e=this._previewData.element){if(!e)return;this.doneEditMemo();const r=Se(e);this.applyActiveStrategyCallback(r,this.getOperationData(e),It.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1}acceptPreview(e=this._previewData.element){if(!e)return;const r=this.getOperationData(e);this.memo&&this.memo.id&&this.acceptedMemoIds.set(this.memo.id,{element:e,segmentIndex:r.segmentIndex});const n=Se(e);this.applyActiveStrategyCallback(n,r,It.AcceptPreview),this.doneEditMemo(),this._previewData.preview=null,this._previewData.isDrag=!1}static viewportContoursToLabelmap(e,r){var v;const n=(r==null?void 0:r.removeContours)??!0,i=gm(),o=Em(e,i);if(!(o!=null&&o.length))return;const a=o.filter(y=>{var m,w;return(w=(m=y.data.contour)==null?void 0:m.polyline)==null?void 0:w.length});if(!a.length)return;const c=new Lp({},{configuration:{strategies:{FILL_INSIDE_CIRCLE:Xw},activeStrategy:"FILL_INSIDE_CIRCLE"}}).addPreview(e.element),{memo:l,segmentationId:f}=c,u=l==null?void 0:l.voxelManager,d=u.sourceVoxelManager||u,{dimensions:h}=u,g=e.getDefaultActor().actor.getMapper().getInputData();for(const y of a){const m=[[1/0,-1/0],[1/0,-1/0],[1/0,-1/0]],{polyline:w}=y.data.contour;for(const I of w)g.worldToIndex(I).forEach((O,A)=>{m[A][0]=Math.min(m[A][0],O),m[A][1]=Math.max(m[A][1],O)});m.forEach((I,P)=>{I[0]=Math.round(Math.max(0,I[0])),I[1]=Math.round(Math.min(h[P]-1,I[1]))});const x=Ra(f),C=((v=y.data.handles)==null?void 0:v[0])||w[0],S=g.worldToIndex(C).map(Math.round),T=d.getAtIJKPoint(S)||0;let _=!1,E=!1;for(const I of w){const P=g.worldToIndex(I).map(Math.round),O=d.getAtIJKPoint(P);O===T?_=!0:O>=0&&(E=!0)}const D=_&&E?T:T===0?x:0;for(let I=m[0][0];I<=m[0][1];I++)for(let P=m[1][0];P<=m[1][1];P++)for(let O=m[2][0];O<=m[2][1];O++){const A=g.indexToWorld([I,P,O]);XE(A,w)&&u.setAtIJK(I,P,O,D)}n&&yn(y.annotationUID)}const p=u.getArrayOfModifiedSlices();bo(f,p)}};Lp.previewData={preview:null,element:null,timerStart:0,timer:null,startPoint:[NaN,NaN],isDrag:!1};let Md=Lp;function n3e(t,e,r,n,i=.4){return[Math.round(t+(255-t)*i),Math.round(e+(255-e)*i),Math.round(r+(255-r)*i),n]}class Jw extends Md{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE_CIRCLE:Xw,ERASE_INSIDE_CIRCLE:WG,FILL_INSIDE_SPHERE:BG,ERASE_INSIDE_SPHERE:GG,THRESHOLD_INSIDE_CIRCLE:Nxe,THRESHOLD_INSIDE_SPHERE:Gxe,THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL:Wxe},defaultStrategy:"FILL_INSIDE_CIRCLE",activeStrategy:"FILL_INSIDE_CIRCLE",brushSize:25,useCenterSegmentIndex:!1,preview:{enabled:!1,previewColors:{0:[255,255,255,128]},previewTimeMs:250,previewMoveDistance:8,dragMoveDistance:4,dragTimeMs:500},actions:{[It.AcceptPreview]:{method:It.AcceptPreview,bindings:[{key:"Enter"}]},[It.RejectPreview]:{method:It.RejectPreview,bindings:[{key:"Escape"}]},[It.Interpolate]:{method:It.Interpolate,bindings:[{key:"i"}],configuration:{useBallStructuringElement:!0,noUseDistanceTransform:!0,noUseExtrapolation:!0}},interpolateExtrapolation:{method:It.Interpolate,bindings:[{key:"e"}],configuration:{}}}}}){super(e,r),this.onSetToolPassive=n=>{this.disableCursor()},this.onSetToolEnabled=()=>{this.disableCursor()},this.onSetToolDisabled=n=>{this.disableCursor()},this.preMouseDownCallback=n=>{const i=n.detail,{element:o}=i,a=Se(o);this._editData=this.createEditData(o),this._activateDraw(o),Ft(o),n.preventDefault(),this._previewData.isDrag=!1,this._previewData.timerStart=Date.now();const s=this._hoverData||this.createHoverData(o);Ne(s.viewportIdsToRender);const c=this.getOperationData(o);return this.applyActiveStrategyCallback(a,c,It.OnInteractionStart),!0},this.mouseMoveCallback=n=>{if(this.mode===$n.Active){if(this.updateCursor(n),!this.configuration.preview.enabled)return;const{previewTimeMs:i,previewMoveDistance:o,dragMoveDistance:a}=this.configuration.preview,{currentPoints:s,element:c}=n.detail,{canvas:l}=s,{startPoint:f,timer:u,timerStart:d,isDrag:h}=this._previewData;if(h)return;const g=Ir(l,f),p=Date.now()-d;if((g>o||p>i&&g>a)&&(u&&(window.clearTimeout(u),this._previewData.timer=null),h||this.rejectPreview(c)),!this._previewData.timer){const v=window.setTimeout(this.previewCallback,250);Object.assign(this._previewData,{timerStart:Date.now(),timer:v,startPoint:l,element:c})}}},this.previewCallback=()=>{if(this._previewData.isDrag){this._previewData.timer=null;return}this._previewData.timer=null;const n=this.getOperationData(this._previewData.element),i=Se(this._previewData.element);if(!i)return;const{viewport:o}=i,a=this.configuration.activeStrategy,s=w8({operationData:n,viewport:o,strategy:a});if(!n)return;const c=this.createMemo(n.segmentationId,s.segmentationVoxelManager);this._previewData.preview=this.applyActiveStrategyCallback(Se(this._previewData.element),{...n,...s,memo:c},It.Preview)},this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Se(o);this.updateCursor(n);const{viewportIdsToRender:c}=this._hoverData;Ne(c);const l=Ir(a.canvas,this._previewData.startPoint),{dragTimeMs:f,dragMoveDistance:u}=this.configuration.preview;!this._previewData.isDrag&&Date.now()-this._previewData.timerStart{const i=n.detail,{element:o}=i,a=Se(o),s=this.getOperationData(o);!this._previewData.preview&&!this._previewData.isDrag&&this.applyActiveStrategy(a,s),this.doneEditMemo(),this._deactivateDraw(o),Xt(o),this.updateCursor(n),this._editData=null,this.applyActiveStrategyCallback(a,s,It.OnInteractionEnd),this._previewData.isDrag||this.acceptPreview(o)},this._activateDraw=n=>{n.addEventListener(k.MOUSE_UP,this._endCallback),n.addEventListener(k.MOUSE_DRAG,this._dragCallback),n.addEventListener(k.MOUSE_CLICK,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(k.MOUSE_UP,this._endCallback),n.removeEventListener(k.MOUSE_DRAG,this._dragCallback),n.removeEventListener(k.MOUSE_CLICK,this._endCallback)}}disableCursor(){this._hoverData=void 0,this.rejectPreview()}updateCursor(e){const r=e.detail,{element:n}=r,{currentPoints:i}=r,o=i.canvas;this._hoverData=this.createHoverData(n,o),this._calculateCursor(n,o),this._hoverData&&Ne(this._hoverData.viewportIdsToRender)}_calculateCursor(e,r){const n=Se(e),{viewport:i}=n,{canvasToWorld:o}=i,a=i.getCamera(),{brushSize:s}=this.configuration,c=At(a.viewUp[0],a.viewUp[1],a.viewUp[2]),l=At(a.viewPlaneNormal[0],a.viewPlaneNormal[1],a.viewPlaneNormal[2]),f=Ge();Wn(f,c,l);const u=o([r[0],r[1]]),d=Ge(),h=Ge(),g=Ge(),p=Ge();for(let x=0;x<=2;x++)d[x]=u[x]-c[x]*s,h[x]=u[x]+c[x]*s,g[x]=u[x]-f[x]*s,p[x]=u[x]+f[x]*s;if(!this._hoverData)return;const{brushCursor:v}=this._hoverData,{data:y}=v;y.handles===void 0&&(y.handles={}),y.handles.points=[d,h,g,p];const m=this.configuration.activeStrategy,w=this.configuration.strategies[m];typeof(w==null?void 0:w.computeInnerCircleRadius)=="function"&&w.computeInnerCircleRadius({configuration:this.configuration,viewport:i}),y.invalidated=!1}getStatistics(e,r){if(!e)return;const n=Se(e);return this.applyActiveStrategyCallback(n,this.getOperationData(e),It.GetStatistics,r)}rejectPreview(e=this._previewData.element){if(!e)return;this.doneEditMemo();const r=Se(e);r&&(this.applyActiveStrategyCallback(r,this.getOperationData(e),It.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1)}acceptPreview(e=this._previewData.element){e&&super.acceptPreview(e)}interpolate(e,r){if(!e)return;const n=Se(e);this._previewData.preview=this.applyActiveStrategyCallback(n,this.getOperationData(e),It.Interpolate,r.configuration),this._previewData.isDrag=!0}invalidateBrushCursor(){if(this._hoverData===void 0)return;const{data:e}=this._hoverData.brushCursor,{viewport:r}=this._hoverData;e.invalidated=!0;const{segmentColor:n}=this.getActiveSegmentationData(r)||{};this._hoverData.brushCursor.metadata.segmentColor=n}renderAnnotation(e,r){var m,w;if(!this._hoverData)return;const{viewport:n}=e;if(!this._hoverData.viewportIdsToRender.includes(n.id))return;const o=this._hoverData.brushCursor;if(o.data.invalidated===!0){const{centerCanvas:x}=this._hoverData,{element:C}=n;this._calculateCursor(C,x)}const a=o.metadata;if(!a)return;const s=a.brushCursorUID,c=o.data,{points:l}=c.handles,f=l.map(x=>n.worldToCanvas(x)),u=f[0],d=f[1],h=[Math.floor((u[0]+d[0])/2),Math.floor((u[1]+d[1])/2)],g=Math.abs(u[1]-Math.floor((u[1]+d[1])/2)),p=`rgb(${((m=a.segmentColor)==null?void 0:m.slice(0,3))||[0,0,0]})`;if(!n.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}ua(r,s,"0",h,g,{color:p,lineDash:this.centerSegmentIndexInfo.segmentIndex===0?[1,2]:null});const{dynamicRadiusInCanvas:y}=((w=this.configuration)==null?void 0:w.threshold)||{dynamicRadiusInCanvas:0};y&&ua(r,s,"1",h,y,{color:p})}}Jw.toolName="Brush";function rg(t,e){const r=fi(t);if(r===void 0)return;const n=r._toolInstances;return Object.keys(n).length?e&&n[e]?[n[e]]:Object.values(n).filter(o=>o instanceof Jw):void 0}function r3e(t,e,r){const n=fi(t);if(n===void 0)return;rg(t,r).forEach(l=>{l.configuration.brushSize=e,l.invalidateBrushCursor()});const o=n.getViewportsInfo(),a=Object.keys(o).map(l=>o[l]);if(!a.length)return;const{renderingEngineId:s}=a[0],c=n.getViewportIds();ni(s),Ne(c)}function i3e(t,e){const r=fi(t);if(r===void 0)return;const n=r._toolInstances;if(!Object.keys(n).length)return;const o=rg(t,e)[0];if(o)return o.configuration.brushSize}function o3e(t,e){const r=fi(t);if(r===void 0||(rg(t).forEach(a=>{a.configuration.activeStrategy.toLowerCase().includes("threshold")&&(a.configuration={...a.configuration,threshold:{...a.configuration.threshold,...e}})}),!r.getViewportsInfo().length))return;const o=r.getViewportIds();Ne(o)}function a3e(t){const e=fi(t);if(e===void 0)return;const r=e._toolInstances;if(!Object.keys(r).length)return;const i=rg(t)[0];if(i)return i.configuration.threshold.range}const Ap=class Ap{static statsInit(e){const{storePointData:r,indices:n,mode:i}=e;this.mode=i,this.indices=n,this.calculators.clear(),this.mode==="individual"?n.forEach(o=>{this.calculators.set(o,new ZI({storePointData:r}))}):this.calculators.set(n,new ZI({storePointData:r}))}static statsCallback(e){const{segmentIndex:r,...n}=e;if(!r)throw new Error("Segment index is required for stats calculation");const i=this.mode==="individual"?this.calculators.get(r):this.calculators.get(this.indices);if(!i)throw new Error(`No calculator found for segment ${r}`);i.statsCallback(n)}static getStatistics(e){if(this.mode==="individual"){const n={};return this.calculators.forEach((i,o)=>{n[o]=i.getStatistics(e)}),n}return this.calculators.get(this.indices).getStatistics(e)}};Ap.calculators=new Map,Ap.indices=[],Ap.mode="collective";let JS=Ap;function s3e(t,e,r,n,i){if(!i)throw new Error("Segmentation ID is required to be passed inside thresholdSegmentationByRange");const{baseVolumeIdx:o,volumeInfoList:a}=tU(t,r),{voxelManager:s}=a[o],c=s,l=t.voxelManager.getScalarDataLength(),f=t.voxelManager;return a.forEach(u=>{const{volumeSize:d}=u;d===l?l3e(f,c,e,u):c3e(f,c,e,u,a,o,n)}),bo(i),t}function c3e(t,e,r,n,i,o,a){const{imageData:s,lower:c,upper:l,dimensions:f}=n;let u,d,h;const g=t.getScalarDataLength();for(let p=0;p{u=u+1,w>=h.lower&&w<=h.upper&&(d=d+1)};u=0,d=0,h={lower:c,upper:l};let m=!1;t.forEach(y,{imageData:s,boundsIJK:v}),m=a===0?d>0:d===u,t.setAtIndex(p,m?r:0)}return{total:u,range:h,overlaps:d}}function l3e(t,e,r,n){const{lower:i,upper:o}=n,a=t.getScalarDataLength();for(let s=0;s=i&&c<=o?r:0)}}function n7(t,e,r){const n=r.toIJK(t),i=r.toIJK(e),o=Ge(),{testIJK:a}=r,s=Nn(Ge(),n,i),c=Math.round(Math.max(...s.map(Math.abs)));if(c<2)return!0;const l=Nr(Ge(),s,1/c);for(let f=1;f{const l=di(Ge(),s,c).map(v=>v/2),f=e.worldToIndex(l).map(Math.round),[u,d,h]=f,g=u+d*o+h*a,p=r.getAtIndex(g);return p===n||(i==null?void 0:i.has(p))},toIJK:s=>e.worldToIndex(s),testIJK:s=>{const[c,l,f]=s,u=Math.round(c)+Math.round(l)*o+Math.round(f)*a,d=r.getAtIndex(u);return d===n||(i==null?void 0:i.has(d))}}}function f3e(t,e,r){const n=Fe.getVolume(t);if(!n){console.warn(`No volume found for ${t}`);return}return u3e({dimensions:n.dimensions,imageData:n.imageData,voxelManager:n.voxelManager,segmentIndex:e,containedSegmentIndices:r})}const Rg=.01;function d3e(t,e,r){const{sliceContours:n}=t,{segmentIndex:i,containedSegmentIndices:o}=r;let a;const s=f3e(e,i,o);for(const c of n){const l=h3e(c,s,a);l&&(a=l)}return a&&Object.assign(a,r),a}function h3e(t,e,r={maxMajor:0,maxMinor:0}){const{points:n}=t.polyData,{maxMinor:i,maxMajor:o}=r;let a=o*o,s=i*i,c;for(let v=0;vRg||e.testCenter(m,w)&&n7(m,w,e)&&(s=x,d=[v,y])}if(!d)return;s=Math.sqrt(s);const h=n[d[0]],g=n[d[1]];return{majorAxis:[l,f],minorAxis:[h,g],maxMajor:a,maxMinor:s,...t}}async function qG(t){const e=await DG({segmentations:t});if(!(e!=null&&e.length)||!e[0].sliceContours.length)return;const{segments:r=[null,{label:"Unspecified",color:null,containedSegmentIndices:null}]}=t,n=ng(t.segmentationId);if(!n)return;const i=r.findIndex(o=>!!o);if(i!==-1)return r[i].segmentIndex=i,d3e(e[0],n.volumeId,r[i])}function XG(t,e){const{majorAxis:r,minorAxis:n,label:i="",sliceIndex:o}=t,[a,s]=r,[c,l]=n,f=[a,s,c,l];return{highlighted:!0,invalidated:!0,metadata:{toolName:"Bidirectional",...e.getViewReference({sliceIndex:o})},data:{handles:{points:f,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:i,cachedStats:{}},isLocked:!1,isVisible:!0}}const{transformWorldToIndex:z2}=Vn,P0=class P0 extends pr{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:g3e}}){super(e,r),this.isPointNearTool=(n,i,o,a)=>{const s=Se(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles;let u=c.worldToCanvas(f[0]),d=c.worldToCanvas(f[1]),h={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},g=Di([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]);return g<=a||(u=c.worldToCanvas(f[2]),d=c.worldToCanvas(f[3]),h={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},g=Di([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]),g<=a)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=Ot(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a);const c=Se(a),{renderingEngine:l}=c;Ne(s),Ft(a),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,c=i.data;i.highlighted=!0;let l=!1,f;o.worldPosition?l=!0:f=c.handles.points.findIndex(g=>g===o);const u=Ot(s,this.getToolName());Ft(s),this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s);const d=Se(s),{renderingEngine:h}=d;Ne(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;this.doneEditMemo(),f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),Xt(o);const{renderingEngine:u}=Se(o);if(this.editData.handleIndex!==void 0){const{points:d}=f.handles,h=no(d[0],d[1]);if(no(d[2],d[3])>h){const p=[[...d[2]],[...d[3]]],v=[...d[0]],y=[...d[1]],m=nn();vs(m,p[1][0]-p[0][0],p[1][1]-p[1][0]);const w=nn();vs(w,-m[1],m[0]);const x=nn();vs(x,y[0]-v[0],y[1]-v[0]);let C;i4(x,w)>0?C=[v,y]:C=[y,v],f.handles.points=[p[0],p[1],C[0],C[1]]}}this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&yn(a.annotationUID),Ne(s),c&&jn(a),this.editData=null,this.isDrawing=!1},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=Se(a),{viewport:c}=s,{worldToCanvas:l}=c,{annotation:f,viewportIdsToRender:u,handleIndex:d,newAnnotation:h}=this.editData;this.createMemo(a,f,{newAnnotation:h});const{data:g}=f,p=o.world;g.handles.points[d]=[...p];const v=g.handles.points.map(l),y={longLineSegment:{start:{x:v[0][0],y:v[0][1]},end:{x:v[1][0],y:v[1][1]}},shortLineSegment:{start:{x:v[2][0],y:v[2][1]},end:{x:v[3][0],y:v[3][1]}}},w=Ir(v[0],v[1])/3,x=y.longLineSegment.start.x-y.longLineSegment.end.x,C=y.longLineSegment.start.y-y.longLineSegment.end.y,S=Math.sqrt(x*x+C*C),T=x/S,_=C/S,E=(y.longLineSegment.start.x+y.longLineSegment.end.x)/2,b=(y.longLineSegment.start.y+y.longLineSegment.end.y)/2,D=E+w*_,I=b-w*T,P=E-w*_,O=b+w*T;g.handles.points[2]=c.canvasToWorld([D,I]),g.handles.points[3]=c.canvasToWorld([P,O]),f.invalidated=!0,Ne(u),cn(f,a,Zt.HandlesUpdated),this.editData.hasMoved=!0},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else this._dragModifyHandle(n),a.invalidated=!0;Ne(s),a.invalidated&&cn(a,o,Zt.HandlesUpdated)},this._dragModifyHandle=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=Se(a),{viewport:c}=s,{annotation:l,handleIndex:f}=this.editData,{data:u}=l,d=o.world,h=[c.worldToCanvas(u.handles.points[0]),c.worldToCanvas(u.handles.points[1]),c.worldToCanvas(u.handles.points[2]),c.worldToCanvas(u.handles.points[3])],g={start:{x:h[0][0],y:h[0][1]},end:{x:h[1][0],y:h[1][1]}},p={start:{x:h[2][0],y:h[2][1]},end:{x:h[3][0],y:h[3][1]}},v=[...d],y=c.worldToCanvas(v);if(f===0||f===1){const w=h[f===0?1:0],x=vs(nn(),y[0]-w[0],y[1]-w[1]),C=vs(nn(),h[f][0]-w[0],h[f][1]-w[1]);Tl(x,x),Tl(C,C);const S={start:{x:w[0],y:w[1]},end:{x:y[0],y:y[1]}};if(this._movingLongAxisWouldPutItThroughShortAxis(S,p))return;const T=w,_=this._getSignedAngle(C,x);let E=h[2][0],b=h[2][1],D=h[3][0],I=h[3][1];E-=T[0],b-=T[1],D-=T[0],I-=T[1];const P=E*Math.cos(_)-b*Math.sin(_),O=E*Math.sin(_)+b*Math.cos(_),A=D*Math.cos(_)-I*Math.sin(_),V=D*Math.sin(_)+I*Math.cos(_);E=P+T[0],b=O+T[1],D=A+T[0],I=V+T[1];const G=c.canvasToWorld([E,b]),R=c.canvasToWorld([D,I]);u.handles.points[f]=v,u.handles.points[2]=G,u.handles.points[3]=R}else{const m=f===2?3:2,w={longLineSegment:{start:g.start,end:g.end},shortLineSegment:{start:p.start,end:p.end}},x=ai(nn(),[w.longLineSegment.end.x,w.longLineSegment.end.y],[w.longLineSegment.start.x,w.longLineSegment.start.y]),C=Tl(nn(),x),S=ai(nn(),[y[0],y[1]],[h[f][0],h[f][1]]),T=wy(S),_=this._getSignedAngle(C,S),E=Math.cos(_)*T,b=UY(nn(),[h[m][0],h[m][1]],C,E);if(this._movingLongAxisWouldPutItThroughShortAxis({start:{x:y[0],y:y[1]},end:{x:b[0],y:b[1]}},{start:{x:w.longLineSegment.start.x,y:w.longLineSegment.start.y},end:{x:w.longLineSegment.end.x,y:w.longLineSegment.end.y}})||!a5([y[0],y[1]],[b[0],b[1]],[g.start.x,g.start.y],[g.end.x,g.end.y]))return;u.handles.points[m]=c.canvasToWorld(b),u.handles.points[f]=v}},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),Xt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Ne(o),a&&jn(i),this.editData=null,i.annotationUID}},this._activateDraw=n=>{He.isInteractingWithTool=!0,n.addEventListener(k.MOUSE_UP,this._endCallback),n.addEventListener(k.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(k.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(k.MOUSE_CLICK,this._endCallback),n.addEventListener(k.TOUCH_TAP,this._endCallback),n.addEventListener(k.TOUCH_END,this._endCallback),n.addEventListener(k.TOUCH_DRAG,this._dragDrawCallback)},this._deactivateDraw=n=>{He.isInteractingWithTool=!1,n.removeEventListener(k.MOUSE_UP,this._endCallback),n.removeEventListener(k.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(k.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(k.MOUSE_CLICK,this._endCallback),n.removeEventListener(k.TOUCH_TAP,this._endCallback),n.removeEventListener(k.TOUCH_END,this._endCallback),n.removeEventListener(k.TOUCH_DRAG,this._dragDrawCallback)},this._activateModify=n=>{He.isInteractingWithTool=!0,n.addEventListener(k.MOUSE_UP,this._endCallback),n.addEventListener(k.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(k.MOUSE_CLICK,this._endCallback),n.addEventListener(k.TOUCH_END,this._endCallback),n.addEventListener(k.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(k.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{He.isInteractingWithTool=!1,n.removeEventListener(k.MOUSE_UP,this._endCallback),n.removeEventListener(k.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(k.MOUSE_CLICK,this._endCallback),n.removeEventListener(k.TOUCH_END,this._endCallback),n.removeEventListener(k.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(k.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!0;const{viewport:a}=n,{element:s}=a;let c=pn(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(X));u.annotationUID=g;const{color:w,lineWidth:x,lineDash:C,shadow:S}=this.getAnnotationStyle({annotation:h,styleSpecifier:u});if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let T;if(!ii(g))continue;!mi(g)&&!this.editData&&y!==null&&(T=[m[y]]),T&&ur(i,g,"0",T,{color:w});const _=`${g}-line-1`,E=`${g}-line-2`;Tn(i,g,"0",m[0],m[1],{color:w,lineDash:C,lineWidth:x,shadow:S},_),Tn(i,g,"1",m[2],m[3],{color:w,lineDash:C,lineWidth:x,shadow:S},E),o=!0;const I=this.getLinkedTextBoxStyle(u,h);if(!I.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const P=this.configuration.getTextLines(p,l);if(!P||P.length===0)continue;let O;p.handles.textBox.hasMoved||(O=Aa(m),p.handles.textBox.worldPosition=a.canvasToWorld(O));const A=a.worldToCanvas(p.handles.textBox.worldPosition),G=uo(i,g,"1",P,A,m,{},I),{x:R,y:N,width:F,height:j}=G;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([R,N]),topRight:a.canvasToWorld([R+F,N]),bottomLeft:a.canvasToWorld([R,N+j]),bottomRight:a.canvasToWorld([R+F,N+j])}}return o},this._movingLongAxisWouldPutItThroughShortAxis=(n,i)=>{const o=nn();vs(o,i.end.x-i.start.x,i.end.y-i.start.y),Tl(o,o);const a={start:{x:i.start.x-o[0]*10,y:i.start.y-o[1]*10},end:{x:i.end.x+o[0]*10,y:i.end.y+o[1]*10}};return!a5([a.start.x,a.start.y],[a.end.x,a.end.y],[n.start.x,n.start.y],[n.end.x,n.end.y])},this._calculateCachedStats=(n,i,o)=>{const{data:a}=n,{element:s}=o.viewport,c=a.handles.points[0],l=a.handles.points[1],f=a.handles.points[2],u=a.handles.points[3],{cachedStats:d}=a,h=Object.keys(d);for(let p=0;pA?O:A,G=O>A?A:O,R=O>A?D:P,N=O>A?P:D;this._isInsideVolume(x,C,S,T,w)?this.isHandleOutsideImage=!1:this.isHandleOutsideImage=!0,d[v]={length:V,width:G,unit:R,widthUnit:N}}const g=n.invalidated;return n.invalidated=!1,g&&cn(n,s,Zt.StatsUpdated),d},this._isInsideVolume=(n,i,o,a,s)=>xr(n,s)&&xr(i,s)&&xr(o,s)&&xr(a,s),this._getSignedAngle=(n,i)=>Math.atan2(n[0]*i[1]-n[1]*i[0],n[0]*i[0]+n[1]*i[1]),this._throttledCalculateCachedStats=qo(this._calculateCachedStats,100,{trailing:!0})}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,o=n.world,a=Se(i),{viewport:s,renderingEngine:c}=a;this.isDrawing=!0;const l=s.getCamera(),{viewPlaneNormal:f,viewUp:u}=l,d=this.getReferencedImageId(s,o,f,u),h=s.getFrameOfReferenceUID(),g={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...f],viewUp:[...u],FrameOfReferenceUID:h,referencedImageId:d,...s.getViewReference({points:[o]})},data:{handles:{points:[[...o],[...o],[...o],[...o]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}}};ln(g,i);const p=Ot(i,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(i),Ft(i),e.preventDefault(),Ne(p),g}_calculateLength(e,r){const n=e[0]-r[0],i=e[1]-r[1],o=e[2]-r[2];return Math.sqrt(n*n+i*i+o*o)}};P0.toolName="Bidirectional",P0.hydrate=(e,r,n)=>{const i=qn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=P0.hydrateBase(P0,i,r[0],n),[f,u]=r,[d,h]=f,[g,p]=u,v=[d,h,g,p],{toolInstance:y,...m}=n||{},w={annotationUID:(n==null?void 0:n.annotationUID)||kn(),data:{handles:{points:v,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...m}};return ln(w,l.element),Ne([l.id]),w};let L1=P0;function g3e(t,e){const{cachedStats:r,label:n}=t,{length:i,width:o,unit:a}=r[e],s=[];return n&&s.push(n),i===void 0||s.push(`L: ${dn(i)} ${a||a}`,`W: ${dn(o)} ${a}`),s}async function p3e(t,e){console.warn("Deprecation Alert: There is a new getSegmentLargestBidirectional function that handles volume, stack and individual segment cases properly. This function is deprecated and will be removed in a future version.");const{data:r}=e,n=Se(t),i=(r.getSegment||m3e)(n,r);if(!i)return;const o=n.viewport.getFrameOfReferenceUID(),a=Kw(),{segmentIndex:s,segmentationId:c}=i,l=Zr.getAnnotations(this.toolName||L1.toolName,o);let f=!1;const u=l.filter(h=>{const g=h.data.segment;return g?(g.segmentationId===c&&g.segmentIndex===s&&(f=!0,h.data.segment=g),!0):!1});f||u.push({data:{segment:i}});let d;if(u.forEach(async h=>{const g=[],p=h.data.segment,{segmentIndex:v,segmentationId:y}=p;g[v]=p,Zr.removeAnnotation(h.annotationUID);const m=await qG({...a.find(C=>C.segmentationId===y),segments:g});if(!m)return;const w=XG(m,n.viewport);w.annotationUID=h.annotationUID,w.data.segment=p;const x=Zr.addAnnotation(w,o);if(p.segmentIndex===i.segmentIndex&&p.segmentationId===i.segmentationId){d=m;const{style:C}=i;C&&_E.setAnnotationStyles(x,C)}}),d){const{sliceIndex:h}=d,g=n.viewport.getImageIds();hs(t,{imageIndex:g.length-1-h}),n.viewport.render()}else console.warn("No bidirectional found");return d}function m3e(t,e){var a;const r=Kw();if(!r.length)return;const n=e.segmentationId||r[0].segmentationId,i=e.segmentIndex??Ra(n);if(!i)return;const o=(a=e.segmentData)==null?void 0:a.get(i);return{label:`Segment ${i}`,segmentIndex:i,segmentationId:n,...o}}function YG(t){const e=fi(t);if(e===void 0)return;rg(t).forEach(a=>{a.invalidateBrushCursor()});const n=e.getViewportsInfo();if(!Object.keys(n).map(a=>n[a]).length)return;const o=e.getViewportIds();Ne(o)}function _8(t,e,r={}){const n=zn(t),i=n.representationData,o=(r==null?void 0:r.representationType)??Object.keys(i)[0];if(!o)throw new Error(`Segmentation ${t} does not have any representations`);switch(o){case Lt.Labelmap:return v3e(n,e,r);case Lt.Contour:return y3e(n,e,r);default:return}}function v3e(t,e,{viewport:r}){const n=t.representationData.Labelmap;if(r instanceof Or){const{volumeId:h}=n,g=Fe.getVolume(h);return g?g.imageData.getScalarValueFromWorld(e):void 0}const i=Wl(r.id,t.segmentationId);if(i.length>1){console.warn("Segment selection for labelmaps with multiple imageIds in stack viewports is not supported yet.");return}const o=i[0];if(!Fe.getImage(o))return;const s=Pw(r.id,t.segmentationId),c=s==null?void 0:s.actor.getMapper().getInputData(),l=ei(c,e),f=c.getDimensions();return(c.voxelManager||oc.createScalarVolumeVoxelManager({dimensions:f,scalarData:c.getPointData().getScalars().getData()})).getAtIJKPoint(l)}function y3e(t,e,{viewport:r}){const n=t.representationData.Contour,i=Array.from(n.annotationUIDsMap.keys()),{viewPlaneNormal:o}=r.getCamera();for(const a of i){const s=n.annotationUIDsMap.get(a);if(s)for(const c of s){const l=ri(c);if(!l)continue;const{polyline:f}=l.data.contour;if(Yt(o,l.metadata.viewPlaneNormal)&&XE(e,f))return Number(a)}}}function JG(t,e,{viewport:r,searchRadius:n}){const o=zn(t).representationData.Labelmap;if(r instanceof Or){const{volumeId:p}=o,v=Fe.getVolume(p);if(!v)return;const y=v.voxelManager,m=v.imageData,w=ei(m,e),x=y.getAtIJK(w[0],w[1],w[2]),C=r.worldToCanvas(e);return x3e(C,x,r,m,n)?x:void 0}const a=mf(r.id,t);if(!Fe.getImage(a))return;const c=Pw(r.id,t),l=c==null?void 0:c.actor.getMapper().getInputData(),f=ei(l,e),u=l.getDimensions(),d=l.voxelManager||oc.createScalarVolumeVoxelManager({dimensions:u,scalarData:l.getPointData().getScalars().getData()}),h=d.getAtIJKPoint(f);return w3e(f,u,d,h)?h:void 0}function ZG(t,e,r=1){const n=Array.from({length:2*r+1},(i,o)=>o-r);for(const i of n)for(const o of n)for(const a of n){if(i===0&&o===0&&a===0)continue;const s=t(i,o,a);if(s!==void 0&&e!==s)return!0}return!1}function w3e(t,e,r,n,i){return ZG((a,s,c)=>{const l=[t[0]+a,t[1]+s,t[2]+c];return r.getAtIJK(l[0],l[1],l[2])},n,i)}function x3e(t,e,r,n,i){return ZG((a,s)=>{const c=[t[0]+a,t[1]+s],l=r.canvasToWorld(c),f=n.get("voxelManager").voxelManager,u=ei(n,l);return f.getAtIJK(u[0],u[1],u[2])},e,i)}function QG(t){const e=zn(t),{annotationUIDsMap:r}=e.representationData.Contour;for(const[n,i]of r.entries())if(Array.from(i).find(a=>ri(a).highlighted))return n}const C3e=`
const MAX_STRENGTH = 65535f;
// Workgroup size - X*Y*Z must be multiple of 32 for better performance
@@ -4284,4 +4284,4 @@ throwBindingError('function `+z+" called with ' + arguments.length + ' arguments
`,Mt.push(gn+"_dtor"),mn.push(H[De].destructorFunction))}Pe&&(mt+=`var ret = retType.fromWireType(rv);
return ret;
`),mt+=`}
-`,Mt.push(mt);var ir=ze(Function,Mt).apply(null,mn);return ir}function $e(z,H,L,U,Y,ue){_(H>0);var me=ke(H,L);Y=Ee(U,Y),$i([],[z],function(we){we=we[0];var De="constructor "+we.name;if(we.registeredClass.constructor_body===void 0&&(we.registeredClass.constructor_body=[]),we.registeredClass.constructor_body[H-1]!==void 0)throw new Io("Cannot register multiple constructors with identical number of parameters ("+(H-1)+") for class '"+we.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return we.registeredClass.constructor_body[H-1]=()=>{ge("Cannot construct "+we.name+" due to unbound types",me)},$i([],me,function(Pe){return Pe.splice(1,0,null),we.registeredClass.constructor_body[H-1]=Ve(De,Pe,null,Y,ue),[]}),[]})}function St(z,H,L,U,Y,ue,me,we){var De=ke(L,U);H=Sr(H),ue=Ee(Y,ue),$i([],[z],function(Pe){Pe=Pe[0];var Be=Pe.name+"."+H;H.startsWith("@@")&&(H=Symbol[H.substring(2)]),we&&Pe.registeredClass.pureVirtualFunctions.push(H);function rt(){ge("Cannot call "+Be+" due to unbound types",De)}var mt=Pe.registeredClass.instancePrototype,Bt=mt[H];return Bt===void 0||Bt.overloadTable===void 0&&Bt.className!==Pe.name&&Bt.argCount===L-2?(rt.argCount=L-2,rt.className=Pe.name,mt[H]=rt):(Li(mt,H,Be),mt[H].overloadTable[L-2]=rt),$i([],De,function(Mt){var mn=Ve(Be,Mt,Pe,ue,me);return mt[H].overloadTable===void 0?(mn.argCount=L-2,mt[H]=mn):mt[H].overloadTable[L-2]=mn,[]}),[]})}var wt=[],Tt=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function jt(z){z>4&&--Tt[z].refcount===0&&(Tt[z]=void 0,wt.push(z))}function Dt(){for(var z=0,H=5;H(z||_n("Cannot use deleted val. handle = "+z),Tt[z].value),toHandle:z=>{switch(z){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var H=wt.length?wt.pop():Tt.length;return Tt[H]={refcount:1,value:z},H}}}};function dr(z,H){H=Sr(H),Xr(z,{name:H,fromWireType:function(L){var U=Gn.toValue(L);return jt(L),U},toWireType:function(L,U){return Gn.toHandle(U)},argPackAdvance:8,readValueFromPointer:qr,destructorFunction:null})}function Pr(z){if(z===null)return"null";var H=typeof z;return H==="object"||H==="array"||H==="function"?z.toString():""+z}function Ki(z,H){switch(H){case 2:return function(L){return this.fromWireType(X[L>>2])};case 3:return function(L){return this.fromWireType(te[L>>3])};default:throw new TypeError("Unknown float type: "+z)}}function Po(z,H,L){var U=Xo(L);H=Sr(H),Xr(z,{name:H,fromWireType:function(Y){return Y},toWireType:function(Y,ue){return ue},argPackAdvance:8,readValueFromPointer:Ki(H,U),destructorFunction:null})}function Ur(z,H,L,U,Y,ue){var me=ke(H,L);z=Sr(z),Y=Ee(U,Y),Si(z,function(){ge("Cannot call "+z+" due to unbound types",me)},H-1),$i([],me,function(we){var De=[we[0],null].concat(we.slice(1));return ya(z,Ve(z,De,null,Y,ue),H-1),[]})}function an(z,H,L){switch(H){case 0:return L?function(Y){return V[Y]}:function(Y){return G[Y]};case 1:return L?function(Y){return R[Y>>1]}:function(Y){return N[Y>>1]};case 2:return L?function(Y){return F[Y>>2]}:function(Y){return j[Y>>2]};default:throw new TypeError("Unknown integer type: "+z)}}function Ln(z,H,L,U,Y){H=Sr(H);var ue=Xo(L),me=rt=>rt;if(U===0){var we=32-8*L;me=rt=>rt<>>we}var De=H.includes("unsigned"),Pe=(rt,mt)=>{},Be;De?Be=function(rt,mt){return Pe(mt,this.name),mt>>>0}:Be=function(rt,mt){return Pe(mt,this.name),mt},Xr(z,{name:H,fromWireType:me,toWireType:Be,argPackAdvance:8,readValueFromPointer:an(H,ue,U!==0),destructorFunction:null})}function Ro(z,H,L){var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Y=U[H];function ue(me){me=me>>2;var we=j,De=we[me],Pe=we[me+1];return new Y(A,Pe,De)}L=Sr(L),Xr(z,{name:L,fromWireType:ue,argPackAdvance:8,readValueFromPointer:ue},{ignoreDuplicateRegistrations:!0})}function Nt(z,H){H=Sr(H);var L=H==="std::string";Xr(z,{name:H,fromWireType:function(U){var Y=j[U>>2],ue=U+4,me;if(L)for(var we=ue,De=0;De<=Y;++De){var Pe=ue+De;if(De==Y||G[Pe]==0){var Be=Pe-we,rt=D(we,Be);me===void 0?me=rt:(me+="\0",me+=rt),we=Pe+1}}else{for(var mt=new Array(Y),De=0;De>2]=ue,L&&me)P(Y,De,ue+1);else if(me)for(var Pe=0;Pe255&&(ye(De),_n("String has UTF-16 code units that do not fit in 8 bits")),G[De+Pe]=Be}else for(var Pe=0;Pe>1,Y=U+H/2;!(U>=Y)&&N[U];)++U;if(L=U<<1,L-z>32&&er)return er.decode(G.subarray(z,L));for(var ue="",me=0;!(me>=H/2);++me){var we=R[z+me*2>>1];if(we==0)break;ue+=String.fromCharCode(we)}return ue}function Er(z,H,L){if(L===void 0&&(L=2147483647),L<2)return 0;L-=2;for(var U=H,Y=L>1]=me,H+=2}return R[H>>1]=0,H-U}function Rr(z){return z.length*2}function as(z,H){for(var L=0,U="";!(L>=H/4);){var Y=F[z+L*4>>2];if(Y==0)break;if(++L,Y>=65536){var ue=Y-65536;U+=String.fromCharCode(55296|ue>>10,56320|ue&1023)}else U+=String.fromCharCode(Y)}return U}function vo(z,H,L){if(L===void 0&&(L=2147483647),L<4)return 0;for(var U=H,Y=U+L-4,ue=0;ue=55296&&me<=57343){var we=z.charCodeAt(++ue);me=65536+((me&1023)<<10)|we&1023}if(F[H>>2]=me,H+=4,H+4>Y)break}return F[H>>2]=0,H-U}function Yl(z){for(var H=0,L=0;L=55296&&U<=57343&&++L,H+=4}return H}function Jl(z,H,L){L=Sr(L);var U,Y,ue,me,we;H===2?(U=bn,Y=Er,me=Rr,ue=()=>N,we=1):H===4&&(U=as,Y=vo,me=Yl,ue=()=>j,we=2),Xr(z,{name:L,fromWireType:function(De){for(var Pe=j[De>>2],Be=ue(),rt,mt=De+4,Bt=0;Bt<=Pe;++Bt){var Mt=De+4+Bt*H;if(Bt==Pe||Be[Mt>>we]==0){var mn=Mt-mt,gn=U(mt,mn);rt===void 0?rt=gn:(rt+="\0",rt+=gn),mt=Mt+H}}return ye(De),rt},toWireType:function(De,Pe){typeof Pe!="string"&&_n("Cannot pass non-string to C++ string type "+L);var Be=me(Pe),rt=ne(4+Be+H);return j[rt>>2]=Be>>we,Y(Pe,rt+4,Be+H),De!==null&&De.push(ye,rt),rt},argPackAdvance:8,readValueFromPointer:qr,destructorFunction:function(De){ye(De)}})}function rl(z,H,L,U,Y,ue){Pn[z]={name:Sr(H),rawConstructor:Ee(L,U),rawDestructor:Ee(Y,ue),fields:[]}}function yf(z,H,L,U,Y,ue,me,we,De,Pe){Pn[z].fields.push({fieldName:Sr(H),getterReturnType:L,getter:Ee(U,Y),getterContext:ue,setterArgumentType:me,setter:Ee(we,De),setterContext:Pe})}function Zl(z,H){H=Sr(H),Xr(z,{isVoid:!0,name:H,argPackAdvance:0,fromWireType:function(){},toWireType:function(L,U){}})}function wf(z){z>4&&(Tt[z].refcount+=1)}function Ql(z,H){var L=ht[z];return L===void 0&&_n(H+" has unknown type "+pe(z)),L}function xf(z,H){z=Ql(z,"_emval_take_value");var L=z.readValueFromPointer(H);return Gn.toHandle(L)}function Cf(){We("")}function Sf(z,H,L){G.copyWithin(z,H,H+L)}function Tf(){return 2147483648}function il(z){try{return S.grow(z-A.byteLength+65535>>>16),fe(S.buffer),1}catch{}}function ol(z){var H=G.length;z=z>>>0;var L=Tf();if(z>L)return!1;let U=(De,Pe)=>De+(Pe-De%Pe)%Pe;for(var Y=1;Y<=4;Y*=2){var ue=H*(1+.2/Y);ue=Math.min(ue,z+100663296);var me=Math.min(L,U(Math.max(z,ue),65536)),we=il(me);if(we)return!0}return!1}function Va(z){return 52}function ss(z,H,L,U,Y){return 70}var ea=[null,[],[]];function eu(z,H){var L=ea[z];H===0||H===10?((z===1?w:x)(b(L,0)),L.length=0):L.push(H)}function tu(z,H,L,U){for(var Y=0,ue=0;ue>2],we=j[H+4>>2];H+=8;for(var De=0;De>2]=Y,0}function al(z){return z}function nu(z){var H=o["_"+z];return H}function hc(z,H){V.set(z,H)}function ru(z,H,L,U,Y){var ue={string:Mt=>{var mn=0;if(Mt!=null&&Mt!==0){var gn=(Mt.length<<2)+1;mn=ft(gn),P(Mt,mn,gn)}return mn},array:Mt=>{var mn=ft(Mt.length);return hc(Mt,mn),mn}};function me(Mt){return H==="string"?D(Mt):H==="boolean"?!!Mt:Mt}var we=nu(z),De=[],Pe=0;if(U)for(var Be=0;Be