var Mb={4242:(oe,Re,G)=>{G.d(Re,{G1:()=>w,YR:()=>pe,y6:()=>A});var z=G(8796);/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var A=(be=>(be[be.MIN_REPRESENTATIVE=0]="MIN_REPRESENTATIVE",be[be.MAX_REPRESENTATIVE=1]="MAX_REPRESENTATIVE",be[be.REPRESENTATIVE_EXCLUDED=2]="REPRESENTATIVE_EXCLUDED",be[be.NONREPRESENTATIVE_EXCLUDED=4]="NONREPRESENTATIVE_EXCLUDED",be))(A||{});function pe(be){return!(be.high>>>31)}const w=new z.R(4294967295,4294967295)},3206:(oe,Re,G)=>{G.d(Re,{B0:()=>w,DN:()=>be,DY:()=>J,Kk:()=>Ge,Uq:()=>Te,W1:()=>I,XZ:()=>ie,_Y:()=>$e,aM:()=>q,no:()=>Ve,ol:()=>ge,pz:()=>me,rG:()=>B,wP:()=>Ze});var z=G(5716),A=G(2596),pe=G(4038);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class w{constructor(N){this.value_=N,this.changed=new pe.IY}get value(){return this.value_}set value(N){N!==this.value_&&(this.value_=N,this.changed.dispatch())}}class be extends w{constructor(N,D,F=N){super(N),this.validator=D,this.defaultValue=F}toJSON(){const{value_:N}=this;if(N!==this.defaultValue)return this.value_}reset(){this.value=this.defaultValue}restoreState(N){if(N!==void 0){const{validator:D}=this;try{this.value=D(N);return}catch{}}this.value=this.defaultValue}}class Ee extends A.O8{constructor(N,D){super(),this.changed=new pe.IY,this.f=N,this.ws=D;for(const F of D)this.registerDisposer(F.changed.add(this.changed.dispatch))}get value(){return this.f(...this.ws.map(N=>N.value))}}function Ge(U,...N){return new Ee(U,N)}class Oe extends A.O8{constructor(N,D){super(),this.changed=new pe.IY,this.valueGeneration=-1,this.f=N,this.ws=D;for(const F of D)this.registerDisposer(F.changed.add(this.changed.dispatch))}get value(){const N=this.changed.count;return N!==this.valueGeneration&&(this.value_=this.f(...this.ws.map(D=>D.value)),this.valueGeneration=N),this.value_}}function ge(U,...N){return new Oe(U,N)}class me extends A.O8{constructor(N,D=(F,Z)=>F===Z){super(),this.changed=new pe.HN,this.value=N.value,this.registerDisposer(N.changed.add(()=>{const F=N.value;D(this.value,F)||(this.value=F,this.changed.dispatch())}))}}function Te(U,N,D){const F=new Ee(U,N),Z=new me(F,D);return Z.registerDisposer(F),Z}class Ze extends A.O8{constructor(N){super(),this.changed=new pe.IY;const D=N(this),F=Object.keys(D),Z=()=>{const te=Array.isArray(D)?[]:{};for(const ye of F)te[ye]=D[ye].value;this.value=te,this.changed.dispatch()};Z();for(const te of F){const ye=D[te];this.registerDisposer(ye.changed.add(()=>Z()))}}}class Pt extends A.O8{constructor(N,...D){super(),this.f=N,this.changed=new pe.IY;for(const F of D)this.registerDisposer(F.add(this.changed.dispatch))}get value(){return this.f()}}class ze extends A.O8{constructor(){super(...arguments),this.changed=new pe.IY}get value(){return this.value_}set value(N){const{value_:D}=this;if(this.value_=N,D!==void 0&&(D.dispose(),D.unregisterDisposer(this.valueHandler),this.valueHandler=void 0),N!==void 0){const F=this.valueHandler=()=>{this.value_===N&&(this.value_=void 0,this.changed.dispatch())};N.registerDisposer(F)}N!==D&&this.changed.dispatch()}reset(){this.value=void 0}disposed(){this.value_!==void 0&&(this.value_.unregisterDisposer(this.valueHandler),this.value_.dispose()),this.value_=void 0,super.disposed()}}class xt extends ze{constructor(N,D){super(),this.validator=N,this.jsonConverter=D}toJSON(){const{value:N}=this;return N&&this.jsonConverter(N)}restoreState(N){this.value=this.validator(N)}}class $e{constructor(N){this.changed=new pe.HN,N===void 0?this.values=new Set:this.values=new Set(N)}add(N){const{values:D}=this;return D.has(N)||(D.add(N),this.changed.dispatch(N,!0)),this}delete(N){const{values:D}=this;return D.delete(N)?(this.changed.dispatch(N,!1),!0):!1}has(N){return this.values.has(N)}get size(){return this.values.size}[Symbol.iterator](){return this.values[Symbol.iterator]()}clear(){const{values:N}=this;N.size>0&&(N.clear(),this.changed.dispatch(null,!1))}}function Ve(U,...N){const D=N.map(Qe=>Qe.value),F=N.length;let Z=new A.O8,te=U(Z,...D);const ye=(0,z.A)(()=>{let Qe=!1;for(let We=0;We<F;++We){const Yt=N[We].value;D[We]!==Yt&&(D[We]=Yt,Qe=!0)}Qe&&(Z.dispose(),Z=new A.O8,te=U(Z,...D))},0),Ye=N.map(Qe=>Qe.changed.add(ye));return{flush(){ye.flush()},dispose(){ye.cancel(),(0,A.$F)(Ye),Z.dispose()},get value(){return ye.flush(),te}}}function q(U,...N){const D=N.map(Qe=>Qe.value),F=N.length;let Z=new A.O8,te=U(Z,...D);const ye=()=>{let Qe=!1;for(let We=0;We<F;++We){const Yt=N[We].value;D[We]!==Yt&&(D[We]=Yt,Qe=!0)}Qe&&(Z.dispose(),Z=new A.O8,te=U(Z,...D))},Ye=N.map(Qe=>Qe.changed.add(ye));return{dispose(){(0,A.$F)(Ye),Z.dispose()},get value(){return te}}}function ie(U){return{changed:pe.$$,value:U}}function I(U,N){return U(N.value),N.changed.add(()=>U(N.value))}function re(U,N){return N.value=U.value,U.changed.add(()=>{N.value=U.value})}class B{constructor(N,D){this.outer=N,this.getInner=D,this.changed=new pe.IY,this.update=()=>{const{disposer:F,outer:Z}=this;F!==void 0&&F();const te=this.inner=this.getInner(Z.value);this.disposer=te.changed.add(this.changed.dispatch),this.changed.dispatch()},N.changed.add(this.update),this.update()}dispose(){this.outer.changed.remove(this.update),this.disposer()}get value(){return this.inner.value}set value(N){this.inner.value=N}}class J extends B{reset(){this.inner.reset()}restoreState(N){this.inner.restoreState(N)}toJSON(){return this.inner.toJSON()}}},4037:(oe,Re,G)=>{G.d(Re,{CS:()=>Ee,El:()=>Ge,Lp:()=>Oe,NT:()=>re,RO:()=>Ve,U8:()=>A,ak:()=>I,b8:()=>$e,eL:()=>q,eN:()=>me,ep:()=>ze,jx:()=>pe,lX:()=>ge,r1:()=>Ze,wm:()=>Pt});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function z(B,J,U,N){for(;J<U;){const D=B[J];if(N(D)){++J;continue}--U,B[J]=B[U],B[U]=D}return U}function A(B,J){const U=B.length;let N=0;for(let D=0;D<U;++D)J(B[D],D,B)&&(B[N]=B[D],++N);B.length=N}function pe(B,J){if(B.length===J)return B;const U=new B.constructor(J);return U.set(B),U}function w(B,J=1){const U=B.length,N=new Array(U);let D=N[0]=J;for(let F=1;F<U;++F)D*=B[F-1],N[F]=D;return N}function be(B,J,U){const N=new B.constructor(B.length);for(let D=0;D<J*U;D+=U)for(let F=0;F<U;F++){const Z=D/U;N[F*J+Z]=B[D+F]}return N}function Ee(B,J,U,N){const D=B.length/J,F=B.length*U*N,Z=new B.constructor(F),te=B.length*N,ye=J,Ye=J*N;for(let Qe=0;Qe<D;++Qe)for(let We=0;We<J;++We){const Cn=B[Qe*J+We],Yt=Qe*Ye+We;for(let Zn=0;Zn<U;++Zn)for(let p=0;p<N;++p)Z[Zn*te+p*ye+Yt]=Cn}return Z}function Ge(B,J,U,N=0,D=B.length){for(;N<D;){const F=N+D-1>>1,Z=U(J,B[F]);if(Z>0)N=F+1;else if(Z<0)D=F;else return F}return~N}function Oe(B,J,U,N=0,D=B.length){let F=-1,Z=1/0;for(;N<D;){const te=N+D-1>>1,ye=U(J,B[te]);if(ye>0)N=te+1;else if(ye<0)D=te;else return te;const Ye=Math.abs(ye);Ye<Z&&(Z=Ye,F=te)}return F}function ge(B,J,U){let N=J-B;for(;N>0;){const D=Math.floor(N/2),F=B+D;U(F)?N=D:(B=F+1,N-=D+1)}return B}function me(B,J){const U=[];for(let N=0,D=B.length;N<D;++N)B[N]===J&&U.push(N);return U}function Te(B,J){const U=[];U.length=J;for(const N of B)U[N]=!0;return me(U,void 0)}function Ze(B,J){const U=B.length;if(J.length!==U)return!1;for(let N=0;N<U;++N)if(B[N]!==J[N])return!1;return!0}function Pt(B,J,U=(N,D)=>N===D){const N=B.length;if(J.length!==N)return!1;for(let D=0;D<N;++D)if(!U(B[D],J[D]))return!1;return!0}function ze(B,J,U){const N=[];if(U===J){for(let D=0;D<B;++D)N[D]=D;return N}N[U]=J;for(let D=0,F=0;D<B;){if(D===J){++D;continue}F===U&&++F,N[F++]=D++}return N}function xt(B,J,U){for(let N=0,D=U.length;N<D;++N){const F=U[N];F!==-1&&(B[F]=J[N])}return B}function $e(B,J,U){for(let N=0,D=U.length;N<D;++N){const F=U[N];F!==-1&&(B[N]=J[F])}return B}function Ve(B){const J=[];for(let U=0,N=B.length;U<N;++U){const D=B[U];for(let F=0,Z=D.length;F<Z;++F){let te=J[F];te===void 0&&(te=J[F]=[]),te.push(D[F])}}return J}function q(B,J){const U=[];let N=0;for(let F=0,Z=J.length;F<Z;++F){const{retainCount:te,deleteCount:ye,insertCount:Ye}=J[F];te!==0&&(U.push(B.slice(N,N+te)),N+=te),N+=ye,Ye!==0&&U.push(new Array(Ye))}const D=B.length;return N!==D&&U.push(B.slice(N)),new Array(0).concat(...U)}function ie(B,J,U){const N=[];let D=0,F=0;const Z=B.length,te=J.length;for(;D<Z&&F<te;){let ye;const Ye=B[D],Qe=J[F];if(ye=U(Ye,Qe),ye===0){let We=1;for(++D,++F;D<Z&&F<te&&(ye=U(B[D],J[F]))===0;)++We,++D,++F;N.push({retainCount:We,deleteCount:0,insertCount:0});continue}if(ye<0){let We=1;for(;++D<Z&&(ye=U(B[D],Qe))<0;)++We;N.push({retainCount:0,deleteCount:We,insertCount:0});continue}if(ye>0){let We=1;for(;++F<te&&(ye=U(Ye,J[F]))>0;)++We;N.push({retainCount:0,deleteCount:0,insertCount:We})}}return(D<Z||F<te)&&N.push({retainCount:0,deleteCount:Z-D,insertCount:te-F}),N}function I(B,J,U){const N=[];let D=0,F=0;const Z=B.length,te=J.length;for(;D<Z;){let ye=0;for(;D<Z&&F<te&&U(B[D],J[F]);)++ye,++D,++F;ye!==0&&N.push({retainCount:ye,deleteCount:0,insertCount:0});let Ye=0;for(;D<Z&&(F===te||!U(B[D],J[F]));)++Ye,++D;Ye!==0&&N.push({retainCount:0,deleteCount:Ye,insertCount:0})}return F!==te&&N.push({retainCount:0,deleteCount:0,insertCount:te-F}),N}function re(B,J,U,N,D,F){let Z=0,te=0;if(B!==0&&J!==0)for(;;){const ye=U(Z,te);if(ye<0){if(N(Z),++Z===B)break}else if(ye>0){if(D(te),++te===J)break}else if(F(Z,te),++Z,++te,Z===B||te===J)break}for(;Z<B;)N(Z),++Z;for(;te<J;)D(te),++te}},4509:(oe,Re,G)=>{G.d(Re,{Dq:()=>pe,Qi:()=>Ee,fx:()=>be,gI:()=>Oe,wS:()=>A,y3:()=>Ge});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class z extends Error{constructor(){super(...arguments),this.name="CancellationError",this.message="CANCELED"}toString(){return"CANCELED"}}const A=new z;function pe(ge){if(ge.isCanceled===!0)throw A}const w=()=>{},be={isCanceled:!1,add:()=>w,remove:w};class Ee{cancel(){const{handlers:me}=this;if(me!==null&&(this.handlers=null,me!==void 0))for(const Te of me)Te()}get isCanceled(){return this.handlers===null}add(me){let{handlers:Te}=this;return Te===null?(me(),w):(Te===void 0&&(Te=this.handlers=new Set),Te.add(me),()=>{this.remove(me)})}remove(me){const{handlers:Te}=this;Te?.delete(me)}}class Ge extends Ee{constructor(){super(...arguments),this.consumers=new Set}addConsumer(me=be){const{consumers:Te}=this;Te.has(me)||me.isCanceled||(Te.add(me),me.add(()=>{Te.delete(me),Te.size===0&&this.cancel()}))}}function Oe(ge,me){return new Promise((Te,Ze)=>{if(ge===be){me(Te,Ze,be);return}const Pt=new Ee,ze=ge.add(()=>{Pt.cancel()});me(xt=>{ze(),Te(xt)},xt=>{ze(),Ze(xt)},Pt)})}},2596:(oe,Re,G)=>{G.d(Re,{$F:()=>pe,K6:()=>w,K9:()=>Ge,O8:()=>be,fL:()=>Ee});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const z=!1;function A(Oe){typeof Oe=="object"?Oe.dispose():Oe()}function pe(Oe){for(let ge=Oe.length;ge>0;--ge)A(Oe[ge-1])}function w(Oe,ge,me,Te){return Oe.addEventListener(ge,me,Te),()=>Oe.removeEventListener(ge,me,Te)}class be{constructor(){this.refCount=1}addRef(){return++this.refCount,this}dispose(){z&&(this.disposedStacks=this.disposedStacks||[]).push(new Error().stack),--this.refCount===0&&this.refCountReachedZero()}refCountReachedZero(){this.disposed();const{disposers:ge}=this;ge!==void 0&&(pe(ge),this.disposers=void 0),this.wasDisposed=!0}disposed(){}registerDisposer(ge){const{disposers:me}=this;return me==null?this.disposers=[ge]:me.push(ge),ge}unregisterDisposer(ge){const{disposers:me}=this;if(me!=null){const Te=me.indexOf(ge);Te!==-1&&me.splice(Te,1)}return ge}registerEventListener(ge,me,Te,Ze){this.registerDisposer(w(ge,me,Te,Ze))}registerCancellable(ge){return this.registerDisposer(()=>{ge.cancel()}),ge}}class Ee extends be{constructor(ge){super(),this.value=ge}}function Ge(Oe){return()=>{if(Oe!==void 0){const ge=Oe;Oe=void 0,A(ge)}}}},3038:(oe,Re,G)=>{G.d(Re,{I1:()=>Cn,Jh:()=>We,Oi:()=>Pt,PC:()=>Ye,Qi:()=>Zn,T2:()=>me,T_:()=>te,Yu:()=>w,Zc:()=>Ge,_A:()=>F,_S:()=>Z,_q:()=>D,bS:()=>ns,eR:()=>A,ln:()=>pe,nL:()=>q,p9:()=>ge,pB:()=>z,qp:()=>ye,r3:()=>Oe,sJ:()=>Yt,uD:()=>J,vs:()=>B,w0:()=>Ee,xK:()=>$e,yb:()=>Ze});var z=G(7684),A=G(329),pe=G(4796),w=G(2221),be=G(4037),Ee=G(1409),Ge=G(842);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Oe=z.create(),ge=["x","y","z"],me=[A.fromValues(1,0,0),A.fromValues(0,1,0),A.fromValues(0,0,1)],Te=A.fromValues(0,0,0),Ze=pe.fromValues(0,0,0,0),Pt=A.fromValues(1,1,1),ze=A.fromValues(1/0,1/0,1/0),xt=w.create();function $e(W){return W[0]*W[1]*W[2]}function Ve(W){return W[0]*W[1]*W[2]*W[3]}function q(W){return`${W[0]},${W[1]},${W[2]}`}function ie(W,Y){const de=Y[0],M=Y[1],ue=Y[2],se=Y[3];W[0]=se,W[1]=ue,W[2]=-M,W[3]=-de}function I(W,Y){const de=Y[0],M=Y[1],ue=Y[2],se=Y[3];W[0]=-ue,W[1]=se,W[2]=de,W[3]=-M}function re(W,Y){const de=Y[0],M=Y[1],ue=Y[2],se=Y[3];W[0]=M,W[1]=-de,W[2]=se,W[3]=-ue}function B(W,Y,de){const M=Y[0],ue=Y[1],se=Y[2];return W[0]=de[0]*M+de[4]*ue+de[8]*se,W[1]=de[1]*M+de[5]*ue+de[9]*se,W[2]=de[2]*M+de[6]*ue+de[10]*se,W}function J(W,Y,de){const M=Y[0],ue=Y[1],se=Y[2];return W[0]=de[0]*M+de[1]*ue+de[2]*se,W[1]=de[4]*M+de[5]*ue+de[6]*se,W[2]=de[8]*M+de[9]*ue+de[10]*se,W}function U(W,Y,de,M,ue){const se=W;return W[0]=M[0],W[1]=M[1],W[2]=M[2]*ue,mat4.fromRotationTranslationScale(W,de,Y,se)}function N(W,Y,de){const M=de.length;let ue=0;for(let he=0;he<M;++he)ue+=(W[he]-Y[he])**2;let se=0;for(let he=0;he<M;++he){const Le=W[he];se-=(Le-de[he])*(Y[he]-Le)}return se/Math.max(ue,1e-6)}function D(W,Y,de,M){const ue=W.length;let se=N(Y,de,M);se=Math.max(0,Math.min(1,se));for(let he=0;he<ue;++he){const Le=Y[he];W[he]=Le+se*(de[he]-Le)}return W}function F(W,Y){const de=Y[0],M=Y[1],ue=Y[2],se=Y[4],he=Y[5],Le=Y[6],qe=Y[8],Xe=Y[9],tt=Y[10];return W[0]=de,W[1]=M,W[2]=ue,W[3]=se,W[4]=he,W[5]=Le,W[6]=qe,W[7]=Xe,W[8]=tt,W}function Z(W,Y){const de=Y[0],M=Y[1],ue=Y[2],se=Y[3],he=Y[4],Le=Y[5],qe=Y[6],Xe=Y[7],tt=Y[8],nt=Y[9],ct=Y[10],Qt=Y[11],Vn=Y[12],qt=Y[13],is=Y[14],Et=Y[15];W[0]=se+de,W[1]=Xe+he,W[2]=Qt+tt,W[3]=Et+Vn,W[4]=se-de,W[5]=Xe-he,W[6]=Qt-tt,W[7]=Et-Vn,W[8]=se+M,W[9]=Xe+Le,W[10]=Qt+nt,W[11]=Et+qt,W[12]=se-M,W[13]=Xe-Le,W[14]=Qt-nt,W[15]=Et-qt;const wi=se+ue,O=Xe+qe,H=Qt+ct,ne=Et+is,ae=se-ue,Ce=Xe-qe,De=Qt-ct,it=Et-is,ot=Math.sqrt(wi**2+O**2+H**2);W[16]=wi/ot,W[17]=O/ot,W[18]=H/ot,W[19]=ne/ot;const _t=Math.sqrt(ae**2+Ce**2+De**2);return W[20]=ae/_t,W[21]=Ce/_t,W[22]=De/_t,W[23]=it/_t,W}function te(W,Y,de,M,ue,se,he){for(let Le=0;Le<6;++Le){const qe=he[Le*4],Xe=he[Le*4+1],tt=he[Le*4+2],nt=he[Le*4+3];if(Math.max(qe*W,qe*M)+Math.max(Xe*Y,Xe*ue)+Math.max(tt*de,tt*se)+nt<0)return!1}return!0}function ye(W,Y,de,M,ue,se,he){for(let Le=0;Le<4;++Le){const qe=he[Le*4],Xe=he[Le*4+1],tt=he[Le*4+2],nt=he[Le*4+3];if(Math.max(qe*W,qe*M)+Math.max(Xe*Y,Xe*ue)+Math.max(tt*de,tt*se)+nt<0)return!1}{const qe=he[20],Xe=he[5*4+1],tt=he[5*4+2],nt=he[5*4+3],ct=Math.max(qe*W,qe*M)+Math.max(Xe*Y,Xe*ue)+Math.max(tt*de,tt*se),Qt=Math.min(qe*W,qe*M)+Math.min(Xe*Y,Xe*ue)+Math.min(tt*de,tt*se),Vn=Math.abs(nt)*1e-6;if(Qt>-nt+Vn||ct<-nt-Vn)return!1}return!0}function Ye(W,Y,de,M=!1){const ue=de.length,se=[],he=M?1:Y+1,Le=M?Y+1:1;for(let qe=0;qe<ue;++qe){const Xe=de[qe];for(let tt=0;tt<Y;++tt)W[tt*he+Xe*Le]!==0&&(se[tt]=!0)}return(0,be.eN)(se,!0)}function Qe(W,Y,de){for(let M=0;M<3;++M){const ue=de[M];for(let se=0;se<3;++se)W[se+M*3]=ue*Y[se+M*3]}return W}function We(W,Y,de){for(let M=0;M<3;++M){const ue=de[M];for(let se=0;se<3;++se)W[M+se*3]=ue*Y[M+se*3]}return W}function Cn(W){if(W[15]===1){const he=2/Math.abs(W[10]),Le=2/Math.abs(W[0]),qe=2/Math.abs(W[5]);return Le*qe*he}const Y=W[10],M=2*W[14]/(2*Y-2),ue=(Y-1)*M/(Y+1);return 4/(W[0]*W[5])/3*(Math.abs(ue)**3-Math.abs(M)**3)}function Yt(W){if(W[15]===1)return 2/Math.abs(W[10]);const Y=W[10],M=2*W[14]/(2*Y-2),ue=(Y-1)*M/(Y+1);return Math.abs(ue-M)}function Zn(W){return W[2]=0,W[6]=0,W[10]=0,W[14]=0,W}const p=A.create();function ns(W,Y){Y[0]=Y[1]=Y[2]=Number.POSITIVE_INFINITY,Y[3]=Y[4]=Y[5]=Number.NEGATIVE_INFINITY;for(let de=0;de<8;++de){p[0]=2*(de&1)-1,p[1]=2*(de>>>1&1)-1,p[2]=2*(de>>>2&1)-1,A.transformMat4(p,p,W);for(let M=0;M<3;++M){const ue=p[M];Y[M]=Math.min(Y[M],ue),Y[M+3]=Math.max(Y[M+3],ue)}}}},9808:(oe,Re,G)=>{G.d(Re,{Bk:()=>Te,Dl:()=>ze,El:()=>xt,JZ:()=>Ge,Rc:()=>ge,cj:()=>me,j$:()=>pe,vd:()=>Oe});var z=G(4509),A=G(8796);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class pe extends Error{constructor(Ve,q,ie,I){let re=`Fetching ${JSON.stringify(Ve)} resulted in HTTP error ${q}`;ie&&(re+=`: ${ie}`),re+=".",super(re),this.name="HttpError",this.message=re,this.url=Ve,this.status=q,this.statusText=ie,I&&(this.response=I)}static fromResponse(Ve){return new pe(Ve.url,Ve.status,Ve.statusText,Ve)}static fromRequestError(Ve,q){if(q instanceof TypeError){let ie;return typeof Ve=="string"?ie=Ve:ie=Ve.url,new pe(ie,0,"Network or CORS error")}return q}}const w=32,be=500,Ee=1e4;function Ge($e){return Math.min(2**$e*be,Ee/2)*(1+Math.random())}async function Oe($e,Ve){for(let q=0;;){if(Ve?.signal?.aborted)throw z.wS;let ie;try{ie=await fetch($e,Ve)}catch(I){throw pe.fromRequestError($e,I)}if(!ie.ok){const{status:I}=ie;if((I===429||I===503||I===504)&&++q!==w){await new Promise(re=>setTimeout(re,Ge(q-1)));continue}throw pe.fromResponse(ie)}return ie}}function ge($e){return $e.arrayBuffer()}function me($e){return $e.json()}async function Te($e,Ve,q,ie=z.fx){if(ie===z.fx){const B=await Oe($e,Ve);return await q(B)}const I=new AbortController,re=ie.add(()=>I.abort());try{const B=await Oe($e,{...Ve,signal:I.signal});return await q(B)}finally{re()}}const Ze=new A.R;function Pt($e,Ve){let q;return typeof Ve=="number"?q=`${Ve-1}`:(Uint64.decrement(Ze,Ve),q=Ze.toString()),{Range:`bytes=${$e}-${q}`}}function ze($e){const Ve=/^([^:/]+):\/\/([^/]+)((?:\/.*)?)$/,q=$e.match(Ve);if(q===null)throw new Error(`Invalid URL: ${JSON.stringify($e)}`);return{protocol:q[1],host:q[2],path:q[3]}}function xt($e){return $e instanceof pe?$e.status===0||$e.status===403||$e.status===404:!1}},7900:(oe,Re,G)=>{G.d(Re,{$v:()=>ye,B8:()=>Yt,DW:()=>Ge,J6:()=>te,JB:()=>me,JY:()=>Ee,MM:()=>ue,Mo:()=>be,Rf:()=>Qe,Sf:()=>D,VH:()=>Vn,Vr:()=>Oe,We:()=>Cn,Xu:()=>Ye,ZD:()=>wi,Zu:()=>is,Zw:()=>w,_D:()=>A,aO:()=>qt,bL:()=>Le,bX:()=>We,by:()=>nt,cQ:()=>M,f4:()=>tt,gG:()=>ct,j3:()=>Zn,qi:()=>Et,si:()=>Qt,sl:()=>Xe,uS:()=>Y,uz:()=>qe,vS:()=>se,vp:()=>ge,xU:()=>he,z$:()=>ns,zB:()=>W,zo:()=>pe,zr:()=>p});var z=G(3038);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function A(O){const H=typeof O;if(H==="number"||H==="string"){const ne=parseFloat(""+O);if(!Number.isNaN(ne))return ne}throw new Error(`Expected floating-point number, but received: ${JSON.stringify(O)}.`)}function pe(O){const H=A(O);if(Number.isFinite(H))return H;throw new Error(`Expected finite floating-point number, but received: ${H}.`)}function w(O){const H=A(O);if(Number.isFinite(H)&&H>=0)return H;throw new Error(`Expected finite non-negative floating-point number, but received: ${H}.`)}function be(O){const H=pe(O);if(H>0)return H;throw new Error(`Expected positive finite floating-point number, but received: ${H}.`)}function Ee(O,H){return ne=>{const ae=A(ne);if(ae>=O&&ae<=H)return ae;throw new Error(`Expected floating-point number in range [${O}, ${H}], but received: ${ae}.`)}}function Ge(O,H,ne=A){Qe(H),O[0]=O[1]=O[2]=0;for(const ae of Object.keys(H))switch(ae){case"x":O[0]=ne(H[ae]);break;case"y":O[1]=ne(H[ae]);break;case"z":O[2]=ne(H[ae]);break;default:throw new Error(`Expected object to have keys ['x', 'y', 'z'], but received: ${JSON.stringify(H)}.`)}return O}function Oe(O,H){const ne=O.length;if(!Array.isArray(H)||H.length!==ne)throw new Error("Incompatible sizes");for(let ae=0;ae<ne;++ae)if(!Number.isFinite(parseFloat(H[ae])))throw new Error("Non-finite value.");for(let ae=0;ae<ne;++ae)O[ae]=parseFloat(H[ae]);return O}function ge(O,H){const ne=O.length;if(!Array.isArray(H)||H.length!==ne)throw new Error("Incompatible sizes.");for(let ae=0;ae<ne;++ae){const Ce=parseInt(H[ae],void 0);if(!Number.isInteger(Ce))throw new Error("Non-integer value.")}for(let ae=0;ae<ne;++ae)O[ae]=parseInt(H[ae],void 0);return O}function me(O){if(typeof O=="object"){if(O===null)return"null";if(Array.isArray(O)){let De="[";const it=O.length;let ot=0;if(ot<it)for(De+=me(O[ot]);++ot<it;)De+=",",De+=me(O[ot]);return De+="]",De}let H="{";const ne=Object.keys(O).sort();let ae=0;const Ce=ne.length;if(ae<Ce){let De=ne[ae];for(H+=JSON.stringify(De),H+=":",H+=me(O[De]);++ae<Ce;)H+=",",De=ne[ae],H+=JSON.stringify(De),H+=":",H+=me(O[De])}return H+="}",H}return JSON.stringify(O)}function Te(O){return O.replace(/['"]/g,H=>H==='"'?"'":'"')}function Ze(O){return Te(JSON.stringify(Te(O)))}const Pt="_";function ze(O){if(typeof O=="object"){if(O===null)return"null";const H=O.toJSON;if(typeof H=="function")return ze(H.call(O));if(Array.isArray(O)){let De="[";const it=O.length;let ot=0;if(ot<it)for(De+=ze(O[ot]);++ot<it;)De+=Pt,De+=ze(O[ot]);return De+="]",De}let ne="{";const ae=Object.keys(O);let Ce=!0;for(const De of ae){const it=O[De];if(it===void 0)continue;const ot=ze(it);ot&&(Ce?Ce=!1:ne+=Pt,ne+=Ze(De),ne+=":",ne+=ot)}return ne+="}",ne}return typeof O=="string"?Ze(O):JSON.stringify(O)}const xt=/('(?:[^'\\]|(?:\\.))*')/,$e=/("(?:[^"\\]|(?:\\.))*")/,Ve=new RegExp(`${xt.source}|${$e.source}`),q=new RegExp(`${$e.source}|${xt.source}`),ie=/^((?:[^"'\\]|(?:\\[^']))*)("|\\')/,I=/^((?:[^"'\\]|(?:\\.))*)'/;function re(O,H,ne,ae){if(O.length>=2&&O.charAt(0)===H&&O.charAt(O.length-1)===H){let Ce=O.substr(1,O.length-2),De=ne;for(;Ce.length>0;){const it=Ce.match(ae);if(it===null){De+=Ce;break}De+=it[1],it[2]===ne?(De+="\\",De+=ne):De+=H,Ce=Ce.substr(it.index+it[0].length)}return De+=ne,De}return O}function B(O){return re(O,"'",'"',ie)}function J(O,H,ne){const ae=/[&_,]/g;let Ce,De,it;ne==='"'?(Ce="'",De=ie,it=Ve):(Ce='"',De=I,it=q);let ot="";for(;O.length>0;){const _t=O.match(it);let j,ei;if(_t===null)j=O,O="",ei="";else{j=O.substr(0,_t.index),O=O.substr(_t.index+_t[0].length);const Je=_t[1];Je!==void 0?ei=re(Je,Ce,ne,De):ei=_t[2]}ot+=j.replace(ae,H),ot+=ei}return ot}function U(O){return J(O,",",'"')}function N(O){return J(O,"_","'")}function D(O){return JSON.parse(U(O))}function F(O){let H="";for(;O.length>0;){const ne=O.match(Ve);let ae,Ce;if(ne===null)ae=O,O="",Ce="";else{ae=O.substr(0,ne.index),O=O.substr(ne.index+ne[0].length);const De=ne[1];De!==void 0?Ce=B(De):Ce=ne[2]}H+=ae.replace(/\(/g,"[").replace(/\)/g,"]").replace("True","true").replace("False","false").replace(/,\s*([}\]])/g,"$1"),H+=Ce}return H}function Z(O){return JSON.parse(F(O))}function te(O,H){if(!Array.isArray(O))throw new Error(`Expected array, but received: ${JSON.stringify(O)}.`);if(H!==void 0&&O.length!==H)throw new Error(`Expected array of length ${H}, but received: ${JSON.stringify(O)}.`);return O}function ye(O,H){if(!Array.isArray(O))throw new Error(`Expected array, but received: ${JSON.stringify(O)}.`);return O.map(H)}function Ye(O,H,ne){const ae=O.length;if(!Array.isArray(H)||H.length!==ae)throw new Error(`Expected length ${ae} array, but received: ${JSON.stringify(H)}.`);for(let Ce=0;Ce<ae;++Ce)O[Ce]=ne(H[Ce],Ce);return O}function Qe(O){if(typeof O!="object"||O==null||Array.isArray(O))throw new Error(`Expected JSON object, but received: ${JSON.stringify(O)}.`);return O}function We(O){const H=parseInt(O,10);if(!Number.isInteger(H))throw new Error(`Expected integer, but received: ${JSON.stringify(O)}.`);return H}function Cn(O){const H=We(O);if(H<=0)throw new Error(`Expected positive integer, but received: ${H}.`);return H}function Yt(O){const H=We(O);if(H<0)throw new Error(`Expected non-negative integer, but received: ${H}.`);return H}function Zn(O,H){const ne=H.get(O);if(ne===void 0)throw new Error(`Expected one of ${JSON.stringify(Array.from(H.keys()))}, but received: ${JSON.stringify(O)}.`);return ne}function p(O){if(typeof O!="string")throw new Error(`Expected string, but received: ${JSON.stringify(O)}.`);return O}function ns(O){if(O!==void 0)return p(O)}function W(O){if(O!==void 0)return We(O)}function Y(O){if(O!==void 0){if(typeof O=="boolean")return O;if(O==="true")return!0;if(O==="false")return!1;throw new Error(`Expected string or boolean but received: ${JSON.stringify(O)}`)}}function de(O,H){return O===void 0?H:O}function M(O,H,ne){const ae=Object.prototype.hasOwnProperty.call(O,H)?O[H]:void 0;try{return ne(ae)}catch(Ce){throw new Error(`Error parsing ${JSON.stringify(H)} property: ${Ce.message}`)}}function ue(O,H,ne,ae){return M(O,H,Ce=>Ce===void 0?ae:ne(Ce))}function se(O,H){Qe(O);const ne=new Map;for(const ae of Object.keys(O))try{ne.set(ae,H(O[ae]))}catch(Ce){throw new Error(`Error parsing value associated with key ${JSON.stringify(ae)}: ${Ce.message}`)}return ne}function he(O){if(typeof O!="number"||!Number.isFinite(O)||O<0||O>1)throw new Error(`Expected floating point number in [0,1], but received: ${JSON.stringify(O)}.`);return O}function Le(O){if(O==="")return{};if(O.startsWith("{"))return D(O);const H={},ne=O.split(/[&;]/);for(const ae of ne){const Ce=ae.match(/^([^=&;]+)=([^&;]*)$/);if(Ce===null)throw new Error(`Invalid query string part: ${JSON.stringify(ae)}.`);H[Ce[1]]=decodeURIComponent(Ce[2])}return H}function qe(O){if(O===void 0)return"";const H=Object.keys(O);return H.length===0?"":H.some(ne=>typeof O[ne]!="string")?JSON.stringify(O):H.map(ne=>`${encodeURIComponent(ne)}=${encodeURIComponent(O[ne])}`).join("&")}function Xe(O,H,ne=/^[a-zA-Z]/){if(typeof O=="string"&&O.match(ne)!==null){const ae=O.toUpperCase();if(Object.prototype.hasOwnProperty.call(H,ae))return H[ae]}throw new Error(`Invalid enum value: ${JSON.stringify(O)}.`)}function tt(O){return Ye(z.eR.create(),O,pe)}function nt(O){return Ye(z.eR.create(),O,be)}function ct(O){return Ye(z.eR.create(),O,Cn)}function Qt(O){if(!Array.isArray(O))throw new Error(`Expected array, received: ${JSON.stringify(O)}.`);for(const H of O)if(typeof H!="string")throw new Error(`Expected string, received: ${JSON.stringify(H)}.`);return O}function Vn(O){if(!Array.isArray(O))throw new Error(`Expected array, received: ${JSON.stringify(O)}.`);for(const H of O)if(!Number.isInteger(H))throw new Error(`Expected integer, received: ${JSON.stringify(H)}.`);return O}function qt(O){if(typeof O!="boolean")throw new Error(`Expected boolean, received: ${JSON.stringify(O)}`);return O}function is(O){for(const H in O)return O}function Et(O,H){if(O!==H)throw new Error(`Expected ${JSON.stringify(H)}, but received: ${JSON.stringify(O)}`);return H}function wi(O,H){if(O===void 0){const ne=new Array(H);return ne.fill(null),ne}return Ye(new Array(H),O,ne=>{if(ne!==null&&typeof ne!="string")throw new Error(`Expected string or null, but received: ${JSON.stringify(name)}`);return ne})}},147:(oe,Re,G)=>{G.d(Re,{Aw:()=>Oe,C:()=>Ge,DA:()=>pe,DI:()=>Te,D_:()=>A,LC:()=>Ze,Lk:()=>Ee,_U:()=>xt,ay:()=>$e,lw:()=>z,nx:()=>w,u6:()=>be,vo:()=>ze});/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function z(q,ie,I,re,B,J,U,N,D){for(let F=0;F<U;++F)for(let Z=0;Z<D;++Z){let te=0;for(let ye=0;ye<N;++ye)te+=I[F+re*ye]*B[ye+J*Z];q[F+ie*Z]=te}return q}function A(q,ie,I){for(let re=0;re<I;++re){const B=ie*re;q.fill(0,B,B+I),q[B+re]=1}return q}function pe(q,ie,I=ie){return A(new q(ie*I),ie,Math.min(ie,I))}function w(q,ie,I=!0){const re=ie.length,B=I?re+1:re,J=new q(B*(re+1));I&&(J[J.length-1]=1);for(let U=0;U<re;++U)J[(B+1)*U]=ie[U];return J}function be(q,ie,I=!0){const re=ie.length,B=I?re+1:re,J=pe(q,B,re+1);for(let U=0;U<re;++U)J[B*re+U]=ie[U];return J}function Ee(q,ie,I){for(let re=0;re<I;++re)for(let B=0;B<I;++B)if(q[re*ie+B]!==(re===B?1:0))return!1;return!0}function Ge(q,ie,I,re,B,J){for(let U=0;U<J;++U){const N=U*re,D=U*ie;for(let F=0;F<B;++F)q[D+F]=I[N+F]}return q}function Oe(q,ie,I,re){Ge(q,ie+1,I,re+1,re,re);for(let B=0;B<re;++B)q[(ie+1)*ie+B]=I[(re+1)*re+B];q[q.length-1]=1;for(let B=re;B<ie;++B)q[(ie+1)*B+B]=1;return q}let ge;function me(q,ie,I){let re=1;(ge===void 0||ge.length<I)&&(ge=new Uint32Array(I));for(let B=0;B<I;++B)ge[B]=B;for(let B=0;B<I;++B){const J=ie*B;let U=B;{let F=Math.abs(q[J+B]);for(let Z=B+1;Z<I;++Z){const te=Math.abs(q[J+Z]);te>F&&(F=te,U=Z)}}if(B!==U){re*=-1;for(let F=0;F<I;++F){const Z=ie*F,te=q[Z+B];q[Z+B]=q[Z+U],q[Z+U]=te}{const F=ge[B];ge[B]=ge[U],ge[U]=F}}const N=q[J+B],D=1/N;re*=N;for(let F=0;F<I;++F)q[ie*F+B]*=D;q[J+B]=D;for(let F=0;F<I;++F){if(F===B)continue;const Z=-q[ie*B+F];for(let te=0;te<I;++te){const ye=ie*te;q[ye+F]+=Z*q[ye+B]}q[ie*B+F]=Z*D}}for(let B=0;B<I;++B){let J=ge[B];for(;J!==B;){const U=ie*B,N=ie*J;for(let F=0;F<I;++F){const Z=U+F,te=N+F,ye=q[Z];q[Z]=q[te],q[te]=ye}const D=ge[B]=ge[J];ge[J]=J,J=D}}return re}function Te(q,ie,I,re,B){return Ge(q,ie,I,re,B,B),me(q,ie,B)}function Ze(q,ie,I,re,B,J){for(let U=0;U<J;++U){const N=ie*U,D=re*U;for(let F=0;F<B;++F)if(q[N+F]!==I[D+F])return!1}return!0}function Pt(q,ie,I,re,B,J){for(let U=0;U<B;++U)for(let N=0;N<J;++N)q[N+U*ie]=I[U+N*re];return q}function ze(q,ie,I,re,B){for(let J=0;J<B;++J){let U=ie[I*B+J];for(let N=0;N<B;++N)U+=ie[I*N+J]*re[N];q[J]=U}return q}function xt(q,ie,I,re,B){for(let J=0;J<B;++J){let U=0;for(let N=0;N<B;++N)U+=ie[I*N+J]*re[N];q[J]=U}return q}function $e(q,ie,I,re,B,J){const U=B.length;for(let N=0;N<U;++N){const D=B[N];for(let F=0;F<J;++F)q[F*ie+N]=I[F*re+D]}return q}function Ve(q,ie,I,re,B,J){const U=B.length;for(let N=0;N<U;++N){const D=B[N];for(let F=0;F<J;++F)q[N*ie+F]=I[D*re+F]}return q}},4038:(oe,Re,G)=>{G.d(Re,{$$:()=>w,HN:()=>z,IY:()=>pe});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class z{constructor(){this.handlers=new Set,this.count=0;const Ee=this;this.dispatch=function(){++Ee.count,Ee.handlers.forEach(Ge=>{Ge.apply(this,arguments)})}}add(Ee){return this.handlers.add(Ee),()=>this.remove(Ee)}remove(Ee){return this.handlers.delete(Ee)}dispose(){this.handlers=void 0}}function A(be,...Ee){be();for(let Ge=0,Oe=Ee.length;Ge<Oe;++Ge)Ee[Ge].add(be);return()=>{for(let Ge=0,Oe=Ee.length;Ge<Oe;++Ge)Ee[Ge].remove(be)}}class pe extends z{}const w={count:0,add(be){return()=>{}},remove(be){return!1}}},4711:(oe,Re,G)=>{var z=G(4037),A=G(3206),pe=G(8103),w=G(3038);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function be(i){return("0"+i.toString(16)).slice(-2)}function Ee(i){return Array.prototype.map.call(i,be).join("")}function Ge(i){if(!/^(?:[0-9a-fA-F]{2})*$/.test(i))throw new Error("Invalid hex-encoded string");const e=i.length/2,t=new Uint8Array(e);for(let n=0;n<e;++n)t[n]=parseInt(i.substr(n*2,2),16);return t}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Oe(i){const e=/^rgba\(([0-9]+), ([0-9]+), ([0-9]+), (0(?:\.[0-9]+)?)\)$/;{const n=i.match(e);if(n!==null)return[parseInt(n[1],10),parseInt(n[2],10),parseInt(n[3],10),parseFloat(n[4])]}const t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/;{const n=i.match(t);if(n!==null)return[parseInt(n[1],16),parseInt(n[2],16),parseInt(n[3],16),1]}throw new Error(`Invalid serialized color: ${JSON.stringify(i)}.`)}function ge(i){try{if(typeof i!="string")throw new Error(`Expected string, but received ${JSON.stringify(i)}.`);const e=document.createElement("canvas").getContext("2d");e.fillStyle=i;const t=Oe(e.fillStyle);return w.ln.fromValues(t[0]/255,t[1]/255,t[2]/255,t[3])}catch(e){throw new Error(`Failed to parse color specification: ${e.message}`)}}function me(i){return ge(i).subarray(0,3)}function Te(i){const e=i[3]===void 0?3:4;let t=0;for(let n=0;n<e;n++)t=(t<<8>>>0)+Math.min(255,Math.max(0,Math.round(i[e-1-n]*255)));return t}function Ze(i){return w.eR.fromValues((i>>>0&255)/255,(i>>>8&255)/255,(i>>>16&255)/255)}function Pt(i){return w.ln.fromValues((i>>>0&255)/255,(i>>>8&255)/255,(i>>>16&255)/255,(i>>>24&255)/255)}function ze(i){if(i[3]===void 0||i[3]===1){let t="#";for(let n=0;n<3;++n)t+=be(Math.min(255,Math.max(0,Math.round(i[n]*255))));return t}let e="rgba(";for(let t=0;t<3;++t)t!==0&&(e+=", "),e+=Math.min(255,Math.max(0,Math.round(i[t]*255)));return e+=`, ${(0,pe.K)(i[3])})`,e}function xt(i){return i<=.03928?i/12.92:((i+.055)/1.055)**2.4}function $e(i){const[e,t,n]=i;return .2126*xt(e)+.7152*xt(t)+.0722*xt(n)}function Ve(i){return $e(i)<=.179}class q extends A.B0{constructor(e){super(w.eR.clone(e)),this.defaultValue=e}toString(){return ze(this.value)}toJSON(){if(!w.eR.equals(this.value,this.defaultValue))return ze(this.value)}reset(){this.value=w.eR.clone(this.defaultValue)}restoreState(e){if(e===void 0){this.reset();return}const{value:t}=this,n=me(e);w.eR.equals(t,n)||(this.value=n)}}class ie extends A.B0{constructor(){super(void 0)}toJSON(){const{value:e}=this;if(e!==void 0)return ze(e)}reset(){this.value=void 0}restoreState(e){if(e===void 0){this.reset();return}const{value:t}=this,n=me(e);(t===void 0||!w.eR.equals(t,n))&&(this.value=n)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var I=(i=>(i[i.UINT8=0]="UINT8",i[i.INT8=1]="INT8",i[i.UINT16=2]="UINT16",i[i.INT16=3]="INT16",i[i.UINT32=4]="UINT32",i[i.INT32=5]="INT32",i[i.UINT64=6]="UINT64",i[i.FLOAT32=7]="FLOAT32",i))(I||{});const re={0:!1,1:!0,2:!1,3:!0,4:!1,5:!0,6:!1,7:void 0},B={0:1,1:1,2:2,3:2,4:4,5:4,6:8,7:4},J={0:Uint8Array,1:Int8Array,2:Uint16Array,3:Int16Array,4:Uint32Array,5:Int32Array,6:Uint32Array,7:Float32Array},U={0:1,1:1,2:1,3:1,4:1,5:1,6:2,7:1};function N(i,e,t=0,n=e.byteLength){const s=B[i],r=U[i];return new J[i](e,t,n/s*r)}var D=G(2596);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var F=(i=>(i[i.LITTLE=0]="LITTLE",i[i.BIG=1]="BIG",i))(F||{});function Z(){const i=Uint16Array.of(4386);return new Uint8Array(i.buffer)[0]===17?1:0}const te=Z();function ye(i){const e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0,n=e.length;t<n;t+=2){const s=e[t];e[t]=e[t+1],e[t+1]=s}}function Ye(i){const e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0,n=e.length;t<n;t+=4){let s=e[t];e[t]=e[t+3],e[t+3]=s,s=e[t+1],e[t+1]=e[t+2],e[t+2]=s}}function Qe(i){const e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0,n=e.length;t<n;t+=8){let s=e[t];e[t]=e[t+7],e[t+7]=s,s=e[t+1],e[t+1]=e[t+6],e[t+6]=s,s=e[t+2],e[t+2]=e[t+5],e[t+5]=s,s=e[t+3],e[t+3]=e[t+4],e[t+4]=s}}function We(i,e,t=te){e!==t&&ye(i)}function Cn(i,e,t=te){e!==t&&Ye(i)}function Yt(i,e,t=te){e!==t&&Qe(i)}function Zn(i,e,t,n=te){if(!(e===n||t===1))switch(t){case 2:ye(i);break;case 4:Ye(i);break;case 8:Qe(i);break}}var p=G(7900);/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ns=2**-1074,W=new Float64Array(1),Y=new Uint32Array(W.buffer);function de(i,e){if(Number.isNaN(i)||Number.isNaN(e))return NaN;if(i===e)return e;if(i===0)return e<0?-ns:ns;W[0]=i;const t=te===F.LITTLE?0:1,n=1-t;return e>i==i>0?Y[t]===4294967295?(Y[t]=0,Y[n]+=1):Y[t]+=1:Y[t]===0?(Y[t]=4294967295,Y[n]-=1):Y[t]-=1,W[0]}var M=G(8796);/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ue={[I.UINT8]:[0,255],[I.INT8]:[-128,127],[I.UINT16]:[0,65535],[I.INT16]:[-32768,32767],[I.UINT32]:[0,4294967295],[I.INT32]:[-2147483648,2147483647],[I.UINT64]:[M.R.ZERO,new M.R(4294967295,4294967295)],[I.FLOAT32]:[0,1]};function se(i,e){if(typeof e=="number"){const o=i[0],a=i[1];return(e-o)/(a-o)}const t=i[0],n=i[1];let s;M.R.compare(e,t)<0?s=-M.R.subtract(ct,t,e).toNumber():s=M.R.subtract(ct,e,t).toNumber();let r=M.R.absDifference(ct,n,t).toNumber();return M.R.compare(t,n)>0&&(r*=-1),s/r}function he(i,e,t){if(typeof i[0]=="number"){const a=i[0],l=i[1];let c=a*(1-t)+l*t;if(e!==I.FLOAT32){const d=ue[e];c=Math.round(c),c=Math.max(d[0],c),c=Math.min(d[1],c)}return c}let n=i[0],s=i[1];M.R.compare(n,s)>0&&([n,s]=[s,n],t=1-t);const r=M.R.subtract(ct,s,n).toNumber(),o=new M.R;return t<=0?(ct.setFromNumber(r*-t),M.R.subtract(o,n,M.R.min(ct,n))):t>=1?(ct.setFromNumber(r*(t-1)),M.R.add(o,s,ct),M.R.less(o,s)&&(o.low=o.high=4294967295)):(ct.setFromNumber(r*t),M.R.add(o,n,ct),M.R.less(o,n)&&(o.low=o.high=4294967295)),o}function Le(i,e){return typeof e=="number"?Math.min(Math.max(i[0],e),i[1]):M.R.min(M.R.max(i[0],e),i[1])}function qe(i,e){return[Le(i,e[0]),Le(i,e[1])]}function Xe(i){if(nt(i[0],i[1])<=0)return i;throw new Error(`Invalid interval: [${i[0]}, ${i[1]}]`)}function tt(i){return nt(i[0],i[1])<=0?i:[i[1],i[0]]}function nt(i,e){return typeof i=="number"?i-e:M.R.compare(i,e)}const ct=new M.R,Qt=new M.R;function Vn(i,e){return typeof e=="number"?Math.abs(e-i[0])<Math.abs(e-i[1])?0:1:M.R.less(M.R.absDifference(ct,i[0],e),M.R.absDifference(Qt,i[1],e))?0:1}function qt(i,e){let t;switch(typeof e!="string"?t=""+e:t=e,i){case I.UINT64:return M.R.parseString(t);case I.FLOAT32:{const n=parseFloat(t);if(!Number.isFinite(n))throw new Error(`Invalid float32 value: ${JSON.stringify(t)}`);return n}default:{const n=parseInt(t),s=ue[i];if(!Number.isInteger(n)||n<s[0]||n>s[1])throw new Error(`Invalid ${I[i].toLowerCase()} value: ${JSON.stringify(t)}`);return n}}}function is(i){if(typeof i=="number")return i;if(typeof i=="string"){const e=new M.R,t=Number(i);if(e.tryParseString(i))return t.toString()===e.toString()?t:e;if(!Number.isFinite(t))throw new Error(`Invalid value: ${JSON.stringify(i)}`);return t}throw new Error(`Invalid value: ${JSON.stringify(i)}`)}function Et(i,e){return(0,p.Xu)(new Array(2),i,t=>qt(e,t))}function wi(i){return(0,p.Xu)(new Array(2),i,e=>is(e))}function O(i,e,t){return i===I.UINT64?M.R.equal(e[0],t[0])&&M.R.equal(e[1],t[1]):e[0]===t[0]&&e[1]===t[1]}function H(i,e,t=ue[e]){if(!O(e,i,t))return e===I.UINT64?[i[0].toString(),i[1].toString()]:i}function ne(i,e,t){switch(i){case I.FLOAT32:return de(e,t*(1/0));case I.UINT64:{const n=e;return t===-1?n.low===0&&n.high===0?n:M.R.decrement(new M.R,n):n.low===4294967295&&n.high===4294967295?n:M.R.increment(new M.R,n)}default:{const n=ue[i];return Math.max(n[0],Math.min(n[1],e+t))}}}function ae(i,e){switch(i){case I.FLOAT32:return 0;case I.UINT64:return .5/M.R.absDifference(ct,e[0],e[1]).toNumber();default:return .5/Math.abs(e[0]-e[1])}}function Ce(i,e){switch(i){case I.FLOAT32:return 1;case I.UINT64:{const t=M.R.absDifference(ct,e[0],e[1]).toNumber();return t/(t+1)}default:{const t=Math.abs(e[0]-e[1]);return t/(t+1)}}}function De(i,e){if(i===void 0)return ue[e];let[t,n]=i;if(e===I.UINT64)return typeof t=="number"&&(t=M.R.fromNumber(t)),typeof n=="number"&&(n=M.R.fromNumber(n)),[t,n];if(typeof t!="number"&&(t=t.toNumber()),typeof n!="number"&&(n=n.toNumber()),e!==I.FLOAT32){t=Math.round(t),n=Math.round(n);const s=ue[e];Number.isFinite(t)?t=Math.min(Math.max(s[0],t),s[1]):t=s[0],Number.isFinite(n)?n=Math.min(Math.max(s[0],n),s[1]):n=s[1]}return[t,n]}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function it(i=128){const e=Math.ceil(i/32),t=new Uint32Array(e);crypto.getRandomValues(t);let n="";for(let s=0;s<e;++s)n+=("00000000"+t[s].toString(16)).slice(-8);return n}function ot(i){const e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),t=65536;for(let n=0,s=e.length;n<s;n+=t)crypto.getRandomValues(e.subarray(n,Math.min(s,n+t)));return i}function _t(){const i=new Uint32Array(1);return crypto.getRandomValues(i),i[0]}var j=G(4038);/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ei extends D.O8{constructor(e){super(),this.id=e,this.changed=new j.IY}}var Je=(i=>(i[i.POINT=0]="POINT",i[i.LINE=1]="LINE",i[i.AXIS_ALIGNED_BOUNDING_BOX=2]="AXIS_ALIGNED_BOUNDING_BOX",i[i.ELLIPSOID=3]="ELLIPSOID",i))(Je||{});const _n=[0,1,2,3],bl={float32:I.FLOAT32,uint32:I.UINT32,int32:I.INT32,uint16:I.UINT16,int16:I.INT16,uint8:I.UINT8,int8:I.INT8,rgb:void 0,rgba:void 0},ti={rgb:{serializedBytes(){return 3},alignment(){return 1},serializeCode(i,e){return`dv.setUint16(${e}, ${i}, true);dv.setUint8(${e} + 2, ${i} >>> 16);`},deserializeCode(i,e){return`${i} = dv.getUint16(${e}, true) | (dv.getUint8(${e} + 2) << 16);`},deserializeJson(i){return Te(me(i))},serializeJson(i){return ze(Ze(i))}},rgba:{serializedBytes(){return 4},alignment(){return 1},serializeCode(i,e){return`dv.setUint32(${e}, ${i}, true);`},deserializeCode(i,e){return`${i} = dv.getUint32(${e}, true);`},deserializeJson(i){return Te(ge(i))},serializeJson(i){return ze(Pt(i))}},float32:{serializedBytes(){return 4},alignment(){return 4},serializeCode(i,e){return`dv.setFloat32(${e}, ${i}, isLittleEndian);`},deserializeCode(i,e){return`${i} = dv.getFloat32(${e}, isLittleEndian);`},deserializeJson(i){return(0,p._D)(i)},serializeJson(i){return i}},uint32:{serializedBytes(){return 4},alignment(){return 4},serializeCode(i,e){return`dv.setUint32(${e}, ${i}, isLittleEndian);`},deserializeCode(i,e){return`${i} = dv.getUint32(${e}, isLittleEndian);`},deserializeJson(i){return(0,p.bX)(i)},serializeJson(i){return i}},int32:{serializedBytes(){return 4},alignment(){return 4},serializeCode(i,e){return`dv.setInt32(${e}, ${i}, isLittleEndian);`},deserializeCode(i,e){return`${i} = dv.getInt32(${e}, isLittleEndian);`},deserializeJson(i){return(0,p.bX)(i)},serializeJson(i){return i}},uint16:{serializedBytes(){return 2},alignment(){return 2},serializeCode(i,e){return`dv.setUint16(${e}, ${i}, isLittleEndian);`},deserializeCode(i,e){return`${i} = dv.getUint16(${e}, isLittleEndian);`},deserializeJson(i){return(0,p.bX)(i)},serializeJson(i){return i}},int16:{serializedBytes(){return 2},alignment(){return 2},serializeCode(i,e){return`dv.setInt16(${e}, ${i}, isLittleEndian);`},deserializeCode(i,e){return`${i} = dv.getInt16(${e}, isLittleEndian);`},deserializeJson(i){return(0,p.bX)(i)},serializeJson(i){return i}},uint8:{serializedBytes(){return 1},alignment(){return 1},serializeCode(i,e){return`dv.setUint8(${e}, ${i});`},deserializeCode(i,e){return`${i} = dv.getUint8(${e});`},deserializeJson(i){return(0,p.bX)(i)},serializeJson(i){return i}},int8:{serializedBytes(){return 2},alignment(){return 1},serializeCode(i,e){return`dv.setInt8(${e}, ${i});`},deserializeCode(i,e){return`${i} = dv.getInt8(${e});`},deserializeJson(i){return(0,p.bX)(i)},serializeJson(i){return i}}},Ob=255;function vh(i,e,t){let n=0;const s=t.length,r=new Array(s),o=[];for(let h=0;h<s;++h)r[h]=h;const a=h=>ti[t[h].type].alignment(i);r.sort((h,f)=>a(f)-a(h));let l=0;const c=new Array(s);let d=e;const u=()=>{d+=(4-d%4)%4,n+=d,o[l]=d,d=0,++l};for(let h=0;h<s;++h){const f=r[h],m=t[f],g=ti[m.type],v=g.serializedBytes(i),y=g.alignment(i),S=(y-d%y)%y,b=d+S+v;b+(4-b%4)%4<=Ob?d+=S:u(),c[f]={offset:d,group:l},d+=v}return u(),{serializedBytes:n,offsets:c,propertyGroupBytes:o}}class yh{constructor(e,t,n){if(this.rank=e,this.firstGroupInitialOffset=t,this.propertySpecs=n,n.length===0){this.serializedBytes=t,this.serialize=this.deserialize=()=>{},this.propertyGroupBytes=[t];return}const{serializedBytes:s,offsets:r,propertyGroupBytes:o}=vh(e,t,n);this.propertyGroupBytes=o;let a="let groupOffset0 = offset;";for(let u=1;u<o.length;++u)a+=`let groupOffset${u} = groupOffset${u-1} + ${o[u-1]}*annotationCount;`;for(let u=0;u<o.length;++u)a+=`groupOffset${u} += ${o[u]}*annotationIndex;`;let l=a,c=a;const d=n.length;for(let u=0;u<d;++u){const{group:h,offset:f}=r[u],m=n[u],g=ti[m.type],v=`properties[${u}]`,y=`groupOffset${h} + ${f}`;l+=g.serializeCode(v,y,e),c+=g.deserializeCode(v,y,e)}this.serializedBytes=s,this.serialize=new Function("dv","offset","annotationIndex","annotationCount","isLittleEndian","properties",l),this.deserialize=new Function("dv","offset","annotationIndex","annotationCount","isLittleEndian","properties",c)}}function wl(i,e){const t=[];for(const n of _n){const s=Bt[n];t[n]=new yh(i,s.serializedBytes(i),e)}return t}function Sh(i,e){const t=i.type==="float32"?e.toPrecision(6):e.toString(),{enumValues:n,enumLabels:s}=i;if(n!==void 0){const r=n.indexOf(e);if(r!==-1)return`${s[r]} (${t})`}return t}function Vb(i,e){switch(i.type){case"rgb":return ze(Ze(e));case"rgba":return ze(Pt(e));default:return Sh(i,e)}}function _b(i){const e=(0,p.zr)(i);if(e.match(/^[a-z][a-zA-Z0-9_]*$/)===null)throw new Error(`Invalid property identifier: ${JSON.stringify(i)}`);return e}function Bb(i){if((0,p.zr)(i),!Object.prototype.hasOwnProperty.call(ti,i))throw new Error("Unsupported property type: $JSON.stringify(obj)}");return i}function Fb(i){const e=new Set;for(const t of i){if(e.has(t.identifier))throw new Error(`Duplicate property identifier: ${t.identifier}`);e.add(t.identifier)}}function Ub(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"id",_b),t=(0,p.cQ)(i,"type",Bb),n=(0,p.MM)(i,"description",p.zr),s=(0,p.MM)(i,"default",a=>ti[t].deserializeJson(a),0);let r,o;switch(t){case"rgb":case"rgba":break;default:{const a=I[t.toUpperCase()];r=(0,p.MM)(i,"enum_values",l=>(0,p.$v)(l,c=>qt(a,c))),r!==void 0&&(o=(0,p.cQ)(i,"enum_labels",l=>(0,p.Xu)(new Array(r.length),l,p.zr)))}}return{type:t,identifier:e,description:n,default:s,enumValues:r,enumLabels:o}}function $b(i){const e=i.default;return{id:i.identifier,description:i.description,type:i.type,default:e===0?void 0:ti[i.type].serializeJson(e)}}function Gb(i){if(!(i===void 0||i.length===0))return i.map($b)}function bh(i){if(i===void 0)return[];const e=(0,p.$v)(i,Ub);return Fb(e),e}function Cl(i,e,t,n,s){for(let r=0;r<n;++r)i.setFloat32(e,s[r],t),e+=4;return e}function xl(i,e,t,n,s,r){return e=Cl(i,e,t,n,s),e=Cl(i,e,t,n,r),e}function El(i,e,t,n,s){for(let r=0;r<n;++r)s[r]=i.getFloat32(e,t),e+=4;return e}function Tl(i,e,t,n,s,r){return e=El(i,e,t,n,s),e=El(i,e,t,n,r),e}const Bt={1:{icon:"\uA579",description:"Line",toJSON(i){return{pointA:Array.from(i.pointA),pointB:Array.from(i.pointB)}},restoreState(i,e,t){i.pointA=(0,p.cQ)(e,"pointA",n=>(0,p.Xu)(new Float32Array(t),n,p.zo)),i.pointB=(0,p.cQ)(e,"pointB",n=>(0,p.Xu)(new Float32Array(t),n,p.zo))},serializedBytes(i){return 2*4*i},serialize(i,e,t,n,s){xl(i,e,t,n,s.pointA,s.pointB)},deserialize:(i,e,t,n,s)=>{const r=new Float32Array(n),o=new Float32Array(n);return Tl(i,e,t,n,r,o),{type:1,pointA:r,pointB:o,id:s,properties:[]}},visitGeometry(i,e){e(i.pointA,!1),e(i.pointB,!1)}},0:{icon:"\u26AC",description:"Point",toJSON:i=>({point:Array.from(i.point)}),restoreState:(i,e,t)=>{i.point=(0,p.cQ)(e,"point",n=>(0,p.Xu)(new Float32Array(t),n,p.zo))},serializedBytes:i=>i*4,serialize:(i,e,t,n,s)=>{Cl(i,e,t,n,s.point)},deserialize:(i,e,t,n,s)=>{const r=new Float32Array(n);return El(i,e,t,n,r),{type:0,point:r,id:s,properties:[]}},visitGeometry(i,e){e(i.point,!1)}},2:{icon:"\u2751",description:"Bounding Box",toJSON:i=>({pointA:Array.from(i.pointA),pointB:Array.from(i.pointB)}),restoreState:(i,e,t)=>{i.pointA=(0,p.cQ)(e,"pointA",n=>(0,p.Xu)(new Float32Array(t),n,p.zo)),i.pointB=(0,p.cQ)(e,"pointB",n=>(0,p.Xu)(new Float32Array(t),n,p.zo))},serializedBytes:i=>2*4*i,serialize(i,e,t,n,s){xl(i,e,t,n,s.pointA,s.pointB)},deserialize:(i,e,t,n,s)=>{const r=new Float32Array(n),o=new Float32Array(n);return Tl(i,e,t,n,r,o),{type:2,pointA:r,pointB:o,id:s,properties:[]}},visitGeometry(i,e){e(i.pointA,!1),e(i.pointB,!1)}},3:{icon:"\u25CE",description:"Ellipsoid",toJSON:i=>({center:Array.from(i.center),radii:Array.from(i.radii)}),restoreState:(i,e,t)=>{i.center=(0,p.cQ)(e,"center",n=>(0,p.Xu)(new Float32Array(t),n,p.zo)),i.radii=(0,p.cQ)(e,"radii",n=>(0,p.Xu)(new Float32Array(t),n,p.Zw))},serializedBytes:i=>2*4*i,serialize(i,e,t,n,s){xl(i,e,t,n,s.center,s.radii)},deserialize:(i,e,t,n,s)=>{const r=new Float32Array(n),o=new Float32Array(n);return Tl(i,e,t,n,r,o),{type:3,center:r,radii:o,id:s,properties:[]}},visitGeometry(i,e){e(i.center,!1),e(i.radii,!0)}}};function Dl(i,e){const t=Bt[i.type].toJSON(i,e.rank);t.type=Je[i.type].toLowerCase(),t.id=i.id,t.description=i.description||void 0;const{relatedSegments:n}=i;if(n?.some(s=>s.length!==0)&&(t.segments=n.map(s=>s.map(r=>r.toString()))),e.properties.length!==0){const s=e.properties;t.props=i.properties.map((r,o)=>ti[s[o].type].serializeJson(r))}return t}function zb(i,e,t=!1){(0,p.Rf)(i);const n=(0,p.cQ)(i,"type",l=>(0,p.sl)(l,Je)),s=(0,p.cQ)(i,"id",t?p.z$:p.zr)||Il(),r=(0,p.cQ)(i,"segments",l=>{if(l===void 0)return e.relationships.map(()=>[]);const c=(0,p.J6)(l);return c.length===0?e.relationships.map(()=>[]):e.relationships.length===1&&!Array.isArray(c[0])?[(0,p.$v)(c,d=>M.R.parseString(d))]:(0,p.$v)((0,p.J6)(l,e.relationships.length),d=>(0,p.$v)(d,u=>M.R.parseString(u)))}),o=(0,p.cQ)(i,"props",l=>{const c=e.properties;return l===void 0?c.map(d=>d.default):(0,p.$v)((0,p.J6)(l,e.properties.length),(d,u)=>ti[c[u].type].deserializeJson(d))}),a={id:s,description:(0,p.cQ)(i,"description",p.z$),relatedSegments:r,properties:o,type:n};return Bt[n].restoreState(a,i,e.rank),a}class ss extends D.O8{constructor(e,t=[],n=[]){super(),this.relationships=t,this.properties=n,this.annotationMap=new Map,this.changed=new j.IY,this.readonly=!1,this.childAdded=new j.HN,this.childUpdated=new j.HN,this.childCommitted=new j.HN,this.childDeleted=new j.HN,this.pending=new Set,this.references=new Map,this.rank_=e,this.annotationPropertySerializers=wl(e,n)}get rank(){return this.rank_}hasNonSerializedProperties(){return!0}add(e,t=!0){if(this.ensureUpdated(),!e.id)e.id=Il();else if(this.annotationMap.has(e.id))throw new Error(`Annotation id already exists: ${JSON.stringify(e.id)}.`);return this.annotationMap.set(e.id,e),t||this.pending.add(e.id),this.changed.dispatch(),this.childAdded.dispatch(e),t&&this.childCommitted.dispatch(e.id),this.getReference(e.id)}commit(e){this.ensureUpdated();const t=e.id;this.pending.delete(t),this.changed.dispatch(),this.childCommitted.dispatch(t)}update(e,t){if(this.ensureUpdated(),e.value===null)throw new Error("Annotation already deleted.");e.value=t,this.annotationMap.set(t.id,t),e.changed.dispatch(),this.changed.dispatch(),this.childUpdated.dispatch(t)}[Symbol.iterator](){return this.ensureUpdated(),this.annotationMap.values()}get(e){return this.ensureUpdated(),this.annotationMap.get(e)}delete(e){e.value!==null&&(e.value=null,this.annotationMap.delete(e.id),this.pending.delete(e.id),e.changed.dispatch(),this.changed.dispatch(),this.childDeleted.dispatch(e.id))}getReference(e){let t=this.references.get(e);return t!==void 0?t.addRef():(t=new ei(e),t.value=this.annotationMap.get(e)||null,this.references.set(e,t),t.registerDisposer(()=>{this.references.delete(e)}),t)}ensureUpdated(){}toJSON(){this.ensureUpdated();const e=[],{pending:t}=this;for(const n of this)t.has(n.id)||e.push(Dl(n,this));return e}clear(){this.annotationMap.clear(),this.pending.clear(),this.changed.dispatch()}restoreState(e){this.ensureUpdated();const{annotationMap:t}=this;t.clear(),this.pending.clear(),e!==void 0&&(0,p.$v)(e,n=>{const s=zb(n,this);t.set(s.id,s)});for(const n of this.references.values()){const{id:s}=n,r=t.get(s);n.value=r||null,n.changed.dispatch()}this.changed.dispatch()}reset(){this.clear()}}class wh extends ss{constructor(e,t,n){super(e.value.sourceRank,n,t),this.watchableTransform=e,this.curCoordinateTransform=e.value,this.registerDisposer(e.changed.add(()=>this.ensureUpdated()))}get rank(){return this.ensureUpdated(),this.rank_}ensureUpdated(){const e=this.watchableTransform.value,{curCoordinateTransform:t}=this;if(e===t)return;this.curCoordinateTransform=e;const n=e.sourceRank,s=t.sourceRank;if(s===n&&(t.inputSpace===e.inputSpace||(0,z.r1)(t.inputSpace.ids.slice(0,n),e.inputSpace.ids.slice(0,n))))return;const{ids:r}=e.inputSpace,o=t.inputSpace.ids,a=[];for(let c=0;c<n;++c){let d=o.indexOf(r[c]);d>=s&&(d=-1),a.push(d)}const l=c=>{const d=new Float32Array(n);for(let u=0;u<n;++u){const h=a[u];d[u]=h===-1?0:c[u]}return d};for(const c of this.annotationMap.values())switch(c.type){case 0:c.point=l(c.point);break;case 1:case 2:c.pointA=l(c.pointA),c.pointB=l(c.pointB);break;case 3:c.center=l(c.center),c.radii=l(c.radii);break}this.rank_!==n&&(this.rank_=n,this.annotationPropertySerializers=wl(this.rank_,this.properties)),this.changed.dispatch()}}const Wb="Data Bounds";function Il(){return it(160)}function Hb(i){return{type:2,id:"data-bounds",description:Wb,pointA:new Float32Array(i.lowerBounds),pointB:new Float32Array(i.upperBounds),properties:[]}}function cn(i){const e=new ss(i.lowerBounds.length);return e.readonly=!0,e.add(Hb(i)),e}function Jb(i,e){let t=0;const n=[];for(const c of _n){const u=e[c].serializedBytes;n[c]=t;const f=i[c].length;t+=u*f}const s=[],r=[],o=new ArrayBuffer(t),a=new DataView(o),l=te===F.LITTLE;for(const c of _n){const d=e[c],{rank:u}=d,h=d.serialize,f=i[c];s[c]=f.map(S=>S.id),r[c]=new Map(f.map((S,x)=>[S.id,x]));const g=Bt[c].serialize,v=n[c],y=d.propertyGroupBytes[0];for(let S=0,x=f.length;S<x;++S){const b=f[S];g(a,v+S*y,l,u,b),h(a,v,S,x,l,b.properties)}}return{data:new Uint8Array(o),typeToIds:s,typeToOffset:n,typeToIdMaps:r}}class jb{constructor(e){this.propertySerializers=e,this.annotations=[[],[],[],[]]}add(e){this.annotations[e.type].push(e)}serialize(){return Jb(this.annotations,this.propertySerializers)}}function Ch(i){if(i==null)return i;const{relatedSegments:e}=i;if(e!==void 0)for(let t=0,n=e.length;t<n;++t){const s=e[t];s!==void 0&&(e[t]=s.map(r=>new M.R(r.low,r.high)))}return i}var we=G(147);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const so=[{prefix:"Y",exponent:24,longPrefix:"yotta"},{prefix:"Z",exponent:21,longPrefix:"zetta"},{prefix:"E",exponent:18,longPrefix:"exa"},{prefix:"P",exponent:15,longPrefix:"peta"},{prefix:"T",exponent:12,longPrefix:"tera"},{prefix:"G",exponent:9,longPrefix:"giga"},{prefix:"M",exponent:6,longPrefix:"mega"},{prefix:"k",exponent:3,longPrefix:"kilo"},{prefix:"",exponent:0,longPrefix:""},{prefix:"m",exponent:-3,longPrefix:"milli"},{prefix:"\xB5",exponent:-6,longPrefix:"micro"},{prefix:"n",exponent:-9,longPrefix:"nano"},{prefix:"p",exponent:-12,longPrefix:"pico"},{prefix:"f",exponent:-15,longPrefix:"femto"},{prefix:"a",exponent:-18,longPrefix:"atto"},{prefix:"z",exponent:-21,longPrefix:"zepto"},{prefix:"y",exponent:-24,longPrefix:"yocto"}],Rl=[...so,{prefix:"h",exponent:2,longPrefix:"hecto"},{prefix:"da",exponent:1,longPrefix:"deca"},{prefix:"d",exponent:-1,longPrefix:"deci"},{prefix:"c",exponent:-2,longPrefix:"centi"}],Yb=[{prefix:"u",exponent:-6},...Rl],Xs=new Map;Xs.set("",{unit:"",exponent:0});const Qb=new Map;for(const{prefix:i,exponent:e}of Yb){Qb.set(e,i);for(const t of["m","s","Hz","rad/s"])Xs.set(`${i}${t}`,{unit:t,exponent:e})}function xh(i){const e=Math.log10(i),t=so.length,n=(0,z.lX)(0,t,s=>so[s].exponent<=e);return so[Math.min(n,t-1)]}function Eh(i,e,t={}){const{precision:n=6,elide1:s=!0}=t;let r=i,o="";if(e!==""){const l=xh(i);o=l.prefix,r=kl(i,-l.exponent)}if(s&&r===1)return{scale:"",unit:e,prefix:o};let a;if(n!==0){r<1||r>=1e3?a=r.toPrecision(n):a=r.toFixed(n);const l=a.indexOf("e");let c,d;l!==-1?(c=a.substring(0,l),d=a.substring(l)):(c=a,d="");const u=c.match(/.*\.(?:[0-9]*[1-9])?(0+)$/);u!==null&&(c=c.substring(0,c.length-u[1].length),c.endsWith(".")&&(c=c.substring(0,c.length-1)),a=c+d)}else a=r.toString();return{scale:a,unit:e,prefix:o}}function Ci(i,e,t){const{scale:n,unit:s,prefix:r}=Eh(i,e,t);return`${n}${r}${s}`}function Zs(i){if(i==="")return{scale:1,unit:""};const e=i.match(/^((?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)?([µa-zA-Z]+)?$/);if(e===null)return;const t=e[1];let n=t===void 0?1:Number(t);if(Number.isNaN(n))return;let s="";if(e[2]!==void 0){const r=Xs.get(e[2]);if(r===void 0)return;s=r.unit,r.exponent>0?n*=10**r.exponent:n/=10**-r.exponent}if(!(n<=0||!Number.isFinite(n)))return{scale:n,unit:s}}function Th(i){const e=Xs.get(i);if(e===void 0)throw new Error(`Invalid unit: ${JSON.stringify(i)}`);return e}function kl(i,e){return e>=0?i*10**e:i/10**-e}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ZV(i,e){const t=i.length;for(let n=0;n<t;++n)if(i[n]!==e[n])return!1;return!0}function Ll(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=e[s]+t[s];return i}function Pl(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=e[s]-t[s];return i}function e_(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=e[s]*t[s];return i}function t_(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=e[s]/t[s];return i}function qb(i,e,t,n){const s=i.length;for(let r=0;r<s;++r)i[r]=e[r]+t[r]*n;return i}function Kb(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=e[s]*t;return i}function Al(i){let e=1;for(let t=0,n=i.length;t<n;++t)e*=i[t];return e}function Xb(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=Math.min(e[s],t[s]);return i}function n_(i,e,t){const n=i.length;for(let s=0;s<n;++s)i[s]=Math.max(e[s],t[s]);return i}const rs=new Float32Array(0),Dh=new Float64Array(0),i_=Float64Array.of(1,1,1);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Zb=0;function os(){return++Zb}function ew(i,e){return(0,z.r1)(i.lowerBounds,e.lowerBounds)&&(0,z.r1)(i.upperBounds,e.upperBounds)}function tw(i,e){return i===void 0?e===void 0:e===void 0?!1:i.explicit===e.explicit&&(0,z.r1)(i.coordinates,e.coordinates)&&(0,z.r1)(i.labels,e.labels)}function nw(i,e){const t=new Map;for(let n=0,s=i.length;n<s;++n)t.set(i[n],e[n]);return i=Array.from(t.keys()),i.sort((n,s)=>n-s),e=Array.from(i,n=>t.get(n)),{coordinates:i,labels:e}}function Ih(i){if(i.length===1)return i[0];const e=new Map;let t=!1;for(const r of i){r.explicit&&(t=!0);const{coordinates:o,labels:a}=r;for(let l=0,c=o.length;l<c;++l)e.set(o[l],a[l])}const n=Array.from(e.keys());n.sort((r,o)=>r-o);const s=Array.from(n,r=>e.get(r));return{explicit:t,coordinates:n,labels:s}}function Rh(i){if(i=i.filter(e=>e!==void 0),i.length!==0)return Ih(i)}function iw(i,e){return(0,z.r1)(i.transform,e.transform)&&ew(i.box,e.box)}function er(i,e){return i.valid===e.valid&&i.rank===e.rank&&(0,z.r1)(i.names,e.names)&&(0,z.r1)(i.ids,e.ids)&&(0,z.r1)(i.timestamps,e.timestamps)&&(0,z.r1)(i.units,e.units)&&(0,z.r1)(i.scales,e.scales)&&(0,z.wm)(i.boundingBoxes,e.boundingBoxes,iw)&&(0,z.wm)(i.coordinateArrays,e.coordinateArrays,tw)}function s_(i,e,t){parseFixedLengthArray(i,t,(n,s)=>{const r=unitFromJson(n);return e[s]=r.exponent,r.unit})}function ke(i){const{names:e,units:t,scales:n}=i,{valid:s=!0,rank:r=e.length,timestamps:o=e.map(()=>Number.NEGATIVE_INFINITY),ids:a=e.map((u,h)=>-h),boundingBoxes:l=[]}=i,{coordinateArrays:c=new Array(r)}=i,{bounds:d=lw(l,r)}=i;return{valid:s,rank:r,names:e,timestamps:o,ids:a,units:t,scales:n,boundingBoxes:l,bounds:d,coordinateArrays:c}}const Bn=ke({valid:!1,names:[],units:[],scales:Dh,boundingBoxes:[]}),xi=ke({valid:!0,names:[],units:[],scales:Dh,boundingBoxes:[]});function sw(i){const[e,t]=(0,p.J6)(i,2),n=(0,p.Mo)(e),s=(0,p.zr)(t),r=Xs.get(s);if(r===void 0)throw new Error(`Invalid unit: ${JSON.stringify(s)}`);return{unit:r.unit,scale:kl(n,r.exponent)}}function Ei(i,e=!1){if(i===void 0)return Bn;(0,p.Rf)(i);const t=Bl(Object.keys(i),e),n=t.length,s=new Array(n),r=new Float64Array(n),o=new Array(n);for(let a=0;a<n;++a)(0,p.cQ)(i,t[a],l=>{if(Array.isArray(l)){const{unit:c,scale:d}=sw(l);s[a]=c,r[a]=d}else{(0,p.Rf)(l);const c=(0,p.cQ)(l,"coordinates",p.VH),d=(0,p.cQ)(l,"labels",p.si),u=c.length;if(u!==d.length)throw new Error(`Length of coordinates array (${u}) does not match length of labels array (${d.length})`);s[a]="",r[a]=1,o[a]={explicit:!0,...nw(c,d)}}});return ke({valid:!1,names:t,units:s,scales:r,coordinateArrays:o})}function ro(i){const{rank:e}=i;if(e===0)return;const{names:t,units:n,scales:s,coordinateArrays:r}=i,o={};for(let a=0;a<e;++a){const l=t[a],c=r[a];c?.explicit?o[l]={coordinates:Array.from(c.coordinates),labels:c.labels}:o[l]=[s[a],n[a]]}return o}class Ml extends A.B0{constructor(){super(Bn)}toJSON(){return ro(this.value)}reset(){this.value=Bn}restoreState(e){this.value=Ei(e)}}function rw(i,e,t){return i.voxelCenterAtIntegerCoordinates[e]?t=Math.round(t):t=Math.floor(t)+.5,t}function kh(i,e){let t=i.lowerBounds[e],n=i.upperBounds[e];return i.voxelCenterAtIntegerCoordinates[e]&&(t+=.5,n+=.5),[t,n]}function ow(i,e,t){const n=i.upperBounds[e];Number.isFinite(n)&&(t=Math.min(t,n-1));const s=i.lowerBounds[e];return Number.isFinite(s)&&(t=Math.max(t,s)),t}function Nl(i,e,t){return t=ow(i,e,t),rw(i,e,t)}function Lh(i,e){let t=(i+e)/2;return Number.isFinite(t)||(t=Math.min(Math.max(0,i),e)),t}function aw(i,e){const{lowerBounds:t,upperBounds:n}=e,s=i.length;for(let r=0;r<s;++r)i[r]=Lh(t[r],n[r]);return i}function dn(i){const e=i.lowerBounds.length;return{box:i,transform:we.DA(Float64Array,e,e+1)}}function Ph(i,e,t){const{box:{lowerBounds:n,upperBounds:s},transform:r}=i,o=n.length,a=t,l=r[a*o+e];let c=l,d=l,u=!1;for(let h=0;h<o;++h){const f=r[a*h+e];if(f===0)continue;const m=f*n[h],g=f*s[h];c+=Math.min(m,g),d+=Math.max(m,g),u=!0}if(u)return{lower:c,upper:d}}function lw(i,e){const t=new Float64Array(e),n=new Float64Array(e);t.fill(Number.NEGATIVE_INFINITY),n.fill(Number.POSITIVE_INFINITY);const s=new Array(e);s.fill(0);const r=new Array(e);r.fill(0);for(const a of i)for(let l=0;l<e;++l){const c=Ph(a,l,e);if(c===void 0)continue;const{lower:d,upper:u}=c;if(Number.isFinite(d)&&Number.isFinite(u)){const h=Math.floor(d),f=Math.floor(u);h===d&&f===u?++r[l]:d-h===.5&&u-f===.5&&++s[l]}t[l]=t[l]===Number.NEGATIVE_INFINITY?d:Math.min(t[l],d),n[l]=n[l]===Number.POSITIVE_INFINITY?u:Math.max(n[l],u)}const o=r.map((a,l)=>s[l]>0&&a===0);return{lowerBounds:t,upperBounds:n,voxelCenterAtIntegerCoordinates:o}}function cw(i,e,t){const{transform:n,box:s}=i,r=t.length,o=s.lowerBounds.length,a=new Float64Array((o+1)*e);for(let l=0;l<r;++l){const c=t[l];if(c!==-1)for(let d=0;d<=o;++d)a[d*e+c]=n[d*r+l]}return{transform:a,box:s}}function Ah(i,e){const t={lowerBounds:Float64Array.of(0),upperBounds:Float64Array.of(1)},n=new Float64Array(2*i);return n[e]=1,{transform:n,box:t}}function Mh(i,e,t){if(e===t)return i;const{box:n}=i,s=n.lowerBounds.length,r=new Float64Array((s+1)*t);return we.C(r,t,i.transform,e,e,s+1),{box:n,transform:r}}function dw(i,e){const{rank:t,sourceRank:n}=i;if(t!==e.rank||n!==e.sourceRank)return!1;const{inputSpace:s}=i,{inputSpace:r}=e;return!(0,z.r1)(r.scales,s.scales)||!(0,z.r1)(r.units,s.units)||!(0,z.r1)(e.outputSpace.names,i.outputSpace.names)?!1:Vh(i.transform,t,i.outputSpace.scales,e.transform,t,e.outputSpace.scales)}function yt(i){return{rank:i.rank,sourceRank:i.rank,inputSpace:i,outputSpace:i,transform:we.DA(Float64Array,i.rank+1)}}function uw(i,e,t,n){const{transform:s,box:r}=i,o=i.box.lowerBounds.length,a=n.length,l=new Float64Array((o+1)*a);for(let c=0;c<a;++c){const d=n[c];for(let h=0;h<o;++h){let f=0;for(let m=0;m<a;++m){const g=t[m];f+=e[(a+1)*m+c]*s[a*h+m]*(g/d)}l[a*h+c]=f}let u=e[(a+1)*a+c];for(let h=0;h<a;++h){const f=t[h];u+=e[(a+1)*h+c]*s[a*o+h]*(f/d)}l[o*a+c]=u}return{transform:l,box:r}}function Nh(i,e,t){return i.boundingBoxes.map(n=>uw(n,e,i.scales,t))}function Ol(i,e,t){const n=ke({valid:i.valid,rank:t.rank,ids:t.ids,names:t.names,timestamps:t.timestamps,scales:t.scales,units:t.units,boundingBoxes:Nh(i,e,t.scales),coordinateArrays:t.coordinateArrays});return er(n,t)?t:n}function Vl(i,e=!1){if(e){const t=Number(i);if(Number.isInteger(t)&&t>=0)return!0}return i.match(/^[a-zA-Z][a-zA-Z_0-9]*['^]?$/)!==null}function oo(i,e=!1){const t=new Set;for(const n of i){if(!Vl(n,e)||t.has(n))return!1;t.add(n)}return!0}function _l(i){const e=i.length,t=new Array(e);t.fill(!0);for(let n=0;n<e;++n){const s=i[n];if(!Vl(s)){t[n]=!1;continue}const r=i.indexOf(s,n+1);r!==-1&&(t[n]=!1,t[r]=!1)}return t}function tr(i){return i.endsWith("'")}function Oh(i){return i.endsWith("'")||i.endsWith("^")}function hw(i){return i.endsWith("^")}function pw(i){return!Oh(i)}function fw(i,e,t){const n=new Float64Array(i),s=e.length,r=(s+1)*s;for(let o=0;o<s;++o)n[r+o]*=e[o]/t[o];return n}function Vh(i,e,t,n,s,r){if(!we.LC(i,e+1,n,s+1,e,e))return!1;for(let o=0;o<e;++o){const a=i[(e+1)*e+o],l=n[(s+1)*s+o];if(a*(t[o]/r[o])!==l)return!1}for(let o=e;o<s;++o)if(n[(s+1)*s+o]!==0)return!1;for(let o=e;o<s;++o){for(let a=0;a<e;++a)if(n[(s+1)*a+o]!==0)return!1;for(let a=0;a<s;++a){const l=n[(s+1)*o+a];if(o===a){if(l!==1)return!1}else if(l!==0)return!1}}return!0}function gw(i,e){if(!e.includes(i))return i;const[,t,n]=i.match(/^([^']*)('?)$/);for(let s=0;;++s){const r=`${t}${s}${n}`;if(!e.includes(r))return r}}function mw(i,e){const{inputSpace:t,transform:n}=i,{ids:s,rank:r}=t,{rank:o,names:a,units:l,scales:c}=e,d=new Array(r);d.fill(!0);const u=[],h=e.ids.map(($,Q)=>{const K=s.indexOf($);return K!==-1?d[K]=!1:u.push(Q),K}),{outputSpace:f}=i,{names:m,units:g,scales:v,ids:y,timestamps:S,coordinateArrays:x}=f,b=d,E=[],C=[],k=new Float64Array(o),T=[],L=[],_=new Array(o);let R=0;const P=new Float64Array((o+1)**2);P[P.length-1]=1;for(let $=0;$<r;++$)if(!b[$]){E[R]=m[$],T[R]=y[$],C[R]=g[$],k[R]=v[$],L[R]=S[$],_[R]=x[$];for(let Q=0;Q<o;++Q){const K=h[Q];K!==-1&&(P[Q*(o+1)+R]=n[K*(r+1)+$])}P[o*(o+1)+R]=n[r*(r+1)+$],++R}for(const $ of u)T[R]=os(),E[R]=gw(a[$],E),k[R]=c[$],C[R]=l[$],P[$*(o+1)+R]=1,++R;const V=ke({valid:e.valid,rank:o,names:E,ids:T,timestamps:L,units:C,scales:k,boundingBoxes:Nh(e,P,k),coordinateArrays:_});return{rank:o,sourceRank:i.sourceRank,inputSpace:e,outputSpace:V,transform:P}}function _h(i){const e=Ol(i.inputSpace,i.transform,i.outputSpace);return e===i.outputSpace?i:{rank:i.rank,sourceRank:i.sourceRank,inputSpace:i.inputSpace,transform:i.transform,outputSpace:e}}class Bh{constructor(e,t=!1){this.mutableSourceRank=t,this.value_=void 0,this.changed=new j.IY,this.inputSpaceChanged=new j.IY,this.defaultTransform=_h(e);const n=this;this.outputSpace={changed:n.changed,get value(){return n.value.outputSpace},set value(s){const{value:r}=n;if(er(r.outputSpace,s)||r.rank!==s.rank)return;const o=fw(r.transform,r.outputSpace.scales,s.scales);n.value_={sourceRank:r.sourceRank,rank:r.rank,inputSpace:r.inputSpace,outputSpace:Ol(r.inputSpace,o,s),transform:o},n.changed.dispatch()}},this.inputSpace={changed:n.inputSpaceChanged,get value(){return n.value.inputSpace},set value(s){const{value:r}=n;er(r.inputSpace,s)||(n.value_=mw(r,s),n.inputSpaceChanged.dispatch(),n.changed.dispatch())}}}set value(e){const t=this.value;e!==t&&(this.value_=_h(e),e.inputSpace!==t.inputSpace&&this.inputSpaceChanged.dispatch(),this.changed.dispatch())}get value(){let{value_:e}=this;return e===void 0&&(e=this.value_=this.defaultTransform),e}reset(){this.value_!==this.defaultTransform&&(this.value_=this.defaultTransform,this.inputSpaceChanged.dispatch(),this.changed.dispatch())}get defaultInputSpace(){return this.defaultTransform.inputSpace}get spec(){const{value:e}=this,{rank:t,transform:n,inputSpace:s,outputSpace:r,sourceRank:o}=e,{defaultTransform:a,mutableSourceRank:l}=this,{inputSpace:c,rank:d,transform:u,outputSpace:h}=a,{units:f,scales:m}=s,g=o===t&&(0,z.r1)(m,l?r.scales:c.scales)&&(0,z.r1)(f,l?r.units:c.units),v=Vh(u,d,h.scales,n,t,r.scales),y=(0,z.r1)(h.names,r.names);if(!(v&&y&&g))return{sourceRank:o,transform:v?void 0:n,outputSpace:e.outputSpace,inputSpace:g?void 0:s}}set transform(e){const{value:t}=this,{inputSpace:n}=t;this.value_={rank:t.rank,sourceRank:t.sourceRank,inputSpace:n,transform:e,outputSpace:Ol(n,e,t.outputSpace)},this.changed.dispatch()}set spec(e){if(e===void 0){this.reset();return}if(this.mutableSourceRank){const R=e.inputSpace||e.outputSpace,P=R.rank,V=ke({rank:P,names:R.names.map(($,Q)=>`${Q}`),units:R.units,scales:R.scales,coordinateArrays:R.coordinateArrays});this.value={rank:P,transform:e.transform||we.DA(Float64Array,P+1),sourceRank:e.sourceRank,outputSpace:e.outputSpace,inputSpace:V};return}const{inputSpace:t,sourceRank:n,outputSpace:s,transform:r,rank:o}=this.defaultTransform,{inputSpace:a,sourceRank:l,outputSpace:c,transform:d}=e,u=e.outputSpace.rank,h=t.names,f=a!==void 0?a.names:h,m=new Array(n);for(let R=0;R<n;++R){let P=f.indexOf(h[R]);P>=l&&(P=-1),m[R]=P}const g=u-l+n;for(let R=l;R<u;++R)m[n+R-l]=R;const v=new Float64Array(g),y=new Array(g),S=[];for(let R=0;R<n;++R){const P=m[R];P===-1||a===void 0?(v[R]=t.scales[R],S[R]=t.units[R],y[R]=t.coordinateArrays[R]):(v[R]=a.scales[P],S[R]=a.units[P],y[R]=Rh([t.coordinateArrays[R],a.coordinateArrays[P]]))}const x=a||c,b=h.slice(0,n),E=s.names.slice(0,n),C=s.coordinateArrays.slice(0,n),k=new Float64Array(g),T=[];for(let R=0;R<g;++R){const P=m[R];P===-1?(k[R]=s.scales[R],T[R]=s.units[R],C[R]=s.coordinateArrays[R]):(E[R]=c.names[P],T[R]=c.units[P],k[R]=c.scales[P],C[R]=c.coordinateArrays[P])}if(!oo(E)){this.reset();return}for(let R=n;R<g;++R){const P=R-n+l;v[R]=x.scales[P],S[R]=x.units[P],b[R]=`${R}`}const L=new Float64Array((g+1)**2);L[L.length-1]=1;for(let R=0;R<g;++R){const P=m[R];let V;P===-1||d===void 0?R>=n?V=0:V=r[o*(o+1)+R]*(s.scales[R]/k[R]):V=d[u*(u+1)+P],L[g*(g+1)+R]=V;for(let $=0;$<g;++$){const Q=m[$];let K;P===-1!=(Q===-1)?K=0:P===-1||d===void 0?P>=n||Q>=n?K=P===Q?1:0:K=r[$*(o+1)+R]:K=d[Q*(u+1)+P],L[$*(g+1)+R]=K}}const _=t.boundingBoxes.map(R=>Mh(R,o,g));for(let R=n;R<g;++R)_.push(Ah(g,R));for(let R=0;R<g;++R){if(L[g*(g+1)+R]!==0)continue;let V;for(let Q=0;Q<g;++Q){const K=L[Q*(g+1)+R];if(K!==0)if(K===1)if(V===void 0)V=Q;else{V=null;break}else{V=null;break}}if(V==null)continue;let $=y[V];$!==void 0&&($.explicit&&($={...$,explicit:!1}),C[R]=Rh([$,C[R]]))}this.value={rank:g,transform:L,sourceRank:n,outputSpace:ke({rank:g,names:E,scales:k,units:T,coordinateArrays:C}),inputSpace:ke({rank:g,names:b,scales:v,units:S,coordinateArrays:y,boundingBoxes:_})}}toJSON(){return $h(this.spec)}restoreState(e){this.spec=Uh(e)}}function vw(i,e=!1){const t=(0,p.zr)(i);if(!Vl(t,e))throw new Error(`Invalid dimension name: ${JSON.stringify(t)}`);return t}function Bl(i,e=!1){const t=(0,p.$v)(i,n=>vw(n,e));if(!oo(t,e))throw new Error(`Invalid dimensions: ${JSON.stringify(t)}`);return t}class Fl{constructor(e,t){this.combined=e,this.bindings=new Set,this.retainCount=0,this.prevCombined=this.combined.value,this.dimensionRefCounts=new Map,this.handleCombinedChanged=()=>{this.combined.value!==this.prevCombined&&this.update()},this.includeDimensionPredicate_=t}getRenameValidity(e){const t=this.combined.value.names,n=_l(e),s=e.length;for(let r=0;r<s;++r){if(!n[r])continue;const o=e[r];if(t.includes(o))continue;let a=!0;for(const l of this.bindings)if(l.space.value.names.includes(o)){a=!1;break}n[r]=a}return n}get includeDimensionPredicate(){return this.includeDimensionPredicate_}set includeDimensionPredicate(e){this.includeDimensionPredicate_=e,this.update()}update(){const{combined:e,bindings:t}=this,n=this.retainCount>0?1:0;if(t.size===0&&!n){e.value=Bn;return}const s=this.includeDimensionPredicate_,r=e.value;let o=Array.from(r.names),a=Array.from(r.units),l=Array.from(r.scales),c=Array.from(r.ids),d=Array.from(r.timestamps),u=r.names.map(()=>n?1:0);const h=[];let f=!1;for(const E of t){const{space:{value:C},prevValue:k,mappedDimensionIds:T}=E;f=f||C.valid;const{names:L,units:_,scales:R,ids:P,timestamps:V}=C,$=[],Q=[];h.push(Q),E.mappedDimensionIds=$,E.prevValue=C;const K=L.length;for(let ee=0;ee<K;++ee){const ce=L[ee];if(!s(ce))continue;if(k!==void 0){const ve=P[ee],Ie=k.ids.indexOf(ve);if(Ie!==-1){const mt=T[Ie];if(mt!==void 0){const Fe=c.indexOf(mt);if(Fe!==-1){$[ee]=mt,++u[Fe],Q[ee]=Fe;const Ct=V[ee];Ct!==void 0&&!(Ct<=d[Fe])&&(o[Fe]=ce,l[Fe]=R[ee],a[Fe]=_[ee],d[Fe]=Ct);continue}}}}let fe=o.indexOf(ce);if(fe!==-1){$[ee]=c[fe],++u[fe],Q[ee]=fe;continue}fe=o.length,Q[ee]=fe,u[fe]=1+n,o[fe]=ce,a[fe]=_[ee],l[fe]=R[ee],d[fe]=V[ee];const le=os();c[fe]=le,$[ee]=le}}const{dimensionRefCounts:m}=this;m.clear();let g=0,v=o.length;for(const E of t){const{space:{value:C}}=E,k=h[g++],{rank:T}=C,L=Array.from(C.names),_=Array.from(C.timestamps),R=Float64Array.from(C.scales),P=Array.from(C.units);for(let V=0;V<T;++V){const $=k[V];$!==void 0&&(P[V]=a[$],R[V]=l[$],_[V]=d[$],L[V]=o[$])}for(const V of L){let $=m.get(V);$===void 0?$=1:++$,m.set(V,$)}if(!(0,z.r1)(P,C.units)||!(0,z.r1)(R,C.scales)||!(0,z.r1)(L,C.names)||!(0,z.r1)(_,C.timestamps)){const V=ke({valid:C.valid,ids:C.ids,scales:R,units:P,names:L,timestamps:_,boundingBoxes:C.boundingBoxes,coordinateArrays:C.coordinateArrays});E.prevValue=V,E.space.value=V}}{for(let C=0;C<v;++C)s(o[C])||(u[C]=0);const E=(C,k)=>u[k]!==0;o=o.filter(E),a=a.filter(E),l=l.filter(E),c=c.filter(E),d=d.filter(E),u=u.filter(E),v=o.length}const y=[],S=new Array(v);for(let E=0,C=r.rank;E<C;++E){const k=r.coordinateArrays[E];if(!k?.explicit)continue;const T=c.indexOf(r.ids[E]);T!==-1&&(S[T]=[k])}for(const E of t){const{space:{value:C}}=E,{rank:k,boundingBoxes:T,coordinateArrays:L}=C,_=C.names.map(R=>o.indexOf(R));for(const R of T)y.push(cw(R,v,_));for(let R=0;R<k;++R){const P=L[R];if(P===void 0)continue;const V=_[R],$=S[V];$===void 0?S[V]=[P]:$.push(P)}}const x=new Array(v);for(let E=0;E<v;++E){const C=S[E];C!==void 0&&(x[E]=Ih(C))}const b=ke({valid:f,ids:c,names:o,units:a,scales:new Float64Array(l),boundingBoxes:y,coordinateArrays:x});if(n)for(let E=0;E<v;++E)--u[E];er(r,b)||(this.prevCombined=b,e.value=b)}retain(){return++this.retainCount,()=>{--this.retainCount===0&&this.update()}}bind(e){const t={space:e,mappedDimensionIds:[],prevValue:void 0},{bindings:n}=this;n.size===0&&this.combined.changed.add(this.handleCombinedChanged),n.add(t);const s=e.changed.add(()=>{e.value!==t.prevValue&&this.update()}),r=()=>{s();const{bindings:o}=this;o.delete(t),o.size===0&&this.combined.changed.remove(this.handleCombinedChanged),this.update()};return this.update(),r}}function Fh(i,e,t,n,s){const r=s.length,o=new i((r+1)**2);o[o.length-1]=1;for(let a=0;a<r;++a){const l=n[a];o[(r+1)*r+a]=e[(t+1)*t+l];for(let c=0;c<r;++c){const d=s[c];o[(r+1)*c+a]=e[(t+1)*d+l]}}return o}function yw(i){if(i===void 0)return;const e=new Float64Array(16);if(Array.isArray(i))if(i.length===16)for(let t=0;t<4;++t)for(let n=0;n<4;++n)e[t*4+n]=(0,p.zo)(i[n*4+t]);else{(0,p.J6)(i,4);for(let t=0;t<4;++t){const n=(0,p.J6)(i[t],4);for(let s=0;s<4;++s)e[s*4+t]=(0,p.zo)(n[s])}}else{(0,p.Rf)(i);const t=w.Yu.create(),n=w.eR.create(),s=w.eR.fromValues(1,1,1);(0,p.MM)(i,"rotation",o=>{(0,p.Vr)(t,o),w.Yu.normalize(t,t)}),(0,p.MM)(i,"translation",o=>{(0,p.Vr)(n,o)}),(0,p.MM)(i,"scale",o=>{(0,p.Vr)(s,o)});const r=w.pB.create();w.pB.fromRotationTranslationScale(r,t,n,s),e.set(r)}return{sourceRank:3,transform:e,outputSpace:ke({valid:!0,names:["x","y","z"],units:["m","m","m"],scales:Float64Array.of(1e-9,1e-9,1e-9)}),inputSpace:void 0}}function Uh(i){if(i===void 0)return;const e=(0,p.Rf)(i),t=(0,p.cQ)(e,"outputDimensions",Ei),n=t.rank,s=(0,p.cQ)(e,"sourceRank",a=>{if(a===void 0)return n;if(!Number.isInteger(a)||a<0||a>n)throw new Error(`Expected integer in range [0, ${n}] but received: ${JSON.stringify(a)}`);return a}),r=(0,p.MM)(e,"inputDimensions",a=>{const l=Ei(a,!0);if(l.rank!==n)throw new Error(`Expected rank of ${n}, but received rank of: ${l.rank}`);return l});return{transform:(0,p.MM)(e,"matrix",a=>{const l=new Float64Array((n+1)**2),c=(0,p.J6)(a,n);l[l.length-1]=1;for(let d=0;d<n;++d)try{const u=(0,p.J6)(c[d],n+1);for(let h=0;h<=n;++h)l[(n+1)*h+d]=(0,p.zo)(u[h])}catch(u){throw new Error(`Error in row ${d}: ${u.message}`)}return l}),outputSpace:t,inputSpace:r,sourceRank:s}}function $h(i){if(i===void 0)return;const{transform:e,outputSpace:t,inputSpace:n,sourceRank:s}=i;let r;const o=t.rank;if(e!==void 0){r=[];for(let a=0;a<o;++a){const l=[];r[a]=l;for(let c=0;c<=o;++c)l[c]=e[(o+1)*c+a]}}return{sourceRank:s===o?void 0:s,matrix:r,outputDimensions:ro(t),inputDimensions:n===void 0?void 0:ro(n)}}function Sw(i,e,t){const{box:n,transform:s}=i,r=i.box.lowerBounds.length,o=e.length,a=new Float64Array((r+1)*o);if(we.ay(a,o,s,t,e,r+1),!a.every(l=>l===0))return{transform:a,box:n}}function Ul(i,e){const{ids:t,names:n,scales:s,units:r,timestamps:o,coordinateArrays:a}=i;return ke({rank:e.length,valid:i.valid,ids:e.map(l=>t[l]),names:e.map(l=>n[l]),timestamps:e.map(l=>o[l]),scales:Float64Array.from(e,l=>s[l]),units:e.map(l=>r[l]),coordinateArrays:e.map(l=>a[l]),boundingBoxes:i.boundingBoxes.map(l=>Sw(l,e,i.rank)).filter(l=>l!==void 0)})}function Gh(i,e,t){return e===t?i:Ul(i,(0,z.ep)(i.rank,t,e))}function zh(i,e){const{transform:t,rank:n}=i,s=(0,w.PC)(t,n,[e]);if(s.length!==1)return;const[r]=s,o=Math.abs(t[(n+1)*r+e]),{inputSpace:a}=i;return{scale:a.scales[r]*o,unit:a.units[r]}}function Wh(i,e){const{scales:t,units:n}=i.defaultInputSpace;return e<t.length?{scale:t[e],unit:n[e]}:void 0}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const r_={channelCoordinateSpace:xi,shape:new Uint32Array(0),numChannels:1,coordinates:new Uint32Array(0)};function bw(i){const{rank:e}=i,{bounds:{lowerBounds:t,upperBounds:n}}=i;if(t.some(a=>a!==0))throw new Error("Lower bounds of channel coordinate space must all be 0");if(n.some(a=>!Number.isInteger(a)||a<=0||a>=4294967296))throw new Error("Upper bounds of channel coordinate space must all be positive integers");const s=new Uint32Array(n),r=Al(s),o=new Uint32Array(r*e);for(let a=0;a<r;++a){let l=a;for(let c=0;c<e;++c){const d=l%s[c];l=(l-d)/s[c],o[a*e+c]=d}}return{channelCoordinateSpace:i,shape:s,numChannels:r,coordinates:o}}function $l(i,e,t,n,s,r){const{scales:o}=t,{scales:a,rank:l}=s,c=e+1;for(let d=0;d<l;++d){const u=r[d];if(u===-1)continue;const h=a[d];for(let f=0;f<e;++f){const m=n[f],g=o[m];i[c*f+u]*=g/h}}}function ww(i,e,t,n,s=xi){const{inputSpace:r,rank:o,sourceRank:a,outputSpace:l,transform:c}=t,{names:d}=r,{names:u}=l;let h;if(n!==void 0)h=Array.from(n.modelSubspaceDimensionIndices);else{h=[];for(let V=0;V<a;++V)h[V]=V}const f=h.length;for(let V=a;V<o;++V)h.push(V);const m=(0,w.PC)(t.transform,o,h,!0),g=h.length,v=h.map(V=>d[V]||`${V}`),y=m.map(V=>u[V]);if(g!==m.length)return{error:"Rank mismatch between model subspace dimensions ("+v.join(", ")+") and corresponding layer/global dimensions ("+y.join(", ")+")"};let S=Fh(Float32Array,c,o,m,h);const x=m.map(V=>u[V]),b=e.names.map(V=>x.indexOf(V)),E=i.names.map(V=>x.indexOf(V));$l(S,g,r,h,i,E),$l(S,g,r,h,e,b);const C=s.names.map(V=>x.indexOf(V));$l(S,g,r,h,s,C);const k=[],T=s.rank;if(n!==void 0){let{subsourceToModelSubspaceTransform:V}=n;f!==g&&(V=we.Aw(new Float32Array((g+1)**2),g,V,f)),S=we.lw(new Float32Array((g+1)**2),g+1,S,g+1,V,g+1,g+1,g+1,g+1)}const L=new Uint32Array(T),{lowerBounds:_,upperBounds:R,voxelCenterAtIntegerCoordinates:P}=s.bounds;for(let V=0;V<T;++V){let $=_[V],Q=R[V];if(P[V]&&($+=.5,Q+=.5),$!==0||!Number.isInteger(Q)||Q<=0||Q>=4294967296)return{error:`Channel dimension ${s.names[V]} must have lower bound of 0 and positive integer upper bound; current bounds are [${$}, ${Q}]`};L[V]=Q;const K=C[V];let ee=-1;if(K!==-1)for(let ce=0;ce<g;++ce){const fe=S[K+ce*(g+1)];if(fe!==0){if(fe!==1||ee!==-1)return{error:`Channel dimension ${y[K]} must map to a single source dimension`};ee=ce}}k[V]=ee}return{rank:g,unpaddedRank:f,modelDimensionNames:v,layerDimensionNames:y,localToRenderLayerDimensions:b,globalToRenderLayerDimensions:E,channelToRenderLayerDimensions:C,modelToRenderLayerTransform:S,channelToModelDimensions:k,channelSpaceShape:L}}function Cw(i,e){return i===e?!0:i.error!==void 0||e.error!==void 0?!1:(0,z.r1)(i.modelDimensionNames,e.modelDimensionNames)&&(0,z.r1)(i.layerDimensionNames,e.layerDimensionNames)&&(0,z.r1)(i.globalToRenderLayerDimensions,e.globalToRenderLayerDimensions)&&(0,z.r1)(i.localToRenderLayerDimensions,e.localToRenderLayerDimensions)&&(0,z.r1)(i.channelToRenderLayerDimensions,e.channelToRenderLayerDimensions)&&(0,z.r1)(i.modelToRenderLayerTransform,e.modelToRenderLayerTransform)&&(0,z.r1)(i.channelSpaceShape,e.channelSpaceShape)}function Hh(i,e,t,n,s){return(0,A.Uq)((r,o,a,l)=>ww(r,o,a,n,l),[i,e,t,s===void 0?(0,A.XZ)(void 0):s],Cw)}function xw(i,e,t,n){const{globalToRenderLayerDimensions:s}=t;for(let r=0;r<3;++r){let o=0;const a=n[r];if(a!==-1){const l=s[a];l!==-1&&(o=e[l])}i[r]=o}}function Ew(i,e,t,n){const{globalToRenderLayerDimensions:s}=t;for(let r=0;r<3;++r){const o=n[r];if(o!==-1){const a=s[o];a!==-1&&(i[a]=e[r])}}}function o_(i,e,t,n){const{globalToRenderLayerDimensions:s}=t.modelTransform,{layerRank:r,chunkToLayerTransform:o}=t,a=r+1;for(let l=0;l<3;++l){let c=0;const d=n[l];if(d!==-1){const u=s[d];if(u!==-1){c=o[a*r+u];for(let h=0;h<r;++h)c+=o[a*h+u]*e[h]}}i[l]=c}return i}function ao(i,e){const t=i.rank,n=i.unpaddedRank;let s;n!==t&&e!==void 0&&(e=we.Aw(new Float32Array((t+1)**2),t,e,n)),e!==void 0?(s=new Float32Array((t+1)*(t+1)),we.lw(s,t+1,i.modelToRenderLayerTransform,t+1,e,t+1,t+1,t+1,t+1)):s=i.modelToRenderLayerTransform;const r=new Float32Array((t+1)*(t+1)),o=we.DI(r,t+1,s,t+1,t+1);if(o===0)throw new Error("Transform is singular");const{globalToRenderLayerDimensions:a,localToRenderLayerDimensions:l,channelToRenderLayerDimensions:c}=i,d=a.length,u=l.length,h=d+u,f=new Float32Array((h+1)*t);for(let E=0;E<t;++E){for(let C=0;C<d;++C){const k=a[C];k!==-1&&(f[E+C*t]=r[E+k*(t+1)])}for(let C=0;C<u;++C){const k=l[C];k!==-1&&(f[E+(d+C)*t]=r[E+k*(t+1)])}f[E+h*t]=r[E+t*(t+1)]}const m=c.length,g=new Array(m),v=[];for(let E=0;E<m;++E){const C=c[E];let k=-1;if(C!==-1){for(let T=0;T<t;++T){const L=s[C+T*(t+1)];if(L!==0){if(L!==1||k!==-1)throw new Error(`Channel dimension ${i.layerDimensionNames[C]} must map with stride 1 to a single data chunk dimensions`);k=T}}if(k!==-1){const T=s[C+t*(t+1)];if(T!==0&&T!==-.5)throw new Error(`Channel dimension ${i.layerDimensionNames[C]} must have an offset of 0 in the chunk coordinate space; current offset is ${T}`);v.push(k)}}g[E]=k}const{channelSpaceShape:y}=i,S=Al(y),x=v.length,b=new Uint32Array(S*x);for(let E=0;E<S;++E){let C=E,k=0;for(let T=0;T<m;++T){const L=C%y[T];C=(C-L)/y[T],g[T]!==-1&&(b[E*x+k]=L,++k)}}return{layerRank:t,modelTransform:i,chunkToLayerTransform:s,layerToChunkTransform:r,chunkToLayerTransformDet:o,combinedGlobalLocalRank:h,combinedGlobalLocalToChunkTransform:f,channelToChunkDimensionIndices:g,chunkChannelDimensionIndices:v,numChannels:S,chunkChannelCoordinates:b,channelSpaceShape:y}}function Jh(i,e){const{globalToRenderLayerDimensions:t}=i,n=[],s=[];for(let r=0;r<3;++r){const o=e[r];if(o===-1)continue;const a=t[o];s.push(a),a!==-1&&n.push(a)}for(let r=s.length;r<3;++r)s[r]=-1;return{layerDisplayDimensionIndices:n,displayToLayerDimensionIndices:s}}function jh(i,e){const{chunkToLayerTransform:t,modelTransform:n}=i,s=n.rank,{layerDisplayDimensionIndices:r,displayToLayerDimensionIndices:o}=e,a=r.length,l=(0,w.PC)(t,s,r);if(l.length!==a){const{modelDimensionNames:u,layerDimensionNames:h}=n;throw new Error(`Rank mismatch between displayed layer dimensions (${Array.from(r,f=>h[f]).join(",\xA0")}) and corresponding chunk dimensions (${Array.from(l,f=>u[f]).join(",\xA0")})`)}const c=w.pB.create();for(let u=0;u<3;++u){const h=o[u];if(h!==-1){for(let f=0;f<a;++f){const m=l[f];c[f*4+u]=t[m*(s+1)+h]}c[12+u]=t[s*(s+1)+h]}}const d=w.pB.create();w.pB.invert(d,c);for(let u=l.length;u<3;++u)l[u]=-1;return{modelTransform:i.modelTransform,chunkTransform:i,displaySubspaceModelMatrix:c,displaySubspaceInvModelMatrix:d,chunkDisplayDimensionIndices:l,numChunkDisplayDims:a}}function as(i,e,t,n,s){const r=e.length,o=t.length,a=i.length;let l=!0;for(let c=0;c<n;++c){let d=c,u=0;for(let h=0;h<r;++h)u+=s[d+h*n]*e[h];d+=r*n;for(let h=0;h<o;++h)u+=s[d+h*n]*t[h];u+=s[d+o*n],c<a?i[c]=u:(u<0||u>=1)&&(l=!1)}return l}function a_(i,e,t,n){return scatterUpdate(i,e,n.globalToRenderLayerDimensions),scatterUpdate(i,t,n.localToRenderLayerDimensions),i}function Tw(i,e,t){i.fill(0),i[15]=1;let n=!0;const{displayDimensionIndices:s}=e,{globalToRenderLayerDimensions:r,modelToRenderLayerTransform:o}=t,a=t.rank;for(let l=0;l<3;++l){const c=s[l];if(c===-1){n=!1;continue}const d=r[c];if(d===-1){n=!1;continue}i[l+12]=o[d+a*(a+1)];for(let u=0;u<3;++u)i[l+4*u]=o[d+(a+1)*u]}if(!n){const{globalDimensionNames:l}=e,c=Array.from(s.filter(d=>d!==-1),d=>l[d]).join(",\xA0");throw new Error(`Transform from model dimensions (${t.modelDimensionNames.join(",\xA0")}) to display dimensions (${c}) does not have full rank`)}}var xe=G(5716);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var Be=(i=>(i[i.GPU_MEMORY=0]="GPU_MEMORY",i[i.SYSTEM_MEMORY=1]="SYSTEM_MEMORY",i[i.SYSTEM_MEMORY_WORKER=2]="SYSTEM_MEMORY_WORKER",i[i.DOWNLOADING=3]="DOWNLOADING",i[i.QUEUED=4]="QUEUED",i[i.NEW=5]="NEW",i[i.FAILED=6]="FAILED",i[i.EXPIRED=7]="EXPIRED",i))(Be||{});const Gl=8;var ni=(i=>(i[i.FIRST_TIER=0]="FIRST_TIER",i[i.FIRST_ORDERED_TIER=0]="FIRST_ORDERED_TIER",i[i.VISIBLE=0]="VISIBLE",i[i.PREFETCH=1]="PREFETCH",i[i.LAST_ORDERED_TIER=1]="LAST_ORDERED_TIER",i[i.RECENT=2]="RECENT",i[i.LAST_TIER=2]="LAST_TIER",i))(ni||{});const zl=3;var Wl=(i=>(i[i.totalTime=0]="totalTime",i[i.totalChunks=1]="totalChunks",i))(Wl||{}),ii=(i=>(i[i.numChunks=0]="numChunks",i[i.systemMemoryBytes=1]="systemMemoryBytes",i[i.gpuMemoryBytes=2]="gpuMemoryBytes",i))(ii||{});const Fn=3,Yh=Gl*zl*Fn+2;function Ti(i,e){return i*zl+e}function Qh(i){return Gl*zl*Fn+i}const c_=1e13,Dw="ChunkQueueManager",Iw="ChunkManager",Rw="ChunkSource.invalidate",kw="ChunkQueueManager.requestChunkStatistics",Lw="ChunkManager.chunkLayerStatistics";class lo{constructor(){this.numVisibleChunksNeeded=0,this.numVisibleChunksAvailable=0,this.numPrefetchChunksNeeded=0,this.numPrefetchChunksAvailable=0}}var je=G(4104);/**
 * @license
 * Copyright 2024 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var qh=(i=>(i[i.MEDIAN=0]="MEDIAN",i[i.MEAN=1]="MEAN",i[i.MAX=2]="MAX",i))(qh||{});class Pw{constructor(e=10,t=10){if(this.numStoredTimes=e,this.queryPoolSize=t,this.timeElapsedQueries=[],this.warnedAboutMissingExtension=!1,this.storedTimeDeltas=[],this.queryPoolSize<1)throw new Error(`Query pool size must be at least 1, but got ${t}.`)}getTimingExtension(e){const t=e.getExtension("EXT_disjoint_timer_query_webgl2");return t===null&&!this.warnedAboutMissingExtension&&(console.log("EXT_disjoint_timer_query_webgl2 extension not available. Cannot measure frame time."),this.warnedAboutMissingExtension=!0),t}startFrameTimeQuery(e,t){if(t===null)return null;const n=e.createQuery();return n!==null&&e.beginQuery(t.TIME_ELAPSED_EXT,n),n}endFrameTimeQuery(e,t,n){if(t!==null&&n!==null&&e.endQuery(t.TIME_ELAPSED_EXT),this.timeElapsedQueries.length>=this.queryPoolSize){const s=this.timeElapsedQueries.shift();s!=null&&e.deleteQuery(s)}this.timeElapsedQueries.push(n)}grabAnyFinishedQueryResults(e){const t=[];for(let n=0;n<this.timeElapsedQueries.length;n++){const s=this.timeElapsedQueries[n];if(s!==null&&e.getQueryParameter(s,e.QUERY_RESULT_AVAILABLE)){const o=e.getQueryParameter(s,e.QUERY_RESULT)/1e6;this.storedTimeDeltas.push(o),e.deleteQuery(s),t.push(n)}}for(let n=t.length-1;n>=0;n--)this.timeElapsedQueries.splice(n,1);this.storedTimeDeltas.length>this.numStoredTimes&&(this.storedTimeDeltas=this.storedTimeDeltas.slice(-this.numStoredTimes))}getLastFrameTimesInMs(e=10){return this.storedTimeDeltas.slice(-e)}getQueries(){return this.timeElapsedQueries}}class Aw{constructor(e=10,t=8,n=16.666666666666668,s=15){this.numberOfStoredFrameDeltas=e,this.maxDownsamplingFactor=t,this.desiredFrameTimingMs=n,this.downsamplingPersistenceDurationInFrames=s,this.lastFrameTime=null,this.frameDeltas=[],this.downsamplingRates=new Map,this.frameCount=0,this.validateConstructorArguments();for(let r=1;r<=this.maxDownsamplingFactor;r*=2)this.downsamplingRates.set(r,-1/0)}validateConstructorArguments(){this.numberOfStoredFrameDeltas=Math.max(1,Math.round(this.numberOfStoredFrameDeltas)),this.maxDownsamplingFactor=Math.max(2,Math.round(this.maxDownsamplingFactor))}storeFrameDelta(e){this.frameDeltas.push(e),this.frameDeltas.length>this.numberOfStoredFrameDeltas&&this.frameDeltas.shift()}calculateMeanFrameTime(){return this.frameDeltas.reduce((e,t)=>e+t,0)/this.frameDeltas.length}calculateMedianFrameTime(){const e=this.frameDeltas.slice().sort((n,s)=>n-s),t=Math.floor(e.length/2);return e.length%2===1?e[t]:(e[t-1]+e[t])/2}calculateMaxFrameTime(){return Math.max(...this.frameDeltas)}updateMaxTrackedDownsamplingRate(e){this.downsamplingRates.set(e,this.frameCount);let t=1;for(const[n,s]of this.downsamplingRates)this.frameCount-s<=this.downsamplingPersistenceDurationInFrames&&(t=n);return t}resetForNewFrameSet(){this.lastFrameTime=null,this.frameCount=0,this.downsamplingRates.forEach((e,t)=>{this.downsamplingRates.set(t,-1/0)})}addFrame(e=Date.now()){if(this.lastFrameTime!==null){const t=e-this.lastFrameTime;t>0&&this.storeFrameDelta(t)}this.lastFrameTime=e,this.frameCount++}calculateFrameTimeInMs(e=2){if(this.frameDeltas.length===0)return 0;switch(e){case 0:return this.calculateMedianFrameTime();case 1:return this.calculateMeanFrameTime();case 2:return this.calculateMaxFrameTime()}}calculateDownsamplingRate(e=1){const t=this.calculateFrameTimeInMs(e);if(t===0)return Math.min(4,this.maxDownsamplingFactor);let n=Math.max(t/this.desiredFrameTimingMs,1);return n=Math.min(Math.pow(2,Math.round(Math.log2(n))),this.maxDownsamplingFactor),this.updateMaxTrackedDownsamplingRate(n)}getFrameDeltas(){return this.frameDeltas}getFrameCount(){return this.frameCount}getDownsamplingRates(){return this.downsamplingRates}setFrameDeltas(e,t=!0){this.frameDeltas=e.slice(-this.numberOfStoredFrameDeltas),t&&this.frameCount++}}var Mw=G(310);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Nw=300;class Hl{constructor(){this.width=0,this.height=0,this.logicalWidth=0,this.logicalHeight=0,this.visibleLeftFraction=0,this.visibleTopFraction=0,this.visibleWidthFraction=0,this.visibleHeightFraction=0}}function Kh(i,e){const t=1/i.visibleWidthFraction,n=1/i.visibleHeightFraction,s=-1-(-1+2*i.visibleLeftFraction)*t;let r=-1-(-1+2*i.visibleTopFraction)*n;r=-r,e[0]=e[0]*t+e[3]*s,e[4]=e[4]*t+e[7]*s,e[8]=e[8]*t+e[11]*s,e[12]=e[12]*t+e[15]*s,e[1]=e[1]*n+e[3]*r,e[5]=e[5]*n+e[7]*r,e[9]=e[9]*n+e[11]*r,e[13]=e[13]*n+e[15]*r}function Xh(i,e){return i.width===e.width&&i.height===e.height&&i.logicalWidth===e.logicalWidth&&i.logicalHeight===e.logicalHeight&&i.visibleLeftFraction===e.visibleLeftFraction&&i.visibleTopFraction===e.visibleTopFraction}class Zh extends D.O8{constructor(e,t,n){super(),this.context=e,this.element=t,this.visibility=n,this.boundsGeneration=-1,this.canvasRelativeClippedLeft=0,this.canvasRelativeClippedTop=0,this.canvasRelativeLogicalLeft=0,this.canvasRelativeLogicalTop=0,this.renderViewport=new Hl,this.monitorState={},this.gl=e.gl,e.addPanel(this)}scheduleRedraw(){this.visible&&this.context.scheduleRedraw()}ensureBoundsUpdated(){const{context:e}=this;e.ensureBoundsUpdated();const{boundsGeneration:t}=e;if(t===this.boundsGeneration)return;this.boundsGeneration=t;const{element:n}=this,s=n.getBoundingClientRect();e.ensureMonitorPanel(n,this.monitorState,s);const r=e.container,o=e.canvasRect,{canvas:a}=e,{width:l,height:c}=a,d=l/o.width,u=c/o.height,h=o.left,f=o.top,m=this.canvasRelativeLogicalLeft=Math.round((s.left-h)*d+n.clientLeft),g=this.canvasRelativeLogicalTop=Math.round((s.top-f)*u+n.clientTop),v=n.clientWidth,y=n.clientHeight,S=m+v,x=g+y;let b=g,E=m,C=S,k=x;for(let R=n.parentElement;R!==null&&R!==r;R=R.parentElement){const P=R.getBoundingClientRect();P.x===0&&P.y===0&&P.width===0&&P.height===0||(E=Math.max(E,(P.left-h)*d),b=Math.max(b,(P.top-f)*u),C=Math.min(C,(P.right-h)*d),k=Math.min(k,(P.bottom-f)*u))}b=this.canvasRelativeClippedTop=Math.round(Math.max(b,0)),E=this.canvasRelativeClippedLeft=Math.round(Math.max(E,0)),C=Math.round(Math.min(C,l)),k=Math.round(Math.min(k,c));const T=this.renderViewport,L=T.width=Math.max(0,C-E),_=T.height=Math.max(0,k-b);T.logicalWidth=v,T.logicalHeight=y,T.visibleLeftFraction=(E-m)/v,T.visibleTopFraction=(b-g)/y,T.visibleWidthFraction=L/v,T.visibleHeightFraction=_/y}setGLClippedViewport(){const{gl:e,canvasRelativeClippedTop:t,canvasRelativeClippedLeft:n,renderViewport:{width:s,height:r}}=this,o=t+r;e.enable(WebGL2RenderingContext.SCISSOR_TEST);const a=this.context.canvas.height-o;e.viewport(n,a,s,r),e.scissor(n,a,s,r)}setGLLogicalViewport(){const{gl:e,renderViewport:{width:t,height:n,logicalWidth:s,logicalHeight:r}}=this,o=this.context.canvas.height;e.enable(WebGL2RenderingContext.SCISSOR_TEST),e.viewport(this.canvasRelativeLogicalLeft,o-(this.canvasRelativeLogicalTop+r),s,r),e.scissor(this.canvasRelativeClippedLeft,o-(this.canvasRelativeClippedTop+n),t,n)}disposed(){this.context.unmonitorPanel(this.element,this.monitorState),this.context.removePanel(this),super.disposed()}get visible(){return this.visibility.visible}getDepthArray(){}get shouldDraw(){if(!this.visible)return!1;const{element:e}=this;return!(e.clientWidth===0||e.clientHeight===0||e.offsetWidth===0||e.offsetHeight===0)}get drawOrder(){return 0}}class Jl extends Zh{constructor(e,t,n){super(e,t,n),this.canvas=document.createElement("canvas"),this.canvasRenderingContext=this.canvas.getContext("2d");const{canvas:s}=this;t.appendChild(s),t.style.position="relative",s.style.position="absolute",s.style.left="0",s.style.right="0",s.style.top="0",s.style.bottom="0"}draw(){this.drawIndirect();const{renderViewport:e,canvas:t}=this,{logicalWidth:n,logicalHeight:s}=e;t.width=n,t.height=s;const{canvasRenderingContext:r}=this;r?.drawImage(this.context.canvas,this.canvasRelativeLogicalLeft,this.canvasRelativeLogicalTop,n,s,0,0,n,s)}}class Ow extends A.DN{constructor(){super(Float64Array.of(0,0,1,1),e=>(0,p.Xu)(new Float64Array(4),e,p.xU))}toJSON(){const{value:e}=this,[t,n,s,r]=e;if(!(t===0&&n===0&&s===1&&r===1))return Array.from(e)}}class Vw extends D.O8{constructor(e){super(),this.container=e,this.canvas=document.createElement("canvas"),this.updateStarted=new j.IY,this.updateFinished=new j.IY,this.continuousCameraMotionStarted=new j.IY,this.continuousCameraMotionFinished=new j.IY,this.changed=this.updateFinished,this.panels=new Set,this.resizeGeneration=0,this.boundsGeneration=-1,this.framerateMonitor=new Pw,this.continuousCameraMotionInProgress=!1,this.orderedPanels=[],this.frameNumber=0,this.resizeCallback=()=>{++this.resizeGeneration,this.scheduleRedraw()},this.resizeObserver=new ResizeObserver(this.resizeCallback),this.debouncedEndContinuousCameraMotion=this.registerCancellable((0,xe.A)(()=>{this.continuousCameraMotionInProgress=!1,this.continuousCameraMotionFinished.dispatch()},Nw)),this.scheduleRedraw=this.registerCancellable((0,je.t)(()=>this.draw()));const{canvas:t,resizeObserver:n}=this;e.style.position="relative",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.width="100%",t.style.height="100%",t.style.zIndex="0",n.observe(t),e.appendChild(t),this.registerEventListener(t,"webglcontextlost",s=>{console.log(`Lost WebGL context: ${s.statusMessage}`),s.preventDefault()}),this.registerEventListener(t,"webglcontextrestored",()=>{console.log("WebGL context restored"),window.location.reload()}),this.gl=(0,Mw.y)(t)}ensureMonitorPanel(e,t,n){t.addedToResizeObserver||(this.resizeObserver.observe(e),t.addedToResizeObserver=!0);const s=this.rootRect,r=s.top-n.top,o=s.left-n.left,a=n.right-s.right,l=n.bottom-s.bottom,c=`${r}px ${a}px ${l}px ${o}px`;t.intersectionObserverMargin!==c&&(t.intersectionObserverMargin=c,t.intersectionObserver?.disconnect(),(t.intersectionObserver=new IntersectionObserver(this.resizeCallback,{root:this.container,rootMargin:c,threshold:[.93,.94,.95,.96,.97,.98,.99,1]})).observe(e))}unmonitorPanel(e,t){t.addedToResizeObserver&&this.resizeObserver.unobserve(e),t.intersectionObserver?.disconnect()}flagContinuousCameraMotion(){this.continuousCameraMotionInProgress||this.continuousCameraMotionStarted.dispatch(),this.continuousCameraMotionInProgress=!0,this.debouncedEndContinuousCameraMotion()}get isContinuousCameraMotionInProgress(){return this.continuousCameraMotionInProgress}applyWindowedViewportToElement(e,t){const[n,s,r,o]=t,a=1/r,l=1/o;e.style.position="absolute",e.style.top=`${-l*s*100}%`,e.style.left=`${-a*n*100}%`,e.style.width=`${a*100}%`,e.style.height=`${l*100}%`,++this.resizeGeneration,this.scheduleRedraw()}isReady(){for(const e of this.panels)if(e.visible&&!e.isReady())return!1;return!0}makeCanvasOverlayElement(){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.width="100%",e.style.height="100%",e.style.zIndex="2",this.container.appendChild(e),e}disposed(){this.orderedPanels.length=0,this.resizeObserver.disconnect()}addPanel(e){this.panels.add(e),this.orderedPanels.length=0,++this.resizeGeneration,this.scheduleRedraw()}removePanel(e){this.panels.delete(e),this.orderedPanels.length=0,++this.resizeGeneration,this.scheduleRedraw()}ensureBoundsUpdated(){const{resizeGeneration:e}=this;if(this.boundsGeneration===e)return;const{canvas:t}=this;t.width=t.offsetWidth,t.height=t.offsetHeight,this.canvasRect=t.getBoundingClientRect(),this.rootRect=this.container.getBoundingClientRect(),this.boundsGeneration=e}draw(){++this.frameNumber,this.updateStarted.dispatch();const e=this.gl,t=this.framerateMonitor.getTimingExtension(e),n=this.framerateMonitor.startFrameTimeQuery(e,t);this.ensureBoundsUpdated(),this.gl.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT);const{orderedPanels:s,panels:r}=this;s.length!==r.size&&(s.push(...r),s.sort((o,a)=>o.drawOrder-a.drawOrder));for(const o of s){if(!o.shouldDraw)continue;o.ensureBoundsUpdated();const{renderViewport:a}=o;a.width===0||a.height===0||o.draw()}e.disable(e.SCISSOR_TEST),this.gl.clearColor(1,1,1,1),this.gl.colorMask(!1,!1,!1,!0),e.clear(e.COLOR_BUFFER_BIT),this.gl.colorMask(!0,!0,!0,!0),this.updateFinished.dispatch(),this.framerateMonitor.endFrameTimeQuery(e,t,n),this.framerateMonitor.grabAnyFinishedQueryResults(e)}getDepthArray(){const{width:e,height:t}=this.canvas,n=new Float32Array(e*t);for(const s of this.panels){if(!s.shouldDraw)continue;const r=s.getDepthArray();if(r===void 0)continue;const{canvasRelativeClippedTop:o,canvasRelativeClippedLeft:a,renderViewport:{width:l,height:c}}=s;for(let d=0;d<c;++d){const u=(c-1-d)*l;n.set(r.subarray(u,u+l),(o+d)*l+a)}}return n}getLastFrameTimesInMs(e=10){return this.framerateMonitor.getLastFrameTimesInMs(e)}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ep extends Hl{constructor(){super(...arguments),this.globalPosition=rs,this.projectionMat=w.pB.create(),this.viewMatrix=w.pB.create(),this.invViewMatrix=w.pB.create(),this.viewProjectionMat=w.pB.create(),this.invViewProjectionMat=w.pB.create()}}function _w(i,e){return i.displayDimensionRenderInfo===e.displayDimensionRenderInfo&&Xh(i,e)&&(0,z.r1)(i.globalPosition,e.globalPosition)&&(0,z.r1)(i.projectionMat,e.projectionMat)&&(0,z.r1)(i.viewMatrix,e.viewMatrix)}function tp(i){const{viewMatrix:e,viewProjectionMat:t}=i;w.pB.invert(e,i.invViewMatrix),w.pB.multiply(t,i.projectionMat,e),w.pB.invert(i.invViewProjectionMat,t)}var co=G(3517);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var xn=(i=>(i[i.info=0]="info",i[i.warning=1]="warning",i[i.error=2]="error",i))(xn||{});class d_{}class Di{constructor(){this.changed=new j.IY,this.messages=[],this.children=[]}addMessage(e){this.messages.push(e),this.changed.dispatch()}clearMessages(){const{messages:e}=this;e.length!==0&&(e.length=0,this.changed.dispatch())}isEmpty(){return this.messages.length===0&&!this.children.some(e=>!e.isEmpty())}addChild(e){return this.children.push(e),e.changed.add(this.changed.dispatch),e.isEmpty()||this.changed.dispatch(),()=>{const{children:t}=this;t.splice(t.indexOf(e),1),e.changed.remove(this.changed.dispatch),e.isEmpty()||this.changed.dispatch()}}*[Symbol.iterator](){yield*this.messages;for(const e of this.children)yield*e}}var at=G(4509);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const uo=!(typeof Window<"u"&&self instanceof Window),np=!1,ip=!1,jl="rpc.promise.response",sp="rpc.promise.cancel",rp="rpc.ready",op=new Map;function dt(i,e){op.set(i,e)}class Bw extends Error{constructor(e,t){super(t),this.name=e,this.message=t}}function ap(i,e){dt(i,function(t){const n=t.id,s=new at.Qi,r=e.call(this,t,s);this.set(n,{promise:r,cancellationToken:s}),r.then(({value:o,transfers:a})=>{this.delete(n),this.invoke(jl,{id:n,value:o},a)},o=>{this.delete(n),this.invoke(jl,{id:n,error:o.message,errorName:o.name})})})}dt(sp,function(i){const e=i.id,t=this.get(e);if(t!==void 0){const{cancellationToken:n}=t;n.cancel()}}),dt(jl,function(i){const e=i.id,{resolve:t,reject:n}=this.get(e);this.delete(e),Object.prototype.hasOwnProperty.call(i,"value")?t(i.value):i.errorName===at.wS.name?n(at.wS):n(new Bw(i.errorName,i.error))}),dt(rp,function(i){this.onPeerReady()});const Fw=uo?-1:0;class Uw{constructor(e,t){this.target=e,this.objects=new Map,this.nextId=Fw,t&&(this.queue=[]),e.onmessage=n=>{const s=n.data;ip&&console.log("Received message",s),op.get(s.functionName).call(this,s)}}sendReady(){this.invoke(rp,{})}onPeerReady(){const{queue:e}=this;if(e!==void 0){this.queue=void 0;for(const{data:t,transfers:n}of e)this.target.postMessage(t,n)}}get numObjects(){return this.objects.size}set(e,t){this.objects.set(e,t)}delete(e){this.objects.delete(e)}get(e){return this.objects.get(e)}getRef(e){const t=e.id,n=this.get(t);return n.referencedGeneration=e.gen,n.addRef(),n}getOptionalRef(e){if(e===void 0)return;const t=e.id,n=this.get(t);return n.referencedGeneration=e.gen,n.addRef(),n}invoke(e,t,n){t.functionName=e,ip&&console.trace("Sending message",t);const{queue:s}=this;if(s!==void 0){s.push({data:t,transfers:n});return}this.target.postMessage(t,n)}promiseInvoke(e,t,n=at.fx,s){return(0,at.gI)(n,(r,o,a)=>{const l=t.id=this.newId();this.set(l,{resolve:r,reject:o}),this.invoke(e,t,s),a.add(()=>{this.invoke(sp,{id:l})})})}newId(){return uo?this.nextId--:this.nextId++}}class un extends D.O8{constructor(){super(...arguments),this.rpc=null,this.rpcId=null}initializeSharedObject(e,t=e.newId()){this.rpc=e,this.rpcId=t,this.isOwner=!1,e.set(t,this)}initializeCounterpart(e,t={}){this.initializeSharedObject(e),this.unreferencedGeneration=0,this.referencedGeneration=0,this.isOwner=!0,t.id=this.rpcId,t.type=this.RPC_TYPE_ID,e.invoke("SharedObject.new",t)}dispose(){super.dispose()}addCounterpartRef(){return{id:this.rpcId,gen:++this.referencedGeneration}}refCountReachedZero(){this.isOwner===!0?this.referencedGeneration===this.unreferencedGeneration&&this.ownerDispose():this.isOwner===!1?this.rpc.invoke("SharedObject.refCountReachedZero",{id:this.rpcId,gen:this.referencedGeneration}):super.refCountReachedZero()}ownerDispose(){np&&console.log(`[${uo}] #rpc object = ${this.rpc.numObjects}`);const{rpc:e,rpcId:t}=this;super.refCountReachedZero(),e.delete(t),e.invoke("SharedObject.dispose",{id:t})}counterpartRefCountReachedZero(e){this.unreferencedGeneration=e,this.refCount===0&&e===this.referencedGeneration&&this.ownerDispose()}}function $w(i,e,t={}){e!=null&&i.initializeSharedObject(e,t.id)}class ho extends un{constructor(e,t={}){super(),$w(this,e,t)}}dt("SharedObject.dispose",function(i){const e=this.get(i.id);if(e.refCount!==0)throw new Error("Attempted to dispose object with non-zero reference count.");np&&console.log(`[${uo}] #rpc objects: ${this.numObjects}`),e.disposed(),this.delete(e.rpcId),e.rpcId=null,e.rpc=null}),dt("SharedObject.refCountReachedZero",function(i){const e=this.get(i.id),t=i.gen;e.counterpartRefCountReachedZero(t)});const lp=new Map;function Kt(i){return e=>{e.prototype.RPC_TYPE_ID=i}}function po(i){return e=>{if(i!==void 0)e.prototype.RPC_TYPE_ID=i;else if(i=e.prototype.RPC_TYPE_ID,i===void 0)throw new Error("RPC_TYPE_ID should have already been defined");lp.set(i,e)}}dt("SharedObject.new",function(i){const e=this,t=i.type,n=lp.get(t),s=new n(e,i);--s.refCount});var Gw=Object.defineProperty,zw=Object.getOwnPropertyDescriptor,Ww=(i,e,t,n)=>{for(var s=n>1?void 0:n?zw(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&Gw(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const cp="SharedWatchableValue.changed";let ut=class extends ho{constructor(i,e={}){super(i,e),this.updatingValue_=!1,i!==void 0&&(this.base=new A.B0(e.value),this.setupChangedHandler())}initializeCounterpart(i,e={}){e.value=this.value,super.initializeCounterpart(i,e)}setupChangedHandler(){this.registerDisposer(this.base.changed.add(()=>{if(this.updatingValue_)this.updatingValue_=!1;else{const{rpc:i}=this;i!==null&&i.invoke(cp,{id:this.rpcId,value:this.value})}}))}static makeFromExisting(i,e){const t=new ut;return t.base=e,t.setupChangedHandler(),t.initializeCounterpart(i),t}static make(i,e){return ut.makeFromExisting(i,new A.B0(e))}get value(){return this.base.value}set value(i){this.base.value=i}get changed(){return this.base.changed}};ut=Ww([po("SharedWatchableValue")],ut),dt(cp,function(i){const e=this.get(i.id);e.updatingValue_=!0,e.base.value=i.value,e.updatingValue_=!1});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ht extends A.B0{constructor(e=Number.NEGATIVE_INFINITY){super(e)}get visible(){return this.value===Number.POSITIVE_INFINITY}get ignored(){return this.value===Number.NEGATIVE_INFINITY}}ht.VISIBLE=Number.POSITIVE_INFINITY,ht.IGNORED=Number.NEGATIVE_INFINITY;class nr extends ht{constructor(){super(...arguments),this.contributors=new Map}add(e){const{contributors:t}=this,n=e.changed.add(()=>{this.update()}),s=()=>{t.delete(s),n(),this.update()};return t.set(s,e),this.update(),s}update(){let e=Number.NEGATIVE_INFINITY;for(const t of this.contributors.values())e=Math.max(e,t.value);this.value=e}}function ir(i){return class extends i{constructor(){super(...arguments),this.visibility=new nr}initializeCounterpart(e,t={}){t.visibility=this.registerDisposer(ut.makeFromExisting(e,this.visibility)).rpcId,super.initializeCounterpart(e,t)}}}var Hw=Object.defineProperty,Jw=Object.getOwnPropertyDescriptor,jw=(i,e,t,n)=>{for(var s=n>1?void 0:n?Jw(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&Hw(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var si=(i=>(i[i.DATA=0]="DATA",i[i.ANNOTATION=1]="ANNOTATION",i[i.DEFAULT_ANNOTATION=2]="DEFAULT_ANNOTATION",i))(si||{});function Yw(){return new A._Y([0,1,2])}class dp extends D.O8{constructor(){super(...arguments),this.role=0,this.messages=new Di,this.layerChanged=new j.IY,this.redrawNeeded=new j.IY,this.layerChunkProgressInfo=new lo}handleAction(e){}getValueAt(e){}transformPickedValue(e){return e.pickedValue}updateMouseState(e,t,n,s){}}class up extends dp{constructor(){super(...arguments),this.visibility=new nr}attach(e){}}function sr(i,e,t){let{state:n}=t;if(n===void 0||n.transform!==i||n.displayDimensionRenderInfo!==e){if(t.messages.clearMessages(),n=t.state={transform:i,displayDimensionRenderInfo:e,modelTransform:void 0},i.error!==void 0){t.messages.addMessage({severity:xn.error,message:i.error});return}try{const s=w.pB.create();Tw(s,e,i),n.modelTransform=s}catch(s){t.messages.addMessage({severity:xn.error,message:s.message})}}return n.modelTransform}class hp extends D.O8{constructor(e){super(),this.renderViewport=new Hl,this.changed=new j.HN;const{parametersConstructor:t=ep,navigationState:n,update:s,isEqual:r=_w}=e;this.oldValue_=new t,this.value_=new t;const o=()=>{const{oldValue_:l,value_:c}=this;l.displayDimensionRenderInfo=n.displayDimensionRenderInfo.value,Object.assign(l,this.renderViewport);let{globalPosition:d}=l;const u=n.position.value,h=u.length;d.length!==h&&(l.globalPosition=d=new Float32Array(h)),d.set(u),s(l,n),!r(l,c)&&(this.value_=l,this.oldValue_=c,this.changed.dispatch(c,l))},a=this.update=this.registerCancellable((0,xe.A)(o,0));this.registerDisposer(n.changed.add(a)),o()}setViewport(e){Xh(e,this.renderViewport)||(Object.assign(this.renderViewport,e),this.update())}get value(){return this.update.flush(),this.value_}}let fo=class extends un{constructor(i,e,t=10){super(),this.base=e,this.updateInterval=t,this.prevDisplayDimensionRenderInfo=void 0,this.update=this.registerCancellable((0,xe.A)((n,s)=>{let r;if(s.displayDimensionRenderInfo!==this.prevDisplayDimensionRenderInfo)r=s,this.prevDisplayDimensionRenderInfo=s.displayDimensionRenderInfo;else{const{displayDimensionRenderInfo:o,...a}=s;r=a}this.rpc.invoke(co.kg,{id:this.rpcId,value:r})},this.updateInterval)),this.initializeCounterpart(i,{value:e.value}),this.registerDisposer(e.changed.add(this.update))}flush(){this.update.flush()}};fo=jw([Kt(co.Bh)],fo);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class rt{constructor(e,t=e){this.value_=e,this.defaultValue=t,this.changed=new j.IY}get value(){return this.value_}set value(e){e!==this.value_&&(this.value_=e,this.changed.dispatch())}toggle(){this.value=!this.value}toJSON(){const{value_:e}=this;if(e!==this.defaultValue)return this.value_}restoreState(e){if(e===!0||e===!1){this.value=e;return}this.value=this.defaultValue}reset(){this.value=this.defaultValue}}class Un extends D.O8{constructor(e,t={}){super(),this.model=e,this.element=document.createElement("input");const{element:n}=this;n.type="checkbox";const s=()=>{const r=this.model.value;this.element.checked=r,(t.enableTitle!==void 0||t.disableTitle!==void 0)&&(this.element.title=(r?t.enableTitle:t.disableTitle)??"")};this.registerDisposer(e.changed.add(s)),s(),this.registerEventListener(n,"change",function(r){e.value=this.checked}),n.addEventListener("mousedown",r=>{r.preventDefault()})}disposed(){const{element:e}=this,{parentElement:t}=e;t&&t.removeChild(e),super.disposed()}}class Xt extends D.O8{constructor(e,t){super(),this.model=e,this.element=t,this.initialDisplay=this.element.style.display,this.updateVisibility(),this.registerDisposer(e.changed.add(this.registerCancellable((0,xe.A)(()=>this.updateVisibility(),0))))}updateVisibility(){this.element.style.display=this.model.value?this.initialDisplay:"none"}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function go(i){try{return i()}catch(e){return{error:e.message}}}function rr(i){if(i.error!==void 0)throw new Error(i.error);return i}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Yl extends D.O8{constructor(e,t){if(super(),this.register=e,this.changed=new j.IY,this.disposerMap=new Map,t===void 0)this.map=new Map;else{const n=this.map=new Map(t),{disposerMap:s}=this;for(const[r,o]of n){const a=new D.O8;s.set(r,a),e(a,o,r)}}}get value(){return this.map}set(e,t){const{map:n,disposerMap:s}=this;let r=s.get(e);return r!==void 0&&r.dispose(),r=new D.O8,s.set(e,r),n.set(e,t),this.register(r,t,e),this.changed.dispatch(),this}delete(e){const{map:t,disposerMap:n}=this,s=n.get(e);return s!==void 0?(s.dispose(),n.delete(e),t.delete(e),this.changed.dispatch(),!0):!1}get(e){return this.map.get(e)}has(e){return this.map.has(e)}get size(){return this.map.size}[Symbol.iterator](){return this.map[Symbol.iterator]()}clear(){const{map:e,disposerMap:t}=this;if(e.size>0){for(const n of t.values())n.dispose();e.clear(),t.clear(),this.changed.dispatch()}}values(){return this.map.values()}keys(){return this.map.keys()}disposed(){const{map:e,disposerMap:t}=this;for(const n of t.values())n.dispose();e.clear(),t.clear(),super.disposed()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const pp=Symbol("objectId");let Qw=0;function St(i){if(i instanceof Object){let e=i[pp];return e===void 0&&(e=i[pp]=Qw++),`o${e}`}return""+JSON.stringify(i)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Ql=!1;var fp=(i=>(i[i.VERTEX=WebGL2RenderingContext.VERTEX_SHADER]="VERTEX",i[i.FRAGMENT=WebGL2RenderingContext.FRAGMENT_SHADER]="FRAGMENT",i))(fp||{});function qw(i){i=i.replace("\0","");const e=[];for(let t of i.split(`
`)){let n=t.match(/^ERROR:\s*(\d+):(\d+)\s*(.+)$/);n!==null?e.push({message:n[3].trim(),file:parseInt(n[1],10),line:parseInt(n[2],10)}):(n=t.match(/^ERROR:\s*(.+)$/),n!==null?e.push({message:n[1]}):(t=t.trim(),t&&e.push({message:t})))}return e}class Kw extends Error{constructor(e,t,n,s){const r=`Error compiling ${fp[e].toLowerCase()} shader: ${n}`;super(r),this.name="ShaderCompilationError",this.log=n,this.message=r,this.shaderType=e,this.source=t,this.errorMessages=s}}class Xw extends Error{constructor(e,t,n){const s=`Error linking shader: ${n}`;super(s),this.name="ShaderLinkError",this.log=n,this.message=s,this.vertexSource=e,this.fragmentSource=t}}function gp(i,e,t){const n=i.createShader(t);if(i.shaderSource(n,e),i.compileShader(n),!i.getShaderParameter(n,i.COMPILE_STATUS)){const s=i.getShaderInfoLog(n)||"";if(Ql){const r=e.replace("<","&lt;").replace(">","&gt;").split(`
`);let o="<pre>";o+=s.replace("<","&lt;").replace(">","&gt;")+`
`,r.forEach((l,c)=>{o+=`${c+1}: ${l}
`}),o+=`
</pre>`,console.log(o);const a=window.open("about:blank","_blank");if(a!==null)try{a.document.write(o)}catch{}}throw new Kw(t,e,s,qw(s))}return n}let ql;class Zw extends D.O8{constructor(e,t,n,s,r,o){super(),this.gl=e,this.vertexSource=t,this.fragmentSource=n,this.attributes=new Map,this.uniforms=new Map,this.vertexShaderInputBinders={},this.transferFunctionTextures=new Map;const a=this.vertexShader=gp(e,t,e.VERTEX_SHADER),l=this.fragmentShader=gp(e,n,e.FRAGMENT_SHADER),c=e.createProgram();if(e.attachShader(c,a),e.attachShader(c,l),Ql&&o?.length&&(e.transformFeedbackVaryings(c,o.map(h=>h.name),WebGL2RenderingContext.INTERLEAVED_ATTRIBS),this.vertexDebugOutputs=o),e.linkProgram(c),!e.getProgramParameter(c,e.LINK_STATUS)){const h=e.getProgramInfoLog(c)||"";throw new Xw(t,n,h)}this.program=c;const{uniforms:d,attributes:u}=this;if(s)for(const h of s)d.set(h,e.getUniformLocation(c,h));if(r)for(const h of r)u.set(h,e.getAttribLocation(c,h))}uniform(e){return this.uniforms.get(e)}attribute(e){return this.attributes.get(e)}textureUnit(e){return this.textureUnits.get(e)}bind(){ql=this,this.gl.useProgram(this.program)}bindAndUpdateTransferFunctionTexture(e,t,n,s){const r=this.textureUnits.get(e);if(r===void 0)throw new Error(`Invalid texture unit symbol: ${e.toString()}`);const o=this.transferFunctionTextures.get(e);if(o===void 0)throw new Error(`Invalid transfer function texture symbol: ${e.toString()}`);return o.updateAndActivate({textureUnit:r,sortedControlPoints:t,dataType:n,lookupTableSize:s})}unbindTransferFunctionTextures(){const e=this.gl;for(const t of this.transferFunctionTextures.keys()){const n=this.textureUnits.get(t);n!==void 0&&(this.gl.activeTexture(e.TEXTURE0+n),this.gl.bindTexture(e.TEXTURE_2D,null))}}disposed(){const{gl:e}=this;e.deleteShader(this.vertexShader),this.vertexShader=void 0,e.deleteShader(this.fragmentShader),this.fragmentShader=void 0,e.deleteProgram(this.program),this.program=void 0,this.gl=void 0,this.attributes=void 0,this.uniforms=void 0,this.transferFunctionTextures=void 0}}function eC(i,e,t,n,s){if(i.drawArraysInstanced(e,t,n,s),!Ql||!ql?.vertexDebugOutputs)return;const{vertexDebugOutputs:r}=ql;let o=0;for(const h of r)o+=tC[h.typeName];const a=i.createBuffer(),l=o*n*s;i.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,a),i.bufferData(WebGL2RenderingContext.ARRAY_BUFFER,l,WebGL2RenderingContext.DYNAMIC_DRAW),i.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,null),i.bindBufferBase(WebGL2RenderingContext.TRANSFORM_FEEDBACK_BUFFER,0,a),i.beginTransformFeedback(WebGL2RenderingContext.POINTS),i.enable(WebGL2RenderingContext.RASTERIZER_DISCARD),i.drawArraysInstanced(WebGL2RenderingContext.POINTS,t,n,s),i.disable(WebGL2RenderingContext.RASTERIZER_DISCARD),i.endTransformFeedback(),i.bindBufferBase(WebGL2RenderingContext.TRANSFORM_FEEDBACK_BUFFER,0,null),i.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,a);const c=new Uint8Array(l);i.getBufferSubData(WebGL2RenderingContext.ARRAY_BUFFER,0,c,0,l),i.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,null),i.deleteBuffer(a);let d=0;const u=new Float32Array(c.buffer);for(let h=0;h<s;++h)for(let f=0;f<n;++f){let m=`i=${h} v=${f}:`;for(const g of r)switch(m+=` ${g.name}=`,g.typeName){case"float":m+=`${u[d++]}`;break;case"vec2":m+=`${u[d++]},${u[d++]}`;break;case"vec3":m+=`${u[d++]},${u[d++]},${u[d++]}`;break;case"vec4":m+=`${u[d++]},${u[d++]},${u[d++]},${u[d++]}`;break}console.log(m)}}class mp{constructor(){this.code="",this.parts=new Set}add(e){if(!this.parts.has(e))switch(this.parts.add(e),typeof e){case"string":this.code+=e;break;case"function":this.add(e());break;default:if(Array.isArray(e))for(const t of e)this.add(t);else throw console.log("Invalid code type",e),new Error("Invalid code type")}}toString(){return this.code}}const or={sampler2D:WebGL2RenderingContext.TEXTURE_2D,isampler2D:WebGL2RenderingContext.TEXTURE_2D,usampler2D:WebGL2RenderingContext.TEXTURE_2D,sampler3D:WebGL2RenderingContext.TEXTURE_3D,isampler3D:WebGL2RenderingContext.TEXTURE_3D,usampler3D:WebGL2RenderingContext.TEXTURE_3D},tC={float:4,vec2:8,vec3:12,vec4:16};class hn{constructor(e){this.gl=e,this.nextSymbolID=0,this.nextTextureUnit=0,this.uniformsCode="",this.attributesCode="",this.varyingsCodeVS="",this.varyingsCodeFS="",this.fragmentExtensionsSet=new Set,this.fragmentExtensions="",this.vertexCode=new mp,this.vertexMain="",this.fragmentCode=new mp,this.outputBufferCode="",this.fragmentMain="",this.required=new Set,this.uniforms=new Array,this.attributes=new Array,this.initializers=[],this.textureUnits=new Map,this.vertexDebugOutputs=[]}addVertexPositionDebugOutput(){this.vertexDebugOutputs.push({typeName:"vec4",name:"gl_Position"})}addVertexDebugOutput(e,t){this.addVarying(e,t),this.vertexDebugOutputs.push({typeName:e,name:t})}allocateTextureUnit(e,t=1){if(this.textureUnits.has(e))throw new Error("Duplicate texture unit symbol: "+e.toString());const n=this.nextTextureUnit;return this.nextTextureUnit+=t,this.textureUnits.set(e,n),n}addTextureSampler(e,t,n,s){const r=this.allocateTextureUnit(n,s);return this.addUniform(`highp ${e}`,t,s),this.addInitializer(o=>{if(s){const a=new Int32Array(s);for(let l=0;l<s;++l)a[l]=l+r;o.gl.uniform1iv(o.uniform(t),a)}else o.gl.uniform1i(o.uniform(t),r)}),r}symbol(e){return e+this.nextSymbolID++}addAttribute(e,t,n){return this.attributes.push(t),n!==void 0&&(this.attributesCode+=`layout(location = ${n})`),this.attributesCode+=`in ${e} ${t};
`,t}addVarying(e,t,n=""){this.varyingsCodeVS+=`${n} out ${e} ${t};
`,this.varyingsCodeFS+=`${n} in ${e} ${t};
`}addOutputBuffer(e,t,n){n!==null&&(this.outputBufferCode+=`layout(location = ${n}) `),this.outputBufferCode+=`out ${e} ${t};
`}addUniform(e,t,n){return this.uniforms.push(t),n!=null?this.uniformsCode+=`uniform ${e} ${t}[${n}];
`:this.uniformsCode+=`uniform ${e} ${t};
`,t}addFragmentExtension(e){this.fragmentExtensionsSet.has(e)||(this.fragmentExtensionsSet.add(e),this.fragmentExtensions+=`#extension ${e} : require
`)}addVertexCode(e){this.vertexCode.add(e)}addFragmentCode(e){this.fragmentCode.add(e)}setVertexMain(e){this.vertexMain=e}addVertexMain(e){this.vertexMain=(this.vertexMain||"")+e}setFragmentMain(e){this.fragmentMain=`void main() {
${e}
}
`}setFragmentMainFunction(e){this.fragmentMain=e}addInitializer(e){this.initializers.push(e)}require(e){this.required.has(e)||(this.required.add(e),e(this))}build(){const e=`#version 300 es
precision highp float;
precision highp int;
${this.uniformsCode}
${this.attributesCode}
${this.varyingsCodeVS}
float defaultMaxProjectionIntensity = 0.0;
${this.vertexCode}
void main() {
${this.vertexMain}
}
`,t=`#version 300 es
${this.fragmentExtensions}
precision highp float;
precision highp int;
${this.uniformsCode}
${this.varyingsCodeFS}
${this.outputBufferCode}
float defaultMaxProjectionIntensity = 0.0;
${this.fragmentCode}
${this.fragmentMain}
`,n=new Zw(this.gl,e,t,this.uniforms,this.attributes,this.vertexDebugOutputs);n.textureUnits=this.textureUnits;const{initializers:s}=this;if(s.length>0){n.bind();for(const r of s)r(n)}return n}}function u_(i,e){const t=new Set;for(const n of e){const s=new RegExp(`(?:^|[^a-zA-Z0-9_])${n}[^a-zA-Z0-9_])`);i.match(s)!==null&&t.add(n)}return t}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ar(){return new A.B0(void 0)}function mo(i){return new A.DN(i,p.zr)}function vo(i,e,t){const n=new Map,{parameters:s,fallbackParameters:r,shaderError:o,encodeParameters:a=v=>v,extraParameters:l=(0,A.XZ)(void 0),encodeExtraParameters:c=v=>v,getContextKey:d,defineShader:u}=t;o!==void 0&&(o.value=void 0);const{encodeContext:h=d}=t,f=(0,p.JB)(t.memoizeKey);function m(v,y,S){const x=JSON.stringify({id:f,context:h(v),parameters:a(y),extraParameters:c(S)});return e.memoize.get(x,()=>{const b=new hn(e);return u(b,v,y,S),b.build()})}function g(v){const y=d(v);let S=n.get(y);S===void 0&&(S={parametersGeneration:-1,extraParametersGeneration:-1,shader:null,fallback:!1,parameters:s.value,extraParameters:l.value},n.set(y,S));const x=s.changed.count,b=l.changed.count;if(x===S.parametersGeneration&&b===S.extraParametersGeneration)return S;const E=S.parameters=s.value,C=S.extraParameters=l.value,k=S.shader;S.parametersGeneration=x,S.extraParametersGeneration=b;let T=null;try{T=m(v,E,C),S.fallback=!1,r!==void 0&&(r.value=E),o!==void 0&&(o.value=null)}catch(L){if(o!==void 0&&(o.value=L),r!==void 0)try{const _=r.value;T=m(v,_,C),S.parameters=_,S.fallback=!0}catch{}}return k!==null&&k.dispose(),S.shader=T,S}return i.registerDisposer(()=>{for(const v of n.values()){const{shader:y}=v;y!==null&&y.dispose()}}),g}function Ii(i,e,t){return vo(i,e,{...t,getContextKey:n=>n,encodeContext:n=>St(n),defineShader:(n,s,r,o)=>(n.require(s),t.defineShader(n,r,o))})}function ls(i,e=1,t=0){return`
#line ${t} ${e}
`+i}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class At{constructor(e,t=WebGL2RenderingContext.ARRAY_BUFFER){this.gl=e,this.bufferType=t,this.gl=e,this.buffer=e.createBuffer()}bind(){this.gl.bindBuffer(this.bufferType,this.buffer)}bindToVertexAttrib(e,t,n=WebGL2RenderingContext.FLOAT,s=!1,r=0,o=0){this.bind(),this.gl.enableVertexAttribArray(e),this.gl.vertexAttribPointer(e,t,n,s,r,o)}bindToVertexAttribI(e,t,n=WebGL2RenderingContext.UNSIGNED_INT,s=0,r=0){this.bind(),this.gl.enableVertexAttribArray(e),this.gl.vertexAttribIPointer(e,t,n,s,r)}setData(e,t=WebGL2RenderingContext.STATIC_DRAW){const n=this.gl;this.bind(),n.bufferData(this.bufferType,e,t)}dispose(){this.gl.deleteBuffer(this.buffer),this.buffer=void 0,this.gl=void 0}static fromData(e,t,n,s){const r=new At(e,n);return r.setData(t,s),r}}function Ri(i,e,t,...n){return i.memoize.get((0,p.JB)({id:"getMemoizedBuffer",getter:St(t),args:n}),()=>{const s=new D.fL(At.fromData(i,t(...n),e,WebGL2RenderingContext.STATIC_DRAW));return s.registerDisposer(s.value),s})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function nC(i=-1,e=-1,t=1,n=1,s=1,r=1){return(0,z.CS)(new Float32Array([i,e,i,n,t,n,t,e]),2,s,r)}function h_(i=-1,e=-1,t=-1,n=1,s=1,r=1,o=1,a=1){return tile2dArray(new Float32Array([i,e,t,n,e,t,i,s,t,n,s,t,i,e,r,n,e,r,i,s,r,n,s,r]),3,o,a)}function lr(i,e=-1,t=-1,n=1,s=1,r=1,o=1){return Ri(i,WebGL2RenderingContext.ARRAY_BUFFER,nC,e,t,n,s,r,o).value}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ki(i){i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_MIN_FILTER,WebGL2RenderingContext.NEAREST),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_MAG_FILTER,WebGL2RenderingContext.NEAREST),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_WRAP_S,WebGL2RenderingContext.CLAMP_TO_EDGE),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_WRAP_T,WebGL2RenderingContext.CLAMP_TO_EDGE)}function iC(i){i.texParameteri(WebGL2RenderingContext.TEXTURE_3D,WebGL2RenderingContext.TEXTURE_MIN_FILTER,WebGL2RenderingContext.NEAREST),i.texParameteri(WebGL2RenderingContext.TEXTURE_3D,WebGL2RenderingContext.TEXTURE_MAG_FILTER,WebGL2RenderingContext.NEAREST),i.texParameteri(WebGL2RenderingContext.TEXTURE_3D,WebGL2RenderingContext.TEXTURE_WRAP_S,WebGL2RenderingContext.CLAMP_TO_EDGE),i.texParameteri(WebGL2RenderingContext.TEXTURE_3D,WebGL2RenderingContext.TEXTURE_WRAP_T,WebGL2RenderingContext.CLAMP_TO_EDGE),i.texParameteri(WebGL2RenderingContext.TEXTURE_3D,WebGL2RenderingContext.TEXTURE_WRAP_R,WebGL2RenderingContext.CLAMP_TO_EDGE)}function sC(i,e,t,n,s=WebGL2RenderingContext.RGBA8,r=WebGL2RenderingContext.RGBA,o=WebGL2RenderingContext.UNSIGNED_BYTE){i.activeTexture(WebGL2RenderingContext.TEXTURE0+i.tempTextureUnit),i.bindTexture(WebGL2RenderingContext.TEXTURE_2D,e),ki(i),i.texImage2D(WebGL2RenderingContext.TEXTURE_2D,0,s,t,n,0,r,o,null),i.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}function rC(i,e,t){i.activeTexture(WebGL2RenderingContext.TEXTURE0+i.tempTextureUnit),i.bindTexture(WebGL2RenderingContext.TEXTURE_2D,e),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_MIN_FILTER,WebGL2RenderingContext.LINEAR),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_MAG_FILTER,WebGL2RenderingContext.LINEAR),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_WRAP_S,WebGL2RenderingContext.CLAMP_TO_EDGE),i.texParameteri(WebGL2RenderingContext.TEXTURE_2D,WebGL2RenderingContext.TEXTURE_WRAP_T,WebGL2RenderingContext.CLAMP_TO_EDGE),i.pixelStorei(WebGL2RenderingContext.UNPACK_FLIP_Y_WEBGL,1),i.pixelStorei(WebGL2RenderingContext.UNPACK_ALIGNMENT,4),i.texImage2D(WebGL2RenderingContext.TEXTURE_2D,0,WebGL2RenderingContext.RGBA8,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.UNSIGNED_BYTE,t),i.pixelStorei(WebGL2RenderingContext.UNPACK_FLIP_Y_WEBGL,0),i.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Kl(i){i.addOutputBuffer("vec4","v4f_fragColor",null),i.setFragmentMain("v4f_fragColor = getValue0();")}function vp(i,e=Kl,t=1){return i.memoize.get(`elementWiseTextureShader:${t}:${St(e)}`,()=>{const n=new hn(i);n.addVarying("vec2","vTexCoord"),n.addUniform("sampler2D","uSampler",t),n.addInitializer(s=>{const r=[];for(let o=0;o<t;++o)r[o]=o;i.uniform1iv(s.uniform("uSampler"),r)});for(let s=0;s<t;++s)n.addFragmentCode(`
vec4 getValue${s}() {
  return texture(uSampler[${s}], vTexCoord);
}
`);return n.addUniform("mat4","uProjectionMatrix"),n.require(e),n.addAttribute("vec4","aVertexPosition"),n.addAttribute("vec2","aTexCoord"),n.setVertexMain("vTexCoord = aTexCoord; gl_Position = uProjectionMatrix * aVertexPosition;"),n.build()})}function p_(i){return vp(i,Kl,1)}function oC(i){return i.memoize.get("trivialColorShader",()=>{const e=new hn(i);return e.addVarying("vec4","vColor"),e.addOutputBuffer("vec4","v4f_fragColor",null),e.setFragmentMain("v4f_fragColor = vColor;"),e.addAttribute("vec4","aVertexPosition"),e.addAttribute("vec4","aColor"),e.addUniform("mat4","uProjectionMatrix"),e.setVertexMain("vColor = aColor; gl_Position = uProjectionMatrix * aVertexPosition;"),e.build()})}function f_(i){return i.memoize.get("trivialUniformColorShader",()=>{const e=new ShaderBuilder(i);return e.addUniform("mat4","uProjectionMatrix"),e.addAttribute("vec4","aVertexPosition"),e.addUniform("vec4","uColor"),e.addOutputBuffer("vec4","v4f_fragColor",null),e.setFragmentMain("v4f_fragColor = uColor;"),e.setVertexMain("gl_Position = uProjectionMatrix * aVertexPosition;"),e.build()})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class yp extends D.O8{constructor(){super(...arguments),this.width=Number.NaN,this.height=Number.NaN}hasSize(e,t){return this.width===e&&this.height===t}resize(e,t){this.hasSize(e,t)||(this.width=e,this.height=t,this.performResize())}}class aC extends yp{constructor(e,t){super(),this.gl=e,this.internalformat=t,this.renderbuffer=null,this.renderbuffer=e.createRenderbuffer()}performResize(){const{gl:e}=this;e.bindRenderbuffer(e.RENDERBUFFER,this.renderbuffer),e.renderbufferStorage(e.RENDERBUFFER,this.internalformat,this.width,this.height),e.bindRenderbuffer(e.RENDERBUFFER,null)}disposed(){this.gl.deleteRenderbuffer(this.renderbuffer)}attachToFramebuffer(e){const{gl:t}=this;t.framebufferRenderbuffer(t.FRAMEBUFFER,e,t.RENDERBUFFER,this.renderbuffer)}}class lC extends aC{constructor(e,t=!1){super(e,t?e.DEPTH_STENCIL:e.DEPTH_COMPONENT16),this.gl=e,this.includeStencilBuffer=t}attachToFramebuffer(){const{gl:e}=this;super.attachToFramebuffer(this.includeStencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT)}}class yo extends lC{constructor(e){super(e,!0)}}const g_=null;class cC extends D.O8{constructor(e){super(),this.gl=e,this.framebuffer=this.gl.createFramebuffer()}disposed(){const{gl:e}=this;e.deleteFramebuffer(this.framebuffer)}bind(){const{gl:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer)}unbind(){const{gl:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,null)}}class pn extends yp{constructor(e,t,n,s){super(),this.gl=e,this.internalFormat=t,this.format=n,this.dataType=s,this.texture=e.createTexture()}performResize(){sC(this.gl,this.texture,this.width,this.height,this.internalFormat,this.format,this.dataType)}disposed(){this.gl.deleteTexture(this.texture)}attachToFramebuffer(e){const{gl:t}=this;t.framebufferTexture2D(t.FRAMEBUFFER,e,t.TEXTURE_2D,this.texture,0)}}class dC extends pn{constructor(e,t=WebGL2RenderingContext.DEPTH_COMPONENT16,n=WebGL2RenderingContext.DEPTH_COMPONENT,s=WebGL2RenderingContext.UNSIGNED_SHORT){super(e,t,n,s)}attachToFramebuffer(){super.attachToFramebuffer(this.format===WebGL2RenderingContext.DEPTH_COMPONENT?WebGL2RenderingContext.DEPTH_ATTACHMENT:WebGL2RenderingContext.DEPTH_STENCIL_ATTACHMENT)}}function cs(i,e,t=WebGL2RenderingContext.RGBA8,n=WebGL2RenderingContext.RGBA,s=WebGL2RenderingContext.UNSIGNED_BYTE){const r=new Array;for(let o=0;o<e;++o)r[o]=new pn(i,t,n,s);return r}class $n extends D.O8{constructor(e,t){super(),this.gl=e,this.width=Number.NaN,this.height=Number.NaN,this.fullAttachmentList=new Array,this.attachmentVerified=!1,this.singleAttachmentList=[this.gl.COLOR_ATTACHMENT0];const{framebuffer:n=new cC(e),colorBuffers:s,depthBuffer:r}=t;this.framebuffer=this.registerDisposer(n),this.colorBuffers=s,this.depthBuffer=r,r!==void 0&&this.registerDisposer(r);const{fullAttachmentList:o}=this;s.forEach((a,l)=>{this.registerDisposer(a),o[l]=e.COLOR_ATTACHMENT0+l})}hasSize(e,t){return this.width===e&&this.height===t}bind(e,t){this.width=e,this.height=t,this.framebuffer.bind();const{gl:n,depthBuffer:s}=this;s!==void 0?(s.resize(e,t),s.attachToFramebuffer()):n.framebufferRenderbuffer(WebGL2RenderingContext.FRAMEBUFFER,WebGL2RenderingContext.DEPTH_STENCIL_ATTACHMENT,WebGL2RenderingContext.RENDERBUFFER,null),this.colorBuffers.forEach((r,o)=>{r.resize(e,t),r.attachToFramebuffer(n.COLOR_ATTACHMENT0+o)}),n.drawBuffers(this.fullAttachmentList),this.verifyAttachment(),n.viewport(0,0,e,t)}bindSingle(e){const{gl:t}=this;this.framebuffer.bind(),e!==0&&t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0),t.bindTexture(t.TEXTURE_2D,null),this.colorBuffers[e].attachToFramebuffer(t.COLOR_ATTACHMENT0),t.drawBuffers(this.singleAttachmentList)}unbind(){this.framebuffer.unbind()}readPixelFloat32IntoBuffer(e,t,n,s,r=1,o=1){const{gl:a}=this;try{this.bindSingle(e),a.readPixels(t,n,r,o,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.FLOAT,s)}finally{this.framebuffer.unbind()}}verifyAttachment(){if(this.attachmentVerified)return;const{gl:e}=this,t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error(`Framebuffer configuration not supported: ${t}`);this.attachmentVerified=!0}}class En extends D.O8{constructor(e,t){super(),this.gl=e,this.shader=t,this.copyVertexPositionsBuffer=lr(this.gl),this.copyTexCoordsBuffer=lr(this.gl,0,0,1,1),this.registerDisposer(t)}draw(...e){const{gl:t,shader:n}=this;n.bind();const s=e.length;for(let a=0;a<s;++a)t.activeTexture(t.TEXTURE0+a),t.bindTexture(t.TEXTURE_2D,e[a]);t.uniformMatrix4fv(n.uniform("uProjectionMatrix"),!1,w.r3);const r=n.attribute("aVertexPosition");this.copyVertexPositionsBuffer.bindToVertexAttrib(r,2);const o=n.attribute("aTexCoord");this.copyTexCoordsBuffer.bindToVertexAttrib(o,2),t.drawArrays(t.TRIANGLE_FAN,0,4),t.disableVertexAttribArray(r),t.disableVertexAttribArray(o);for(let a=0;a<s;++a)t.activeTexture(t.TEXTURE0+a),t.bindTexture(t.TEXTURE_2D,null)}static get(e,t=Kl,n=1){return e.memoize.get(`OffscreenCopyHelper:${n}:${St(t)}`,()=>new En(e,vp(e,t,n)))}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const uC=`
float mixLinear(float x, float y, float a) { return mix(x, y, a); }
`,hC=`
vec3 hueToRgb(float hue) {
  float hue6 = hue * 6.0;
  float r = abs(hue6 - 3.0) - 1.0;
  float g = 2.0 - abs(hue6 - 2.0);
  float b = 2.0 - abs(hue6 - 4.0);
  return clamp(vec3(r, g, b), 0.0, 1.0);
}
vec3 hsvToRgb(vec3 c) {
  vec3 hueRgb = hueToRgb(c.x);
  return c.z * ((hueRgb - 1.0) * c.y + 1.0);
}
`,pt=`
struct uint64_t {
  highp uvec2 value;
};
struct uint64x2_t {
  highp uvec4 value;
};
uint64_t mixLinear(uint64_t x, uint64_t y, float a) {
  return x;
}
uint64_t toUint64(uint64_t x) { return x; }
`,pC=[pt,`
uint64_t unpackUint64leFromUint32(highp uvec2 x) {
  uint64_t result;
  result.value = x;
  return result;
}
uint64x2_t unpackUint64leFromUint32(highp uvec4 x) {
  uint64x2_t result;
  result.value = x;
  return result;
}
`],Sp=[pt,`
bool equals(uint64_t a, uint64_t b) {
  return a.value == b.value;
}
`],So=[pt,`
bool compareLessThan(uint64_t a, uint64_t b) {
  return (a.value[1] < b.value[1])||
         (a.value[1] == b.value[1] && a.value[0] < b.value[0]);
}
`],bp=[pt,`
uint64_t subtract(uint64_t a, uint64_t b) {
  if (a.value[0] < b.value[0]) {
    --a.value[1];
  }
  a.value -= b.value;
  return a;
}
`],fC=[[pt,`
uint64_t add(uint64_t a, uint64_t b) {
  a.value[0] += b.value[0];
  if (a.value[0] < b.value[0]) {
    ++a.value[1];
  }
  a.value[1] += b.value[1];
  return a;
}
`],So,`
uint64_t addSaturate(uint64_t a, uint64_t b) {
  a = add(a, b);
  if (compareLessThan(a, b)) {
    a.value = uvec2(0xffffffffu, 0xffffffffu);
  }
  return a;
}
`],gC=[bp,So,`
uint64_t subtractSaturate(uint64_t a, uint64_t b) {
  b = subtract(a, b);
  if (compareLessThan(a, b)) {
    b.value = uvec2(0u, 0u);
  }
  return b;
}
`],wp=[pt,`
uint64_t shiftRight(uint64_t a, int shift) {
  if (shift >= 32) {
    return uint64_t(uvec2(a.value[1] >> (shift - 32), 0u));
  } else if (shift == 0) {
    return a;
  } else {
    return uint64_t(uvec2((a.value[0] >> shift) | (a.value[1] << (32 - shift)), a.value[1] >> shift));
  }
}
`],mC=[pt,`
uint64_t shiftLeft(uint64_t a, int shift) {
  if (shift >= 32) {
    return uint64_t(uvec2(0u, a.value[0] << (shift - 32)));
  } else if (shift == 0) {
    return a;
  } else {
    return uint64_t(uvec2(a.value[0] << shift, (a.value[1] << shift) | (a.value[0] >> (32 - shift))));
  }
}
`],Cp=[pt,`
struct uint8_t {
  highp uint value;
};
struct uint8x2_t {
  highp uvec2 value;
};
struct uint8x3_t {
  highp uvec3 value;
};
struct uint8x4_t {
  highp uvec4 value;
};
uint8_t mixLinear(uint8_t x, uint8_t y, highp float a) {
  return uint8_t(uint(round(mix(float(x.value), float(y.value), a))));
}
highp uint toRaw(uint8_t x) { return x.value; }
highp float toNormalized(uint8_t x) { return float(x.value) / 255.0; }
highp uvec2 toRaw(uint8x2_t x) { return x.value; }
highp vec2 toNormalized(uint8x2_t x) { return vec2(x.value) / 255.0; }
highp uvec3 toRaw(uint8x3_t x) { return x.value; }
vec3 toNormalized(uint8x3_t x) { return vec3(x.value) / 255.0; }
highp uvec4 toRaw(uint8x4_t x) { return x.value; }
vec4 toNormalized(uint8x4_t x) { return vec4(x.value) / 255.0; }
uint64_t toUint64(uint8_t x) {
  uint64_t result;
  result.value[0] = x.value;
  result.value[1] = 0u;
  return result;
}
uint8_t uint8FromFloat(highp float x) {
  return uint8_t(uint(clamp(x, 0.0, 255.0)));
}
`],xp=[pt,`
struct int8_t {
  highp int value;
};
struct int8x2_t {
  highp ivec2 value;
};
struct int8x3_t {
  highp ivec3 value;
};
struct int8x4_t {
  highp ivec4 value;
};
int8_t mixLinear(int8_t x, int8_t y, highp float a) {
  return int8_t(int(round(mix(float(x.value), float(y.value), a))));
}
highp int toRaw(int8_t x) { return x.value; }
highp ivec2 toRaw(int8x2_t x) { return x.value; }
highp ivec3 toRaw(int8x3_t x) { return x.value; }
highp ivec4 toRaw(int8x4_t x) { return x.value; }
uint64_t toUint64(int8_t x) {
  uint64_t result;
  result.value[0] = uint(x.value);
  result.value[1] = uint(x.value >> 31);
  return result;
}
int8_t int8FromFloat(highp float x) {
  return int8_t(int(clamp(x, -128.0, 127.0)));
}
`],Xl=`
highp float toRaw(highp float x) { return x; }
highp float toNormalized(highp float x) { return x; }
vec2 toRaw(vec2 x) { return x; }
vec2 toNormalized(vec2 x) { return x; }
vec3 toRaw(vec3 x) { return x; }
vec3 toNormalized(vec3 x) { return x; }
vec4 toRaw(vec4 x) { return x; }
vec4 toNormalized(vec4 x) { return x; }
`,Ep=[pt,`
struct uint16_t {
  highp uint value;
};
struct uint16x2_t {
  highp uvec2 value;
};
uint16_t mixLinear(uint16_t x, uint16_t y, highp float a) {
  return uint16_t(uint(round(mix(float(x.value), float(y.value), a))));
}
highp uint toRaw(uint16_t x) { return x.value; }
highp float toNormalized(uint16_t x) { return float(toRaw(x)) / 65535.0; }
highp uvec2 toRaw(uint16x2_t x) { return x.value; }
highp vec2 toNormalized(uint16x2_t x) { return vec2(toRaw(x)) / 65535.0; }
uint64_t toUint64(uint16_t x) {
  uint64_t result;
  result.value[0] = x.value;
  result.value[1] = 0u;
  return result;
}
uint16_t uint16FromFloat(highp float x) {
  return uint16_t(uint(clamp(x, 0.0, 65535.0)));
}
`],Tp=[pt,`
struct int16_t {
  highp int value;
};
struct int16x2_t {
  highp ivec2 value;
};
int16_t mixLinear(int16_t x, int16_t y, highp float a) {
  return int16_t(int(round(mix(float(x.value), float(y.value), a))));
}
highp int toRaw(int16_t x) { return x.value; }
highp ivec2 toRaw(int16x2_t x) { return x.value; }
uint64_t toUint64(int16_t x) {
  uint64_t result;
  result.value[0] = uint(x.value);
  result.value[1] = uint(x.value >> 31);
  return result;
}
int16_t int16FromFloat(highp float x) {
  return int16_t(int(clamp(x, -32768.0, 32767.0)));
}
`],bo=[pt,`
struct uint32_t {
  highp uint value;
};
uint32_t mixLinear(uint32_t x, uint32_t y, highp float a) {
  return uint32_t(uint(round(mix(float(x.value), float(y.value), a))));
}
highp float toNormalized(uint32_t x) { return float(x.value) / 4294967295.0; }
highp uint toRaw(uint32_t x) { return x.value; }
uint64_t toUint64(uint32_t x) {
  uint64_t result;
  result.value[0] = x.value;
  result.value[1] = 0u;
  return result;
}
uint32_t uint32FromFloat(highp float x) {
  return uint32_t(uint(clamp(x, 0.0, 4294967295.0)));
}
`],Dp=[pt,`
struct int32_t {
  highp int value;
};
int32_t mixLinear(int32_t x, int32_t y, highp float a) {
  return int32_t(int(round(mix(float(x.value), float(y.value), a))));
}
highp int toRaw(int32_t x) { return x.value; }
uint64_t toUint64(int32_t x) {
  uint64_t result;
  result.value[0] = uint(x.value);
  result.value[1] = uint(x.value >> 31);
  return result;
}
int32_t int32FromFloat(highp float x) {
  return int32_t(int(clamp(x, 2147483648.0, 2147483647.0)));
}
`],vC=`
highp int getFortranOrderIndex(ivec3 subscripts, ivec3 size) {
  return subscripts.x + size.x * (subscripts.y + size.y * subscripts.z);
}
`,yC=`
highp uint log2Exact(highp uint i) {
  highp uint r;
  r = uint((i & 0xAAAAAAAAu) != 0u);
  r |= uint((i & 0xFFFF0000u) != 0u) << 4;
  r |= uint((i & 0xFF00FF00u) != 0u) << 3;
  r |= uint((i & 0xF0F0F0F0u) != 0u) << 2;
  r |= uint((i & 0xCCCCCCCCu) != 0u) << 1;
  return r;
}
`,SC=`
bool clipLineToDepthRange(inout highp vec4 a, inout highp vec4 b) {
  highp float tmin = 0.0, tmax = 1.0;
  highp float k1 = b.w - a.w + a.z - b.z;
  highp float k2 = a.w - b.w + a.z - b.z;
  highp float q1 = (a.z - a.w) / k1;
  highp float q2 = (a.z + a.w) / k2;
  if (k1 > 0.0) tmin = max(tmin, q1);
  else if (k1 < 0.0) tmax = min(tmax, q1);
  if (k2 > 0.0) tmax = min(tmax, q2);
  else if (k2 < 0.0) tmin = max(tmin, q2);
  if (tmin <= tmax) {
    highp vec4 tempA = a;
    highp vec4 tempB = b;
    a = mix(tempA, tempB, tmin);
    b = mix(tempA, tempB, tmax);
    return true;
  }
  return false;
}
`,Ip=`
highp float simpleFloatHash(highp vec2 co) {
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
`,bC=`
highp uint shiftLeftSaturate(highp uint x, int shiftAmount) {
  highp uint result = x << shiftAmount;
  if ((result >> shiftAmount) != x) return 0xffffffffu;
  return result;
}
`,Zl=`
highp uint addSaturate(highp uint x, highp uint y) {
  highp uint result = x + y;
  if (result < x) return 0xffffffffu;
  return result;
}
`,wC=`
highp uint subtractSaturate(highp uint x, highp uint y) {
  highp uint result = x - y;
  if (result > x) return 0u;
  return result;
}
`,CC=[Zl,`
highp int addSaturate(highp int x, highp uint y) {
  if (x >= 0) {
    return int(min(addSaturate(y, uint(x)), 0x7fffffffu));
  } else if (y >= uint(-x)) {
    return int(min(y - uint(-x), 0x7fffffffu));
  } else {
    return -int(min(uint(-x) - y, 0x80000000u));
  }
}
`],xC=[Zl,`
highp int subtractSaturate(highp int x, highp uint y) {
  if (x < 0) {
    return -int(min(addSaturate(uint(-x), uint(y)), 0x80000000u));
  } else if (uint(x) >= y) {
    return x - int(y);
  } else {
    return -int(min(y - uint(x), 0x80000000u));
  }
}
`];function vt(i,e=1){switch(i){case I.FLOAT32:if(e===1)return"float";if(e>1&&e<=4)return`vec${e}`;break;case I.UINT8:case I.INT8:case I.UINT16:case I.INT16:case I.UINT32:case I.INT32:case I.UINT64:{const t=re[i]?"":"u",n=B[i]*8;if(e===1)return`${t}int${n}_t`;if(e>1&&e*n<=32)return`${t}int${n}x${e}_t`;break}}throw new Error(`No shader type for ${I[i]}[${e}].`)}const ds={[I.UINT8]:Cp,[I.INT8]:xp,[I.UINT16]:Ep,[I.INT16]:Tp,[I.UINT32]:bo,[I.INT32]:Dp,[I.UINT64]:pt,[I.FLOAT32]:Xl};function EC(i,e){return e===1?i:i==="float"?`vec${e}`:`${i[0]}vec${e}`}const TC={[WebGL2RenderingContext.UNSIGNED_BYTE]:1,[WebGL2RenderingContext.BYTE]:1,[WebGL2RenderingContext.UNSIGNED_SHORT]:2,[WebGL2RenderingContext.SHORT]:2,[WebGL2RenderingContext.FLOAT]:4,[WebGL2RenderingContext.INT]:4,[WebGL2RenderingContext.UNSIGNED_INT]:4};function wo(i,e,t,n,s,r,o=1){let a=0,l=r*o;for(;l>0;){const u=Math.min(4,l),h=EC(e,u);l-=u,i.addAttribute("highp "+h,`a${s}${a}`),++a}l=r*o;let c="";for(let u=0;u<o;++u){c+=`highp ${e}[${r}] get${s}${u}() {
  highp ${e}[${r}] result;
`;for(let h=0;h<r;++h){const f=u*r+h,m=Math.floor(f/4),g=f%4;c+=`  result[${h}] = a${s}${m}`,(g!==0||f!==l-1)&&(c+=`[${g}]`),c+=`;
`}c+=`  return result;
`,c+=`}
`}i.addVertexCode(c);const d=TC[t];i.addInitializer(u=>{const h=[];for(let f=0;f<a;++f)h[f]=u.attribute(`a${s}${f}`);u.vertexShaderInputBinders[s]={enable(f){const{gl:m}=u;for(let g=0;g<a;++g){const v=h[g];m.enableVertexAttribArray(v),m.vertexAttribDivisor(v,f)}},disable(){const{gl:f}=u;for(let m=0;m<a;++m){const g=h[m];f.vertexAttribDivisor(g,0),f.disableVertexAttribArray(g)}},bind(f,m){const{gl:g}=u;for(let v=0;v<a;++v){const y=h[v],S=Math.min(4,l-4*v);e==="float"?g.vertexAttribPointer(y,S,t,n,f,m):g.vertexAttribIPointer(y,Math.min(4,l-4*v),t,f,m),m+=d*S}}}})}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const DC=!1;class Rp extends D.O8{constructor(e,t,n,s=new nr){super(),this.channels=e,this.properties=t,this.bounds=n,this.visibility=s,this.framebuffers=[],this.producerVisibility=new nr,this.frameNumber=-1}getFramebuffers(e){const{framebuffers:t}=this,n=this.bounds.value.length;for(;t.length<n;){const s=new $n(e,{colorBuffers:cs(e,1,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT)});t.push(s)}return t}get visibleHistograms(){return this.visibility.visible?this.bounds.value.length:0}disposed(){for(const e of this.framebuffers)e.dispose();this.framebuffers.length=0}}const kp=Symbol("histogramDataSamplerTextureUnit"),Lp=Symbol("histogramDepthTextureUnit"),ec=4096,IC=2**14;class tc extends D.O8{constructor(e){super(),this.gl=e,this.shader=this.registerDisposer((()=>{const t=new hn(this.gl);return t.addOutputBuffer("vec4","outputValue",0),t.addAttribute("float","aInput1"),t.addTextureSampler("sampler2D","uDataSampler",kp),t.addTextureSampler("sampler2D","uDepthSampler",Lp),t.addVertexCode(Ip),t.setVertexMain(`
float uRandomSeed = 0.0;
vec2 p = vec2(simpleFloatHash(vec2(aInput1 + float(gl_VertexID), uRandomSeed + float(gl_InstanceID))),
              simpleFloatHash(vec2(aInput1 + float(gl_VertexID) + 10.0, 5.0 + uRandomSeed + float(gl_InstanceID))));
float dataValue = texture(uDataSampler, p).x;
float stencilValue = texture(uDepthSampler, p).x;
if (stencilValue == 1.0) {
  gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
} else {
  gl_Position = vec4(2.0 * (dataValue * 255.0 + 0.5) / 256.0 - 1.0, 0.0, 0.0, 1.0);
}
gl_PointSize = 1.0;
`),t.setFragmentMain(`
outputValue = vec4(1.0, 1.0, 1.0, 1.0);
`),t.build()})()),this.inputIndexBuffer=this.registerDisposer(Ri(this.gl,WebGL2RenderingContext.ARRAY_BUFFER,()=>new Uint8Array(ec)))}static get(e){return e.memoize.get("textureHistogramGeneration",()=>new tc(e))}compute(e,t,n,s,r){const{gl:o}=this,{shader:a}=this,l=s.getFramebuffers(o);a.bind(),o.enable(WebGL2RenderingContext.BLEND),o.disable(WebGL2RenderingContext.SCISSOR_TEST),o.disable(WebGL2RenderingContext.DEPTH_TEST),o.blendFunc(WebGL2RenderingContext.ONE,WebGL2RenderingContext.ONE),this.inputIndexBuffer.value.bindToVertexAttrib(a.attribute("aInput1"),1,WebGL2RenderingContext.UNSIGNED_BYTE,!0);const c=a.textureUnit(kp),d=a.textureUnit(Lp);o.activeTexture(WebGL2RenderingContext.TEXTURE0+d),o.bindTexture(WebGL2RenderingContext.TEXTURE_2D,t),ki(o),o.activeTexture(WebGL2RenderingContext.TEXTURE0+c);const u=s.frameNumber;s.frameNumber=r;for(let h=0;h<e;++h)if(o.bindTexture(WebGL2RenderingContext.TEXTURE_2D,n[h].texture),ki(o),l[h].bind(256,1),r!==u&&(o.clearColor(0,0,0,0),o.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT)),o.drawArraysInstanced(WebGL2RenderingContext.POINTS,0,ec,IC/ec),DC){const f=new Float32Array(1024);o.readPixels(0,0,256,1,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.FLOAT,f);const m=new Float32Array(256);for(let g=0;g<256;++g)m[g]=f[g*4];console.log("histogram",m.join(" "))}o.disable(WebGL2RenderingContext.BLEND)}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const nc={[I.UINT8]:"vec2",[I.INT8]:"vec2",[I.UINT16]:"vec2",[I.INT16]:"vec2",[I.FLOAT32]:"vec2",[I.UINT32]:"Uint32LerpParameters",[I.INT32]:"Int32LerpParameters",[I.UINT64]:"Uint64LerpParameters"},cr={[I.UINT8]:"",[I.INT8]:"",[I.UINT16]:"",[I.INT16]:"",[I.FLOAT32]:"",[I.UINT32]:`
struct Uint32LerpParameters {
  uint offset;
  int shift;
  float multiplier;
};
`,[I.INT32]:`
struct Int32LerpParameters {
  int offset;
  int shift;
  float multiplier;
};
`,[I.UINT64]:[pt,`
struct Uint64LerpParameters {
  uint64_t offset;
  int shift;
  float multiplier;
};
`]},Pp=`
float computeInvlerp(float inputValue, vec2 p) {
  float outputValue = inputValue;
  outputValue = (outputValue - p[0]) * p[1];
  return outputValue;
}
`;function Co(i){const t=`
float computeInvlerp(${vt(i)} inputValue, vec2 p) {
  return computeInvlerp(float(toRaw(inputValue)), p);
}
`;return[ds[i],Pp,t]}function Ap(i){const e=vt(i),t=i===I.INT32?"int":"uint",n=nc[i];return[ds[i],cr[i],`
float computeInvlerp(${t} v, ${n} p) {
  uint x;
  if (v >= p.offset) {
    x = uint(v - p.offset);
  } else {
    x = uint(p.offset - v);
    p.multiplier = -p.multiplier;
  }
  x >>= p.shift;
  return float(x) * p.multiplier;
}
float computeInvlerp(${e} inputValue, ${n} p) {
  return computeInvlerp(toRaw(inputValue), p);
}
`]}const RC={[I.UINT8]:Co(I.UINT8),[I.INT8]:Co(I.INT8),[I.UINT16]:Co(I.UINT16),[I.INT16]:Co(I.INT16),[I.FLOAT32]:Pp,[I.UINT32]:Ap(I.UINT32),[I.INT32]:Ap(I.INT32),[I.UINT64]:[pt,So,bp,wp,cr[I.UINT64],`
float computeInvlerp(uint64_t inputValue, Uint64LerpParameters p) {
  if (compareLessThan(inputValue, p.offset)) {
    inputValue = subtract(p.offset, inputValue);
    p.multiplier = -p.multiplier;
  } else {
    inputValue = subtract(inputValue, p.offset);
  }
  uint shifted = shiftRight(inputValue, p.shift).value[0];
  return float(shifted) * p.multiplier;
}
`]};function dr(i){let t=`
${vt(i)} computeLerp(float inputValue, vec2 p) {
  inputValue = inputValue / p[1] + p[0];
`;return i===I.FLOAT32?t+=`return inputValue;
`:t+=`return ${I[i].toLowerCase()}FromFloat(round(inputValue));
`,t+=`
}
`,[ds[i],t]}function Mp(i){const e=vt(i),t=nc[i];return[ds[i],cr[i],bC,i===I.UINT32?Zl:CC,i===I.UINT32?wC:xC,`
${e} computeLerp(float inputValue, ${t} p) {
  inputValue = inputValue / p.multiplier;
  uint x = uint(clamp(round(abs(inputValue)), 0.0, 4294967295.0));
  uint xShifted = shiftLeftSaturate(x, p.shift);
  if (inputValue >= 0.0) {
    return ${e}(addSaturate(p.offset, xShifted));
  } else {
    return ${e}(subtractSaturate(p.offset, xShifted));
  }
}
`]}const kC={[I.UINT8]:dr(I.UINT8),[I.INT8]:dr(I.INT8),[I.UINT16]:dr(I.UINT16),[I.INT16]:dr(I.INT16),[I.FLOAT32]:dr(I.FLOAT32),[I.UINT32]:Mp(I.UINT32),[I.INT32]:Mp(I.INT32),[I.UINT64]:[pt,So,Sp,fC,gC,wp,mC,cr[I.UINT64],`
uint64_t computeLerp(float inputValue, Uint64LerpParameters p) {
  inputValue = inputValue / p.multiplier;
  uint64_t x = uint64_t(uvec2(uint(clamp(round(abs(inputValue)), 0.0, 4294967295.0)), 0u));
  uint64_t shifted = shiftLeft(x, p.shift);
  if (!equals(shiftRight(shifted, p.shift), x)) {
    return uint64_t(uvec2(0xffffffffu, 0xffffffffu));
  }
  if (inputValue >= 0.0) {
    return addSaturate(p.offset, shifted);
  } else {
    return subtractSaturate(p.offset, shifted);
  }
}
`]};function Np(i,e,t){const n=`uLerpParams_${e}`,s=`uLerpBounds_${e}`,r=`uLerpScalar_${e}`;let o="";switch(t){case I.INT8:case I.UINT8:case I.INT16:case I.UINT16:case I.FLOAT32:i.addUniform("vec2",n);break;case I.INT32:case I.UINT32:{const a=nc[t];i.addUniform(`${t===I.INT32?"i":"u"}vec2`,s),i.addUniform("float",r),o+=`
#define ${n} ${a}(${s}[0], int(${s}[1]), ${r})
`;break}case I.UINT64:{i.addUniform("uvec3",s),i.addUniform("float",r),o+=`
#define ${n} Uint64LerpParameters(uint64_t(${s}.xy), int(${s}[2]), ${r})
`;break}}return[cr[t],o]}function us(i,e,t,n=!1){const s=vt(t);let r=`
float ${e}(${s} inputValue) {
  float v = computeInvlerp(inputValue, uLerpParams_${e});
  ${n?"v = clamp(v, 0.0, 1.0);":""}
  defaultMaxProjectionIntensity = v;
  return v;
}
`;if(t!==I.UINT64&&t!==I.FLOAT32){const o=re[t]?"int":"uint";r+=`
float ${e}(${o} inputValue) {
  return ${e}(${s}(inputValue));
}
`}return[ds[t],Np(i,e,t),RC[t],r]}function LC(i,e,t){return[ds[t],Np(i,e,t),kC[t],`
${vt(t)} ${e}(float inputValue) {
  return computeLerp(inputValue, uLerpParams_${e});
}
`]}const Li=new M.R;function Pi(i,e,t,n){const{gl:s}=i;switch(t){case I.INT8:case I.UINT8:case I.INT16:case I.UINT16:case I.FLOAT32:s.uniform2f(i.uniform(`uLerpParams_${e}`),n[0],1/(n[1]-n[0]));break;case I.INT32:case I.UINT32:{const r=n[0],o=n[1]-r,a=Math.max(0,Math.ceil(Math.log2(Math.abs(o)))-24),l=2**a/o,c=i.uniform(`uLerpBounds_${e}`);t===I.UINT32?s.uniform2ui(c,r,a):s.uniform2i(c,r,a),s.uniform1f(i.uniform(`uLerpScalar_${e}`),l);break}case I.UINT64:{const r=n[0],o=n[1];M.R.absDifference(Li,o,r);const a=Li.high>0?32+Math.ceil(Math.log2(Li.high)):Math.ceil(Math.log2(Li.low)),l=Math.max(0,a-24);M.R.rshift(Li,Li,l);let c=1/Li.low;M.R.compare(r,o)>0&&(c*=-1);const d=i.uniform(`uLerpBounds_${e}`);s.uniform3ui(d,r.low,r.high,l),s.uniform1f(i.uniform(`uLerpScalar_${e}`),c)}}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Mt(i,e,t){(0,p.MM)(i,e,n=>t.restoreState(n))}class Ai extends D.O8{constructor(){super(...arguments),this.children=new Map,this.changed=new j.IY}add(e,t){const{children:n}=this;if(n.has(e))throw new Error(`Key ${JSON.stringify(e)} already registered.`);return this.children.set(e,t),t.changed.add(this.changed.dispatch),this.changed.dispatch(),()=>{this.remove(e)}}remove(e){const{children:t}=this;if(t.has(e))throw new Error(`Key ${JSON.stringify(e)} not registered.`);const n=t.get(e);this.children.delete(e),n.changed.remove(this.changed.dispatch),this.changed.dispatch()}disposed(){const{changed:e}=this;for(const t of this.children.values())t.changed.remove(e.dispatch);this.children=void 0,super.disposed()}toJSON(){const e=this.baseJSON();for(const[t,n]of this.children)e[t]=n.toJSON();return e}baseJSON(){return{}}reset(){for(const e of this.children.values())e.reset()}restoreState(e){(0,p.Rf)(e);for(const[t,n]of this.children)try{if(Object.prototype.hasOwnProperty.call(e,t)){const s=e[t];if(s===void 0)continue;n.restoreState(s)}}catch(s){throw new Error(`Error restoring property ${JSON.stringify(t)}: ${s.message}`)}}}class v_ extends Ai{constructor(){super(...arguments),this.lastState={}}restoreState(e){(0,p.Rf)(e),this.lastState=e,super.restoreState(e)}reset(){this.lastState={},super.reset()}baseJSON(){const e=Object.assign(super.baseJSON(),this.lastState);for(const t of this.children.keys())delete e[t];return e}toJSON(){const e=super.toJSON();return this.lastState=e,e}add(e,t){const n=super.add(e,t),s=this.lastState[e];return s!==void 0&&(t.reset(),t.restoreState(s)),n}}const Op=new WeakMap;function ri(i){let e=Op.get(i);const t=i.changed.count;if(e!==void 0&&e.generation===t)return e;let n;if(i instanceof Ai){n=i.baseJSON();for(const[s,r]of i.children)n[s]=ri(r).value}else n=i.toJSON();return e===void 0?(e={generation:t,value:n},Op.set(i,e)):(e.generation=t,e.value=n),e}var Mi=G(6703);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var xo=(i=>(i[i.LINKED=0]="LINKED",i[i.RELATIVE=1]="RELATIVE",i[i.UNLINKED=2]="UNLINKED",i))(xo||{}),Vp=(i=>(i[i.LINKED=0]="LINKED",i[i.UNLINKED=2]="UNLINKED",i))(Vp||{});class PC extends Mi.F{constructor(e=0){super(xo,e)}}class y_ extends Mi.F{constructor(e=0){super(Vp,e)}}const Eo=w.eR.create(),_p=w.Yu.create();function ur(i,e,t,n){let s=!1;const r=!1;let o;i.registerDisposer(e);const a=()=>{if(!r){switch(s=!0,t.value){case 2:if(n.isValid(i))break;case 0:n.assign(i,e);break;case 1:n.add(i,e,o);break}s=!1}},l=()=>{if(!s)switch(t.value){case 2:break;case 0:n.assign(e,i);break;case 1:n.subtract(e,i,o);break}};let c=2;const d=()=>{const u=t.value;if(u!==c)switch(u){case 2:o=void 0;break;case 0:o=void 0,n.assign(i,e);break;case 1:o=n.difference(i,e);break}c=u,i.changed.dispatch()};return i.registerDisposer(i.changed.add(l)),i.registerDisposer(e.changed.add(a)),i.registerDisposer(t.changed.add(d)),d(),i}function Bp(i,e,t,n){return ur(i,e,t,n)}class oi extends D.O8{constructor(e){super(),this.coordinateSpace=e,this.coordinates_=rs,this.changed=new j.IY,this.registerDisposer(e.changed.add(()=>{this.handleCoordinateSpaceChanged()}))}get valid(){return this.coordinateSpace.value.valid}get value(){return this.handleCoordinateSpaceChanged(),this.coordinates_}reset(){this.curCoordinateSpace=void 0,this.coordinates_=rs,this.changed.dispatch()}set value(e){const{curCoordinateSpace:t}=this;if(t===void 0||!t.valid||t.rank!==e.length)return;const{coordinates_:n}=this;n.set(e),this.changed.dispatch()}handleCoordinateSpaceChanged(){const e=this.coordinateSpace.value,t=this.curCoordinateSpace;if(e===t)return;this.curCoordinateSpace=e;const{rank:n}=e;if(!e.valid)return;if(t===void 0||!t.valid){let{coordinates_:d}=this;if(!(d!==void 0&&d.length===n)){d=this.coordinates_=new Float32Array(n),aw(d,e.bounds);const{voxelCenterAtIntegerCoordinates:u}=e.bounds;for(let h=0;h<n;++h)u[h]?d[h]=Math.round(d[h]):d[h]=Math.floor(d[h])+.5}this.changed.dispatch();return}const s=new Float32Array(n),r=this.coordinates_,{ids:o,scales:a}=e,{ids:l,scales:c}=t;for(let d=0;d<n;++d){const u=o[d],h=l.indexOf(u);h===-1?s[d]=Lh(e.bounds.lowerBounds[d],e.bounds.upperBounds[d]):s[d]=r[h]*(c[h]/a[d])}this.coordinates_=s,this.changed.dispatch()}toJSON(){if(!this.valid&&this.coordinates_.length===0)return;this.handleCoordinateSpaceChanged();const{value:e}=this;if(e.length!==0)return Array.from(e)}restoreState(e){if(e===void 0){this.reset();return}this.curCoordinateSpace=void 0,this.coordinates_=Float32Array.from((0,p.$v)(e,p.zo)),this.handleCoordinateSpaceChanged(),this.changed.dispatch()}snapToVoxel(){this.handleCoordinateSpaceChanged();const{bounds:{voxelCenterAtIntegerCoordinates:e}}=this.coordinateSpace.value,{coordinates_:t}=this,n=t.length;for(let s=0;s<n;++s)e[s]?t[s]=Math.round(t[s]):t[s]=Math.floor(t[s])+.5;this.changed.dispatch()}assign(e){e.handleCoordinateSpaceChanged();const{curCoordinateSpace:t,coordinates_:n}=e;this.curCoordinateSpace=t,this.coordinates_=Float32Array.from(n),this.changed.dispatch()}static getOffset(e,t){const n=e.coordinates_,s=t.coordinates_;if(n.length===s.length)return Pl(new Float32Array(n.length),n,s)}static addOffset(e,t,n,s=1){e.handleCoordinateSpaceChanged();const{value:r}=t;n!==void 0&&r.length===n.length&&(qb(e.value,r,n,s),e.changed.dispatch())}get legacyJsonView(){const e=this;return{changed:e.changed,toJSON(){return e.toJSON()},reset(){e.reset()},restoreState(t){if(t===void 0||Array.isArray(t)){e.restoreState(t);return}(0,p.Rf)(t),Mt(t,"voxelCoordinates",e)}}}}var Gn=(i=>(i[i.STOP=0]="STOP",i[i.LOOP=1]="LOOP",i[i.REVERSE=2]="REVERSE",i))(Gn||{});const Fp=10;class ic{constructor(){this.velocity=Fp,this.atBoundary=2,this.paused=!0}}function AC(i,e){return i.velocity===e.velocity&&i.atBoundary===e.atBoundary&&i.paused===e.paused}function MC(i){return(0,p.Rf)(i),{velocity:(0,p.MM)(i,"velocity",p.zo,Fp),atBoundary:(0,p.MM)(i,"atBoundary",e=>(0,p.sl)(e,Gn),0),paused:(0,p.MM)(i,"paused",p.aO,!0)}}function NC(i){const{velocity:e,atBoundary:t,paused:n}=i;return{velocity:e,atBoundary:t===0?void 0:Gn[t].toLowerCase(),paused:n?void 0:!1}}class sc extends D.O8{constructor(e){super(),this.coordinateSpace=e,this.changed=new j.IY,this.registerDisposer(e.changed.add(()=>{this.handleCoordinateSpaceChanged()})),this.curCoordinateSpace=e.value,this.velocities_=new Array(this.curCoordinateSpace?.rank??0)}get valid(){return this.coordinateSpace.value.valid}get value(){return this.handleCoordinateSpaceChanged(),this.velocities_}set value(e){const{curCoordinateSpace:t}=this;t===void 0||t.rank!==e.length||(this.velocities_=e,this.changed.dispatch())}get(e){const t=this.coordinateSpace.value?.ids;if(t===void 0)return;const n=t.indexOf(e);return n===-1?void 0:this.value[n]}dimensionVelocity(e,t){const n=new j.IY;let s=-1;const r=()=>{const c=this.coordinateSpace.value?.ids;c===void 0?s=-1:(s===-1||c[s]!==t)&&(s=c.indexOf(t))},o=()=>{if(r(),s!==-1)return this.value[s]},a=c=>{if(r(),s===-1)return;const d=this.value;d[s]!==c&&(d[s]=c,this.changed.dispatch())},l=o();return e.registerDisposer(this.changed.add(()=>{o()!==l&&n.dispatch()})),{get value(){return o()},set value(c){a(c)},changed:n}}modifyDimension(e,t){const n=this.coordinateSpace.value?.ids;if(n===void 0)return;const s=n.indexOf(e);if(s===-1)return;const r=this.value,o=r[s],a=t(o);o!==a&&(r[s]=a,this.changed.dispatch())}togglePlayback(e,t=void 0){this.modifyDimension(e,(n=new ic)=>({...n,paused:t??!n.paused}))}playbackEnabled(e){const t=this;return{changed:this.changed,get value(){return t.get(e)!==void 0},set value(n){t.modifyDimension(e,s=>n?s??new ic:void 0)}}}multiplyVelocity(e,t){this.modifyDimension(e,(n=new ic)=>{let s=Math.round(n.velocity*t);return s===0&&(s=Math.sign(n.velocity)||1),{...n,velocity:s}})}handleCoordinateSpaceChanged(){const e=this.coordinateSpace.value,t=this.curCoordinateSpace;if(e===t)return;this.curCoordinateSpace=e;const{rank:n}=e;if(!e.valid)return;if(t===void 0){let{velocities_:l}=this;l.length===n||(l=new Array(n)),this.changed.dispatch();return}const s=new Array(n),r=this.velocities_,{ids:o}=e,{ids:a}=t;for(let l=0;l<n;++l){const c=o[l],d=a.indexOf(c);d!==-1&&(s[l]=r[d])}this.velocities_=s,this.changed.dispatch()}toJSON(){this.handleCoordinateSpaceChanged();const{velocities_:e,curCoordinateSpace:t}=this;if(!t?.valid||!e.some(o=>o!==void 0))return;const n={},{names:s,rank:r}=t;for(let o=0;o<r;++o){const a=e[o];a!==void 0&&(n[s[o]]=NC(a))}return n}reset(){this.handleCoordinateSpaceChanged(),this.velocities_=new Array(this.curCoordinateSpace?.rank??0)}restoreState(e){if(e===void 0){this.reset();return}(0,p.Rf)(e);const t=this.curCoordinateSpace=this.coordinateSpace.value;if(this.velocities_=new Array(t?.rank??0),t===void 0)throw new Error("Must specify dimensions in order to specify velocities");const n=this.velocities_=new Array(t?.rank??0),{names:s}=t;for(const r of Object.keys(e)){const o=s.indexOf(r);if(o===-1)throw new Error(`Invalid dimension name: ${JSON.stringify(r)}`);n[o]=(0,p.cQ)(e,r,MC)}this.changed.dispatch()}assign(e){const t=e.value,n=this.value,s=n.length;let r=!1;for(let o=0;o<s;++o){const a=t[o],l=n[o];a!==l&&((l===void 0||a===void 0||!AC(l,a))&&(r=!0),n[o]=a)}r&&this.changed.dispatch()}}class OC extends D.O8{constructor(e,t){super(),this.peer=e,this.positionLink=t,this.changed=new j.IY,this.velocity=this.registerDisposer(new sc(this.peer.coordinateSpace)),this.registerDisposer(e),this.velocity.changed.add(()=>{this.positionLink.value===2?this.changed.dispatch():this.peer.assign(this.velocity)});const n=()=>{this.positionLink.value!==2&&this.velocity.assign(this.peer)};this.registerDisposer(e.changed.add(n)),n()}toJSON(){if(this.positionLink.value===2)return this.velocity.toJSON()}reset(){this.positionLink.value===2&&this.velocity.reset()}restoreState(e){this.positionLink.value===2&&this.velocity.restoreState(e)}copyToPeer(){this.positionLink.value===2&&this.peer.assign(this.velocity)}}class rc extends D.O8{constructor(e,t,n){super(),this.display=e,this.position=t,this.velocity=n,this.dimensionStates=new Map,this.lastUpdateGeneration=0,this.handleVelocityChanged(),this.registerDisposer(n.changed.add(()=>this.handleVelocityChanged()))}disposed(){this.unregisterUpdateStartedCallback?.(),super.disposed()}handleVelocityChanged(){const{dimensionStates:e}=this,t=this.position.coordinateSpace.value?.ids??[],n=t.length,s=this.velocity.value,r=++this.lastUpdateGeneration,o=this.position.value,a=Date.now();for(let l=0;l<n;++l){const c=s[l];if(c===void 0||c.velocity===0||c.paused)continue;const d=t[l],u=e.get(d);u===void 0?e.set(d,{prevTime:a,dimensionIndex:l,prevCoordinate:o[l],generation:r}):(u.generation=r,u.dimensionIndex=l)}for(const[l,c]of e)c.generation!==r&&e.delete(l);if(e.size===0){const{unregisterUpdateStartedCallback:l}=this;l!==void 0&&(l(),this.unregisterUpdateStartedCallback=void 0)}else this.unregisterUpdateStartedCallback===void 0&&(this.unregisterUpdateStartedCallback=this.display.updateStarted.add(()=>this.updateStarted()),this.display.scheduleRedraw())}updateStarted(){const e=this.position.coordinateSpace.value;if(e===void 0)return;const t=e.ids,n=this.position.value;let s=!1,r=!1;const o=Date.now(),a=this.velocity.value,{bounds:{lowerBounds:l,upperBounds:c}}=e;for(const[d,u]of this.dimensionStates){const{dimensionIndex:h}=u;if(t[h]!==d)continue;const f=a[h];if(Math.floor(n[h])!==Math.floor(u.prevCoordinate)){f?.paused===!1&&(a[h]={...f,paused:!0},r=!0);continue}const m=o-u.prevTime,g=f?.velocity??0,v=m*g/1e3;if(v===0)continue;let y=n[h]+v;const S=l[h],x=Math.ceil(c[h]-1),b=v>0?x:S,E=v>0?S:x,C=Math.sign(v);if(Number.isFinite(b)&&y*C>=b*C)switch(f.atBoundary){case 1:if(Number.isFinite(E)){y=E;break}case 0:a[h]={...f,paused:!0},r=!0,y=b;break;case 2:a[h]={...f,velocity:-g},r=!0,y=b;break}n[h]=y,u.prevCoordinate=n[h],u.prevTime=o,s=!0}s&&this.position.changed.dispatch(),r&&this.velocity.changed.dispatch(),this.display.scheduleRedraw()}}function Up(i,e,t){if(t===void 0||Object.keys(t).length===0){i.value=0;return}(0,p.Rf)(t),i.value=2,(0,p.cQ)(t,"value",n=>{n!==void 0&&e.restoreState(n)}),(0,p.cQ)(t,"link",n=>i.restoreState(n))}class hr{constructor(e,t=new PC){this.peer=e,this.link=t}get changed(){return this.value.changed}toJSON(){const{link:e}=this;if(e.value!==0)return{link:e.toJSON(),value:this.getValueJson()}}getValueJson(){return this.value.toJSON()}reset(){this.link.value=0}restoreState(e){Up(this.link,this.value,e)}copyToPeer(){this.link.value!==0&&(this.link.value=2,this.peer.assign(this.value),this.link.value=0)}}class $p extends hr{}class Gp extends hr{constructor(){super(...arguments),this.value=ur(new oi(this.peer.coordinateSpace),this.peer,this.link,{assign:(e,t)=>e.assign(t),isValid:e=>e.valid,difference:oi.getOffset,add:oi.addOffset,subtract:(e,t,n)=>{oi.addOffset(e,t,n,-1)}})}}function VC(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}class hs extends D.O8{constructor(e){super(),this.changed=new j.IY,e==null&&(e=w.Yu.create()),this.orientation=e}toJSON(){const{orientation:e}=this;if(w.Yu.normalize(this.orientation,this.orientation),!VC(e))return Array.prototype.slice.call(this.orientation)}restoreState(e){try{(0,p.Vr)(this.orientation,e),w.Yu.normalize(this.orientation,this.orientation)}catch{w.Yu.identity(this.orientation)}this.changed.dispatch()}reset(){w.Yu.identity(this.orientation),this.changed.dispatch()}snap(){const e=w.w0.create();w.w0.fromQuat(e,this.orientation);const t=[!1,!1,!1];for(let n=0;n<3;++n){let s=0,r=0;for(let o=0;o<3;++o){const a=e[n*3+o];e[n*3+o]=0,!t[o]&&Math.abs(a)>Math.abs(s)&&(s=a,r=o)}e[n*3+r]=Math.sign(s),t[r]=!0}w.Yu.fromMat3(this.orientation,e),this.changed.dispatch()}static makeRelative(e,t){const n=new hs(w.Yu.multiply(w.Yu.create(),e.orientation,t));let s=!1;n.registerDisposer(e.changed.add(()=>{s||(r=!0,w.Yu.multiply(n.orientation,e.orientation,t),n.changed.dispatch(),r=!1)}));let r=!1;const o=w.Yu.invert(w.Yu.create(),t);return n.registerDisposer(n.changed.add(()=>{r||(s=!0,w.Yu.multiply(e.orientation,n.orientation,o),e.changed.dispatch(),s=!1)})),n}assign(e){w.Yu.copy(this.orientation,e.orientation),this.changed.dispatch()}}class oc extends hr{constructor(){super(...arguments),this.value=ur(new hs,this.peer,this.link,{assign:(e,t)=>e.assign(t),isValid:()=>!0,difference:(e,t)=>{const n=w.Yu.create();return w.Yu.multiply(n,w.Yu.invert(n,t.orientation),e.orientation)},add:(e,t,n)=>{w.Yu.multiply(e.orientation,t.orientation,n),e.changed.dispatch()},subtract:(e,t,n)=>{w.Yu.multiply(e.orientation,t.orientation,w.Yu.invert(_p,n)),e.changed.dispatch()}})}}class zp extends D.O8{constructor(e){super(),this.coordinateSpace=e,this.changed=new j.IY,this.curCoordinateSpace=Bn,this.value_={factors:new Float64Array(0)},this.registerDisposer(e.changed.add(()=>this.update())),this.update()}get value(){return this.update()}reset(){this.value_={factors:new Float64Array(0)},this.curCoordinateSpace=Bn,this.changed.dispatch()}toJSON(){const e={};let t=!1;const{value:n}=this,{factors:s}=n,{names:r,rank:o}=this.curCoordinateSpace;for(let a=0;a<o;++a){const l=s[a];l!==1&&(e[r[a]]=l,t=!0)}if(t)return e}restoreState(e){const{coordinateSpace:{value:t}}=this,{names:n,rank:s}=t,r=new Float64Array(s);if(r.fill(-1),e!==void 0){const o=(0,p.Rf)(e);for(let a=0;a<s;++a)r[a]=(0,p.cQ)(o,n[a],l=>l===void 0?1:(0,p.Mo)(l))}this.value_={factors:r},this.curCoordinateSpace=t,this.changed.dispatch()}setFactors(e){const{coordinateSpace:{value:t}}=this;e.length===t.rank&&(this.value_={factors:e},this.curCoordinateSpace=t,this.changed.dispatch())}update(){const{coordinateSpace:{value:e}}=this;let t=this.value_;const{curCoordinateSpace:n}=this;if(n===e)return t;const{ids:s}=n,{ids:r,rank:o}=e,a=t.factors,l=new Float64Array(o);l.fill(1);for(let c=0;c<o;++c){const d=r[c],u=s.indexOf(d);u!==-1&&(l[c]=a[u])}return(0,z.r1)(l,a)||(t=this.value_={factors:l},this.curCoordinateSpace=e,this.changed.dispatch()),t}assign(e){this.setFactors(e.value.factors)}}function Wp(i,e,t,n,s){if(t===n)return e;const{ids:r}=t,{rank:o,ids:a}=n,l=new i(o);for(let c=0;c<o;++c){const d=a[c],u=r.indexOf(d);l[c]=u===-1?s(c):e[u]}return l}class _C extends hr{constructor(){super(...arguments),this.value=ur(new zp(this.peer.coordinateSpace),this.peer,this.link,{assign:(e,t)=>e.assign(t),difference:(e,t)=>{const{factors:n}=e.value,s=e.coordinateSpace.value,r=t.value.factors;return{coordinateSpace:s,offsets:Pl(new Float64Array(n.length),n,r)}},add:(e,t,n)=>{const s=Wp(Float64Array,n.offsets,n.coordinateSpace,e.coordinateSpace.value,()=>0);e.setFactors(Ll(new Float64Array(s.length),s,t.value.factors))},subtract:(e,t,n)=>{const s=Wp(Float64Array,n.offsets,n.coordinateSpace,e.coordinateSpace.value,()=>0);e.setFactors(Pl(new Float64Array(s.length),t.value.factors,s))},isValid:()=>!0})}}function Hp(i,e,t){const{rank:n,names:s,units:r}=i,{displayRank:o,displayDimensionIndices:a}=e,l=new Float64Array(3),c=new Float64Array(3);let d;const{factors:u}=t,h=new Array(3),f=new Float64Array(3);if(l.fill(1),c.fill(1),f.fill(1),h.fill(""),o===0)d=1;else{d=Number.POSITIVE_INFINITY;const{scales:m}=i;for(let g=0;g<o;++g){const v=a[g],y=c[g]=u[v]*m[v];d=Math.min(d,y),h[g]=r[v],f[g]=m[v]}for(let g=0;g<o;++g)l[g]=c[g]/d}return{globalRank:n,globalDimensionNames:s,displayRank:o,displayDimensionIndices:a,displayDimensionUnits:h,displayDimensionScales:f,canonicalVoxelFactors:l,voxelPhysicalScales:c,canonicalVoxelPhysicalSize:d}}function Jp(i,e){return(0,z.r1)(i.globalDimensionNames,e.globalDimensionNames)&&(0,z.r1)(i.displayDimensionIndices,e.displayDimensionIndices)&&(0,z.r1)(i.canonicalVoxelFactors,e.canonicalVoxelFactors)&&(0,z.r1)(i.voxelPhysicalScales,e.voxelPhysicalScales)&&i.canonicalVoxelPhysicalSize===e.canonicalVoxelPhysicalSize&&(0,z.r1)(i.displayDimensionUnits,e.displayDimensionUnits)&&(0,z.r1)(i.displayDimensionScales,e.displayDimensionScales)}function BC(i,e){const t=i.displayDimensionRenderInfo;return t===e?!0:Jp(t,e)?(i.displayDimensionRenderInfo=e,!0):!1}class jp extends D.O8{constructor(e,t){super(),this.relativeDisplayScales=e,this.displayDimensions=t,this.changed=new j.IY,this.curRelativeDisplayScales=this.relativeDisplayScales.value,this.curDisplayDimensions=this.displayDimensions.value,this.curCoordinateSpace=this.relativeDisplayScales.coordinateSpace.value,this.value_=Hp(this.curCoordinateSpace,this.curDisplayDimensions,this.curRelativeDisplayScales),this.registerDisposer(e),this.registerDisposer(t);const n=()=>{this.value};this.registerDisposer(e.changed.add(n)),this.registerDisposer(t.changed.add(n))}get value(){const{relativeDisplayScales:{value:e,coordinateSpace:{value:t}},displayDimensions:{value:n},curRelativeDisplayScales:s,curDisplayDimensions:r,curCoordinateSpace:o}=this;let a=this.value_;if(s!==e||r!==n||o!==t){this.curRelativeDisplayScales=e,this.curDisplayDimensions=n,this.curCoordinateSpace=t;const l=Hp(t,n,e);Jp(a,l)||(this.value_=a=l,this.changed.dispatch())}return a}}class Yp extends D.O8{constructor(e){super(),this.coordinateSpace=e,this.changed=new j.IY,this.default_=!0,this.value_=void 0,this.registerDisposer(this.coordinateSpace.changed.add(this.changed.dispatch)),this.update()}get value(){return this.update(),this.value_}update(){const{coordinateSpace:{value:e}}=this,t=this.value_;if(t!==void 0&&t.coordinateSpace===e)return;if(t===void 0||this.default_){this.setToDefault(e);return}const n=new Int32Array(3),{ids:s}=t.coordinateSpace,{ids:r}=e,o=t.displayDimensionIndices,a=t.displayRank;let l=0;for(let c=0;c<a;++c){const d=r.indexOf(s[o[c]]);d!==-1&&(n[l]=d,++l)}if(n.fill(-1,l),l===0){this.default_=!0,this.setToDefault(e);return}this.assignValue(e,l,n),this.changed.dispatch()}setToDefault(e){const t=Math.min(e.rank,3),n=new Int32Array(3);n.fill(-1);for(let s=0;s<t;++s)n[s]=s;this.assignValue(e,t,n)}assignValue(e,t,n){this.value_={coordinateSpace:e,displayRank:t,displayDimensionIndices:n},this.changed.dispatch()}reset(){this.default_=!0,this.value_=void 0,this.changed.dispatch()}restoreState(e){if(e===void 0){this.reset();return}const t=Bl(e);if(t.length>3)throw new Error("Number of spatial dimensions must be <= 3");const{coordinateSpace:{value:n}}=this,s=new Int32Array(3);s.fill(-1);const{names:r}=n;let o=0;for(const a of t){const l=r.indexOf(a);l!==-1&&(s[o++]=l)}if(o===0){this.reset();return}this.default_=!1,this.assignValue(n,o,s)}get default(){return this.update(),this.default_}set default(e){this.default_!==e&&(e?(this.default_=!0,this.setToDefault(this.coordinateSpace.value)):(this.default_=!1,this.changed.dispatch()))}setDimensionIndices(e,t){this.default_=!1,this.assignValue(this.coordinateSpace.value,e,t)}toJSON(){if(this.default_)return;const{value:e}=this,t=[],{displayRank:n,displayDimensionIndices:s,coordinateSpace:{names:r}}=e;if(n!==0){for(let o=0;o<n;++o)t[o]=r[s[o]];return t}}assign(e){if(e.default)this.default=!0;else{const{displayRank:t,displayDimensionIndices:n}=e.value;this.setDimensionIndices(t,n)}}}class FC extends $p{constructor(){super(...arguments),this.value=Bp(new Yp(this.peer.coordinateSpace),this.peer,this.link,{assign:(e,t)=>e.assign(t),isValid:()=>!0})}}class ps extends D.O8{constructor(e,t,n){super(),this.position=e,this.displayDimensionRenderInfo=t,this.orientation=n,this.changed=new j.IY,this.registerDisposer(e),this.registerDisposer(n),this.registerDisposer(t),this.registerDisposer(e.changed.add(this.changed.dispatch)),this.registerDisposer(n.changed.add(this.changed.dispatch)),this.registerDisposer(t.changed.add(this.changed.dispatch))}get displayDimensions(){return this.displayDimensionRenderInfo.displayDimensions}get relativeDisplayScales(){return this.displayDimensionRenderInfo.relativeDisplayScales}get valid(){return this.position.valid}reset(){this.position.reset(),this.orientation.reset(),this.displayDimensions.reset()}updateDisplayPosition(e,t=Eo){const{coordinateSpace:{value:n},value:s}=this.position,{displayDimensionIndices:r,displayRank:o}=this.displayDimensions.value;if(n===void 0)return!1;t.fill(0);for(let a=0;a<o;++a){const l=r[a];t[a]=s[l]}if(e(t)!==!1){for(let a=0;a<o;++a){const l=r[a];s[l]=t[a]}return this.position.changed.dispatch(),!0}return!1}toMat4(e,t){w.pB.fromQuat(e,this.orientation.orientation);const{value:n}=this.position,{canonicalVoxelFactors:s,displayDimensionIndices:r}=this.displayDimensionRenderInfo.value;for(let o=0;o<3;++o){const a=r[o],l=t/s[o];e[o]*=l,e[4+o]*=l,e[8+o]*=l,e[12+o]=n[a]||0}}toMat3(e,t){w.w0.fromQuat(e,this.orientation.orientation);const{canonicalVoxelFactors:n,displayRank:s}=this.displayDimensionRenderInfo.value;for(let r=0;r<s;++r){const o=t/n[r];e[r]*=o,e[3+r]*=o,e[6+r]*=o}}snap(){this.orientation.snap(),this.position.snapToVoxel(),this.changed.dispatch()}translateDimensionRelative(e,t){if(!this.valid)return;const{position:n}=this,{value:s}=n,{bounds:r}=n.coordinateSpace.value;s[e]=Nl(r,e,s[e]+t),n.changed.dispatch()}translateVoxelsRelative(e){if(!this.valid)return;const t=w.eR.transformQuat(Eo,e,this.orientation.orientation),{position:n}=this,{value:s}=n,{displayDimensionIndices:r,displayRank:o}=this.displayDimensions.value,{bounds:a}=n.coordinateSpace.value;for(let l=0;l<o;++l){const c=r[l],d=t[l];d!==0&&(s[c]=Nl(a,c,s[c]+d))}this.position.changed.dispatch()}rotateRelative(e,t){const n=w.Yu.create();w.Yu.setAxisAngle(n,e,t);const s=this.orientation.orientation;w.Yu.multiply(s,s,n),this.orientation.changed.dispatch()}rotateAbsolute(e,t,n){const{coordinateSpace:{value:s},value:r}=this.position;if(s===void 0)return;const{relativeDisplayScales:{value:{factors:o}},displayDimensions:{value:{displayDimensionIndices:a,displayRank:l}}}=this,{scales:c}=s,d=w.Yu.create();w.Yu.setAxisAngle(d,e,t);const u=this.orientation.orientation,h=Eo;Eo.fill(0);for(let m=0;m<l;++m){const g=a[m],v=n[g]-r[g];h[m]=v*c[g]*o[g]}const f=w.Yu.invert(_p,u);w.eR.transformQuat(h,h,f),w.Yu.multiply(u,d,u),w.eR.transformQuat(h,h,u);for(let m=0;m<l;++m){const g=a[m];r[g]=n[g]-h[m]/(c[g]*o[g])}this.position.changed.dispatch(),this.orientation.changed.dispatch()}translateNonDisplayDimension(e,t){if(!this.valid)return;const{displayDimensionIndices:n}=this.displayDimensions.value,{position:s}=this,r=s.coordinateSpace.value.rank;for(let o=0;o<r;++o)if(n.indexOf(o)===-1&&e--===0){this.translateDimensionRelative(o,t);return}}}class ac extends hr{constructor(e,t){super(e),this.value=(()=>{const n=new e.constructor(t),s=(c,d)=>{c.assign(d)},r=(c,d)=>c.value/d.value*(c.canonicalVoxelPhysicalSize/d.canonicalVoxelPhysicalSize),o=(c,d,u)=>{c.setPhysicalScale(d.value*u,d.canonicalVoxelPhysicalSize)},a=(c,d,u)=>{c.setPhysicalScale(d.value/u,d.canonicalVoxelPhysicalSize)},l=c=>c.coordinateSpaceValue.valid&&c.canonicalVoxelPhysicalSize!==0;return ur(n,this.peer,this.link,{assign:s,isValid:l,difference:r,add:o,subtract:a}),n})()}}function pr(i){return{changed:i.changed,toJSON(){return i.toJSON()},restoreState(e){Up(i.link,i.value.legacyJsonView,e)},reset(){i.reset()}}}class Qp extends D.O8{constructor(e){super(),this.displayDimensionRenderInfo=e,this.changed=new j.IY,this.curCanonicalVoxelPhysicalSize=0,this.value_=Number.NaN,this.legacyValue_=Number.NaN,this.registerDisposer(e),this.registerDisposer(e.changed.add(()=>this.handleCoordinateSpaceChanged())),this.registerDisposer(e.relativeDisplayScales.coordinateSpace.changed.add(()=>this.handleCoordinateSpaceChanged())),this.handleCoordinateSpaceChanged()}get value(){return this.handleCoordinateSpaceChanged(),this.value_}set value(e){const{canonicalVoxelPhysicalSize:t}=this;Object.is(e,this.value_)&&t===this.curCanonicalVoxelPhysicalSize||(this.curCanonicalVoxelPhysicalSize=t,this.legacyValue_=Number.NaN,this.value_=e,this.changed.dispatch())}get canonicalVoxelPhysicalSize(){return this.displayDimensionRenderInfo.value.canonicalVoxelPhysicalSize}get coordinateSpaceValue(){return this.displayDimensionRenderInfo.relativeDisplayScales.coordinateSpace.value}set legacyValue(e){Object.is(e,this.legacyValue_)||(this.value_=Number.NaN,this.legacyValue_=e,this.curCanonicalVoxelPhysicalSize=0,this.changed.dispatch())}get legacyValue(){return this.legacyValue_}handleCoordinateSpaceChanged(){const{value_:e}=this,{displayDimensionRenderInfo:{value:{canonicalVoxelPhysicalSize:t},relativeDisplayScales:{coordinateSpace:{value:n}}}}=this,{curCanonicalVoxelPhysicalSize:s}=this;if(!(!Number.isNaN(e)&&t===s)){if(!Number.isNaN(e)){s!==0&&(this.value_=e*(s/t),this.curCanonicalVoxelPhysicalSize=t,this.changed.dispatch());return}!n.valid||t===0||(this.curCanonicalVoxelPhysicalSize=t,this.value_=this.getDefaultValue(),this.changed.dispatch())}}toJSON(){const{value:e}=this;return Number.isNaN(e)?void 0:e}restoreState(e){this.curCanonicalVoxelPhysicalSize=0,this.legacyValue_=Number.NaN,e===void 0?this.value_=Number.NaN:this.value_=(0,p.Mo)(e),this.changed.dispatch()}reset(){this.curCanonicalVoxelPhysicalSize=0,this.value_=Number.NaN,this.legacyValue_=Number.NaN,this.changed.dispatch()}get legacyJsonView(){const e=this;return{changed:e.changed,toJSON(){return e.toJSON()},reset(){return e.reset()},restoreState(t){e.legacyValue=(0,p.Mo)(t)}}}setPhysicalScale(e,t){const n=this.curCanonicalVoxelPhysicalSize=this.canonicalVoxelPhysicalSize;this.value=e*(t/n)}assign(e){const{legacyValue:t}=e;Number.isNaN(t)?this.setPhysicalScale(e.value,e.canonicalVoxelPhysicalSize):this.legacyValue=t}}class UC extends Qp{getDefaultValue(){const{legacyValue_:e}=this;if(Number.isNaN(e))return 1;const{canonicalVoxelPhysicalSize:t}=this;return this.legacyValue_*1e-9/t}}class $C extends Qp{getDefaultValue(){const{legacyValue_:e}=this;if(!Number.isNaN(e)){this.legacyValue_=Number.NaN;const{canonicalVoxelPhysicalSize:a}=this;return 200*Math.tan(Math.PI/8)*1e-9*e/a}const{coordinateSpaceValue:{bounds:{lowerBounds:t,upperBounds:n}}}=this,{canonicalVoxelFactors:s,displayDimensionIndices:r}=this.displayDimensionRenderInfo.value;let o=s.reduce((a,l,c)=>{const d=r[c],u=(n[d]-t[d])*l;return Math.max(a,u)},0);return Number.isFinite(o)?o=2**Math.ceil(Math.log2(o)):o=1024,o}}class lc extends D.O8{constructor(e,t){super(),this.defaultValue=e,this.displayDimensionRenderInfo=t,this.changed=new j.IY,this.value_=e,this.canonicalVoxelPhysicalSize=t.value.canonicalVoxelPhysicalSize,this.registerDisposer(t.changed.add(()=>{this.value}))}get value(){let{value_:e}=this;if(e>0){const{canonicalVoxelPhysicalSize:t}=this.displayDimensionRenderInfo.value,n=this.canonicalVoxelPhysicalSize;t!==n&&(this.canonicalVoxelPhysicalSize=t,e=this.value_=e=n/t,this.changed.dispatch())}return e}set value(e){if(e===this.value)return;this.value_=e;const{canonicalVoxelPhysicalSize:t}=this.displayDimensionRenderInfo.value;this.canonicalVoxelPhysicalSize=t,this.changed.dispatch()}toJSON(){const{value:e}=this;if(e!==this.defaultValue)return e}reset(){this.value=this.defaultValue}restoreState(e){typeof e!="number"||!Number.isFinite(e)||e===0?this.value=this.defaultValue:this.value=e}setValueAbsolute(e,t){if(e>0){const{canonicalVoxelPhysicalSize:n}=this.displayDimensionRenderInfo.value;e=e*(t/n)}this.value=e}assign(e){this.setValueAbsolute(e.value,e.canonicalVoxelPhysicalSize)}}class qp extends $p{constructor(e,t){super(e),this.value=Bp(new lc(e.defaultValue,t),this.peer,this.link,{assign:(n,s)=>n.assign(s),isValid:()=>!0})}}class fs extends D.O8{constructor(e,t,n){super(),this.pose=e,this.zoomFactor=t,this.depthRange=n,this.changed=new j.IY,this.registerDisposer(e),this.registerDisposer(t),this.registerDisposer(n),this.registerDisposer(this.pose.changed.add(this.changed.dispatch)),this.registerDisposer(this.zoomFactor.changed.add(this.changed.dispatch)),this.registerDisposer(this.depthRange.changed.add(this.changed.dispatch))}get coordinateSpace(){return this.pose.position.coordinateSpace}reset(){this.pose.reset(),this.zoomFactor.reset()}get position(){return this.pose.position}get displayDimensions(){return this.pose.displayDimensions}get relativeDisplayScales(){return this.pose.relativeDisplayScales}get displayDimensionRenderInfo(){return this.pose.displayDimensionRenderInfo}toMat4(e){this.pose.toMat4(e,this.zoomFactor.value)}toMat3(e){this.pose.toMat3(e,this.zoomFactor.value)}get relativeDepthRange(){let e=this.depthRange.value;return e>0?e/=this.zoomFactor.value:e*=-1,e}get valid(){return this.pose.valid&&!Number.isNaN(this.zoomFactor.value)}zoomBy(e){this.zoomFactor.value*=e}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class GC{constructor(e){if(this.parents=new Array,this.parentPriorities=new Array,this.bindings=new Map,e!==void 0){this.parents.push(...e.parents),this.parentPriorities.push(...e.parentPriorities);for(const[t,n]of e.bindings)this.bindings.set(t,n)}}addParent(e,t){const{parents:n,parentPriorities:s}=this;let r=0;const{length:o}=n;for(;r<o&&t<s[r];)++r;return n.splice(r,0,e),s.splice(r,0,t),()=>{this.removeParent(e)}}removeParent(e){const t=this.parents.indexOf(e);if(t===-1)throw new Error("Attempt to remove non-existent parent map.");this.parents.splice(t,1),this.parentPriorities.splice(t,1)}set(e,t){this.bindings.set(e,t)}delete(e){this.bindings.delete(e)}clear(){this.bindings.clear(),this.parents.length=0,this.parentPriorities.length=0}get(e){const{parents:t,parentPriorities:n}=this,s=n.length;let r=0,o;for(;r<s&&n[r]>0;++r)if(o=t[r].get(e),o!==void 0)return o;if(o=this.bindings.get(e),o!==void 0)return o;for(;r<s;++r)if(o=t[r].get(e),o!==void 0)return o}*getAll(e){const{parents:t,parentPriorities:n}=this,s=n.length,r=0;let o;for(;r<s&&n[r]>0;)o=t[r].get(e),o!==void 0&&(yield o);for(o=this.bindings.get(e),o!==void 0&&(yield o);r<s;)o=t[r].get(e),o!==void 0&&(yield o)}*entries(){const{parents:e,parentPriorities:t}=this,n=t.length;let s=0;for(;s<n&&t[s]>0;++s)yield*e[s].entries();for(yield*this.bindings.entries();s<n;++s)yield*e[s].entries()}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var Kp=(i=>(i[i.CONTROL=1]="CONTROL",i[i.ALT=2]="ALT",i[i.META=4]="META",i[i.SHIFT=8]="SHIFT",i))(Kp||{});function cc(i){return(i.ctrlKey?1:0)|(i.altKey?2:0)|(i.metaKey?4:0)|(i.shiftKey?8:0)}function dc(i,e){let t="";return e&1&&(t+="control+"),e&2&&(t+="alt+"),e&4&&(t+="meta+"),e&8&&(t+="shift+"),t+=i,t}function zC(i,e,t){let n="";return e&1&&(n+="control+"),t&1&&(n+="control?+"),e&2&&(n+="alt+"),t&2&&(n+="alt?+"),e&4&&(n+="meta+"),t&4&&(n+="meta?+"),e&8&&(n+="shift+"),t&8&&(n+="shift?+"),n+=i,n}function Xp(i){const e=i.indexOf(":");let t;if(e!==-1&&(t=i.substring(0,e),t!=="at"&&t!=="bubble"))throw new Error(`Invalid event phase: ${JSON.stringify(t)}`);const n=i.substring(e+1).split("+");let s,r=0,o=0;e:for(const a of n)switch(a){case"control":r|=1;break;case"control?":o|=1;break;case"alt":r|=2;break;case"alt?":o|=2;break;case"meta":r|=4;break;case"meta?":o|=4;break;case"shift":r|=8;break;case"shift?":o|=8;break;default:if(s===void 0)s=a;else{s=void 0;break e}}if(s===void 0||r&o)throw new Error(`Invalid event identifier: ${JSON.stringify(i)}`);return{phase:t,keyName:s,modifiers:r,optionalModifiers:o}}function*WC(i,e,t){t===0&&(yield dc(i,e));for(let n=0;n<16;++n)(n&(e|t))===n&&(n&e)===e&&(yield dc(i,n))}function*Zp(i){const{phase:e}=i,t=WC(i.keyName,i.modifiers,i.optionalModifiers);if(e===void 0)for(const n of t)yield`at:${n}`,yield`bubble:${n}`;else for(const n of t)yield`${e}:${n}`}function HC(i,e){const t=zC(i.keyName,i.modifiers,i.optionalModifiers);return typeof e=="string"?{action:e,originalEventIdentifier:t}:{...e,originalEventIdentifier:t}}function JC(i){return i=i.replace(/^(?:at|bubble|capture)|(?:(?:shift|control|alt|meta)\?\+)/g,""),i}class Pe extends GC{static fromObject(e,t={}){const n=new Pe;if(n.label=t.label,t.parents!==void 0)for(const[s,r]of t.parents)n.addParent(s,r);for(const s of Object.keys(e))n.set(s,e[s]);return n}setFromObject(e){for(const t of Object.keys(e))this.set(t,e[t])}set(e,t){const n=Xp(e),s=HC(n,t);for(const r of Zp(n))super.set(r,s)}delete(e){for(const t of Zp(Xp(e)))super.delete(t)}describe(){const e=[],t=new Map;for(const[,s]of this.entries())t.set(s.originalEventIdentifier,s.action);const n=new Map;for(const[s,r]of t){let o=n.get(r);o===void 0&&(o=[],n.set(r,o)),o.push(JC(s))}for(const[s,r]of n){const o=r.length===1?r[0]:`{${r.join(",")}}`;e.push(`${o}\u2192${s}`)}return e.join(", ")}}function ef(i,e,t){if(t===void 0)return;t.stopPropagation!==!1&&i.stopPropagation();const n=new CustomEvent("action:"+t.action,{bubbles:!0,detail:e,cancelable:!0}),s=!i.target.dispatchEvent(n);(t.preventDefault!==!1||s)&&i.preventDefault()}const To=[];To[Event.AT_TARGET]="at",To[Event.CAPTURING_PHASE]="capture",To[Event.BUBBLING_PHASE]="bubble";function tf(i,e,t,n,s){const r=To[t]+":"+i,o=s.get(r);ef(e,n,o)}function nf(i,e,t,n){tf(dc(i,cc(e)),e,e.eventPhase,t,n)}function X(i,e,t,n){return(0,D.K6)(i,`action:${e}`,t,n)}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class fn extends D.O8{constructor(e,t,n){super(),this.target=e,this.eventMap=t,this.shouldIgnore=void 0,this.registerEventListener(e,"wheel",s=>{n!==void 0&&n(s),this.dispatch("wheel",s)}),this.registerEventListener(e,"click",s=>{n!==void 0&&n(s),this.dispatch(`click${s.button}`,s)}),this.registerEventListener(e,"dblclick",s=>{n!==void 0&&n(s),this.dispatch(`dblclick${s.button}`,s)}),this.registerEventListener(e,"mousedown",s=>{n!==void 0&&n(s);let r=s.button;r===2&&(s.buttons&3)===1&&(r=0),this.dispatch(`mousedown${r}`,s)}),this.registerEventListener(e,"mouseup",s=>{n!==void 0&&n(s),this.dispatch(`mouseup${s.button}`,s)})}dispatch(e,t){this.shouldIgnore?.(t)||nf(e,t,t,this.eventMap)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function $t(i,e,t){const{document:n}=i.view;let s=i.clientX,r=i.clientY;const o=d=>{const u=d.clientX-s,h=d.clientY-r;s=d.clientX,r=d.clientY,e(d,u,h)},a=i.button,l=d=>{n.removeEventListener("pointermove",o,!0),n.removeEventListener("pointerup",c,!1),t!==void 0&&t(d,d.clientX-s,d.clientY-r)},c=d=>{d.button===a&&l(d)};n.addEventListener("pointermove",o,!0),n.addEventListener("pointerup",c,!1),n.addEventListener("pointercancel",l,!1)}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const fr=6,S_=2,uc=`
vec2 getQuadVertexPosition(vec2 lower, vec2 upper) {
  const vec2 coeffs[] = vec2[](
    vec2(0.0, 0.0),
    vec2(0.0, 1.0),
    vec2(1.0, 1.0),
    vec2(1.0, 1.0),
    vec2(1.0, 0.0),
    vec2(0.0, 0.0)
  );
  int v = gl_VertexID % 6;
  return mix(lower, upper, coeffs[v]);
}
`;function Do(i,e,t){i.drawArraysInstanced(WebGL2RenderingContext.TRIANGLES,0,fr*e,t)}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const gn=fr;function Tn(i,e=!1){i.addVertexCode(uc),i.addUniform("highp vec3","uLineParams"),i.addVarying("highp float","vLineCoord"),i.addVarying("highp float","vLineFeatherFraction"),e&&(i.addVarying("highp float","vEndpointFraction"),i.addVarying("highp float","vLineCoordT"),i.addVarying("highp float","vLineBorderStartFraction")),i.addVertexCode(SC),i.addVertexCode(`
vec2 getLineOffset() { return getQuadVertexPosition(vec2(0.0, -1.0), vec2(1.0, 1.0)); }
float getLineEndpointCoefficient() { return getLineOffset().x; }
uint getLineEndpointIndex() { return uint(getLineEndpointCoefficient()); }
void emitLine(vec4 vertexAClip, vec4 vertexBClip, float lineWidthInPixels
              ${e?", float borderWidth":""}) {
  if (!clipLineToDepthRange(vertexAClip, vertexBClip)) {
    gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
    return;
  }
  vec3 vertexADevice = vertexAClip.xyz / vertexAClip.w;
  vec3 vertexBDevice = vertexBClip.xyz / vertexBClip.w;

  vec2 lineDirectionUnnormalized = vertexBDevice.xy - vertexADevice.xy;
  vec2 lineDirection;
  float linePixelLength = length(lineDirectionUnnormalized / uLineParams.xy * 0.5);

  if (linePixelLength < 1e-3) {
    lineDirection = vec2(1.0, 0.0);
    vertexADevice.z = vertexBDevice.z = 0.0;
  } else {
    lineDirection = normalize(lineDirectionUnnormalized);
  }
  vec2 lineNormal = normalize(vec2(lineDirection.y, -lineDirection.x) / uLineParams.yx * uLineParams.xy);

  vec2 lineOffset = getLineOffset();
  gl_Position = vec4(mix(vertexADevice, vertexBDevice, lineOffset.x), 1.0);
  float totalLineWidth = lineWidthInPixels + 2.0 * uLineParams.z ${e?" + 2.0 * borderWidth":""};
  if (lineWidthInPixels == 0.0) totalLineWidth = 0.0;
  vLineFeatherFraction = max(1e-6, uLineParams.z) / totalLineWidth;
  gl_Position.xy += (lineOffset.y * lineNormal
                     ${e?"+ lineDirection * (2.0 * lineOffset.x - 1.0)":""})
                  * totalLineWidth * uLineParams.xy;
  vLineCoord = lineOffset.y;
  ${e?"vEndpointFraction = totalLineWidth / (linePixelLength + totalLineWidth * 2.0);":""}
  ${e?"vLineCoordT = lineOffset.x; vLineBorderStartFraction = lineWidthInPixels / totalLineWidth;":""}
}
void emitLine(mat4 projection, vec3 vertexA, vec3 vertexB, float lineWidthInPixels
              ${e?", float borderWidth":""}) {
  emitLine(projection * vec4(vertexA, 1.0), projection * vec4(vertexB, 1.0),
           lineWidthInPixels
           ${e?", borderWidth":""});
}
`),e&&i.addFragmentCode(`
vec4 getRoundedLineColor(vec4 interiorColor, vec4 borderColor) {
  float radius;
  if (vLineCoordT < vEndpointFraction || vLineCoordT > 1.0 - vEndpointFraction) {
    radius = length(vec2(1.0 - min(vLineCoordT, 1.0 - vLineCoordT) / vEndpointFraction,
                         vLineCoord));
    if (radius > 1.0) {
      discard;
    }
  } else {
    radius = abs(vLineCoord);
  }
  float borderColorFraction = clamp((radius - vLineBorderStartFraction) / vLineFeatherFraction, 0.0, 1.0);
  float feather = clamp((1.0 - radius) / vLineFeatherFraction, 0.0, 1.0);
  vec4 color = mix(interiorColor, borderColor, borderColorFraction);
  return vec4(color.rgb, color.a * feather);
}
`),i.addFragmentCode(`
float getLineAlpha() {
  return clamp((1.0 - abs(vLineCoord)) / vLineFeatherFraction, 0.0, 1.0);
}
`)}function Dn(i,e,t){Do(i,e,t)}function In(i,e,t){const{gl:n}=i;n.uniform3f(i.uniform("uLineParams"),1/e.width,1/e.height,t)}/**
 * @license
 * Copyright 2024 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function sf(i,e=-1,t=1,n=1,s=-1){const r=new Float32Array(i*fr*2),o=(t-e)/i;let a=e;for(let l=0;l<i;++l){const c=l*fr*2;r[c]=a,r[c+1]=n,r[c+2]=a+o,r[c+3]=n,r[c+4]=a+o,r[c+5]=s,r[c+6]=a,r[c+7]=n,r[c+8]=a+o,r[c+9]=s,r[c+10]=a,r[c+11]=s,a+=o}return r}function b_(i,e,t=-1,n=1,s=1,r=-1){return getMemoizedBuffer(i,WebGL2RenderingContext.ARRAY_BUFFER,sf,e,t,n,s,r).value}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Io(i,e,t,n){e*=6;const s=Math.floor(e),r=e-s,o=n*(1-t),a=n*(1-t*r),l=n*(1-t*(1-r));switch(s%6){case 0:i[0]=n,i[1]=l,i[2]=o;break;case 1:i[0]=a,i[1]=n,i[2]=o;break;case 2:i[0]=o,i[1]=n,i[2]=l;break;case 3:i[0]=o,i[1]=a,i[2]=n;break;case 4:i[0]=l,i[1]=o,i[2]=n;break;case 5:i[0]=n,i[1]=o,i[2]=a;break}return i}function jC(i,e,t,n){const s=Math.max(Math.max(e,t),n),r=Math.min(Math.min(e,t),n);if(i[2]=s,r===s)i[0]=0,i[1]=0;else{const o=s-r;i[1]=o/s,e===s?i[0]=(t-n)/o:t===s?i[0]=2+(n-e)/o:i[0]=4+(e-t)/o,i[0]/=6,i[0]<0&&(i[0]+=1),i[0]>1&&(i[0]-=1)}return i}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Ro extends D.O8{constructor(e,t=()=>w.eR.fromValues(1,0,0)){super(),this.model=e,this.getDefaultColor=t,this.element=document.createElement("input");const{element:n}=this;n.classList.add("neuroglancer-color-widget"),n.type="color",n.addEventListener("change",()=>this.updateModel()),n.addEventListener("input",()=>this.updateModel()),n.addEventListener("wheel",s=>{s.stopPropagation(),s.preventDefault(),this.adjustHueViaWheel(s)}),this.registerDisposer(e.changed.add(()=>this.updateView())),this.updateView()}getRGB(){return this.model.value??this.getDefaultColor()}updateView(){this.element.value=ze(this.getRGB())}updateModel(){this.model.value=me(this.element.value)}adjustHueViaWheel(e){const t=this.getRGB(),n=w.eR.create();jC(n,t[0],t[1],t[2]);const{deltaY:s}=e;let r=Math.round(n[0]*256);r+=s>0?1:s<0?-1:0,r=(r+256)%256,n[0]=r/256,Io(n,n[0],n[1],n[2]),this.model.value=n}}var rf=G(2104),of=G(2809);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ae(i){for(;;){const e=i.firstChild;if(!e)break;i.removeChild(e)}}function lt(i){const{parentElement:e}=i;return e?(e.removeChild(i),!0):!1}function Ft(i,e=Math.max(1,i.value.length)){const t=`${e}ch`;i.style.width!==t&&(i.style.width="0px",i.offsetWidth,i.style.width=t)}function Zt(i,e){let t=i.firstElementChild;for(const n of e)n!==t&&i.insertBefore(n,t),t=n.nextElementSibling;for(;t!==null;){const n=t.nextElementSibling;i.removeChild(t),t=n}}function hc(i){return i instanceof HTMLElement?!!(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i.isContentEditable):!1}function YC(i){const e=i.cloneNode(!0);return e.style.position="absolute",document.body.appendChild(e),e.getBoundingClientRect()}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const QC=0,qC=1,KC=2;function gs(i){let e=0;const{deltaMode:t}=i;switch(t){case QC:e=.005;break;case qC:e=.1;break;case KC:e=2;break}return Math.exp(i.deltaY*e)}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function w_(i){const e=_e(i);return i.svgHover&&(e.classList.add("neuroglancer-icon-hover"),e.innerHTML+=i.svgHover),e}function _e(i){const{title:e,onClick:t,href:n}=i;let s;n!==void 0?(s=document.createElement("a"),s.href=n,s.target="_blank"):s=document.createElement("div"),e!==void 0&&(s.title=e),t!==void 0&&s.addEventListener("click",t);const{svg:r}=i;return s.className="neuroglancer-icon",r!==void 0&&(s.innerHTML=r),i.text!==void 0&&s.appendChild(document.createTextNode(i.text)),s}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Gt extends D.O8{constructor(e=new ht(ht.VISIBLE)){super(),this.visibility=e,this.element=document.createElement("div");const{element:t}=this;t.classList.add("neuroglancer-tab-content")}get visible(){return this.visibility.visible}disposed(){lt(this.element),super.disposed()}}class XC extends D.O8{constructor(){super(...arguments),this.changed=new j.IY,this.options=new Map,this.optionsChanged=new j.IY,this.selectedValue=void 0,this.defaultValue=void 0,this.ready_=!0}get value(){const{selectedValue:e}=this;return e!==void 0?e:this.defaultValue}set default(e){this.defaultValue!==e&&(this.defaultValue=e,this.changed.dispatch())}get default(){return this.defaultValue}set value(e){e!==void 0&&this.ready_&&!this.options.has(e)&&(e=void 0);const{selectedValue:t}=this;t!==e&&(this.selectedValue=e,this.changed.dispatch())}get validValue(){const e=this.selectedValue;return e===void 0||!this.options.has(e)?this.defaultValue:e}add(e,t){const{options:n}=this;if(n.has(e))throw new Error(`Option already defined: ${JSON.stringify(e)}.`);n.set(e,t),this.optionsChanged.dispatch(),this.defaultValue===void 0&&(this.default=e)}remove(e){const{options:t}=this;if(!t.has(e))throw new Error(`Option is not defined: ${JSON.stringify(e)}.`);t.delete(e),this.optionsChanged.dispatch()}toJSON(){const{value:e,defaultValue:t}=this;if(e!==t)return e}reset(){this.value=void 0}get ready(){return this.ready_}set ready(e){e!==this.ready_&&(this.ready_=e,e&&(this.value=this.value),this.changed.dispatch())}restoreState(e){typeof e!="string"&&(e=void 0),this.value=e}}class ZC extends D.O8{constructor(e,t,n=new ht(ht.VISIBLE),s=!1){super(),this.getter=e,this.selected=t,this.visibility=n,this.invalidateByDefault=s,this.element=document.createElement("div"),this.tabs=new Map,this.tabVisibilityChanged=new j.HN,this.debouncedUpdateSelectedTab=this.registerCancellable((0,je.t)(()=>this.updateSelectedTab()));const{element:r}=this;r.className="neuroglancer-stack-view",this.registerDisposer(n.changed.add(this.debouncedUpdateSelectedTab)),this.registerDisposer(t.changed.add(this.debouncedUpdateSelectedTab)),this.updateSelectedTab()}get visible(){return this.visibility.visible}flush(){this.debouncedUpdateSelectedTab.flush()}invalidate(e){const{tabs:t}=this,n=t.get(e);n!==void 0&&(n.dispose(),t.delete(e),e===this.displayedTab&&(this.displayedTab=void 0,this.debouncedUpdateSelectedTab()))}hideTab(e){const t=this.tabs.get(e);t!==void 0&&(t.visibility.value=ht.IGNORED,t.element.style.display="none"),this.tabVisibilityChanged.dispatch(e,!1)}showTab(e){const{tabs:t}=this;let n=t.get(e);n===void 0&&(n=this.getter(e),this.element.appendChild(n.element),t.set(e,n)),n.element.style.display="",n.visibility.value=ht.VISIBLE,this.tabVisibilityChanged.dispatch(e,!0)}updateSelectedTab(){const{displayedTab:e}=this,t=this.visible?this.selected.value:void 0;t===e&&(t===void 0||this.tabs.has(t))||(e!==void 0&&this.hideTab(e),this.invalidateByDefault&&this.invalidateAll(),this.displayedTab=t,t!==void 0&&this.showTab(t))}invalidateAll(e=void 0){const{tabs:t}=this;for(const[n,s]of t)e?.(n)||(t.delete(n),s.dispose());this.debouncedUpdateSelectedTab()}disposed(){this.invalidateAll(),lt(this.element),super.disposed()}}class ex extends XC{}function tx(i,e){const t="neuroglancer-selected-tab-label";e?i.classList.add(t):i.classList.remove(t)}class nx extends D.O8{constructor(e,t=new ht(ht.VISIBLE)){super(),this.visibility=t,this.element=document.createElement("div"),this.tabBar=document.createElement("div"),this.tabLabels=new Map,this.tabsGeneration=-1,this.debouncedUpdateView=this.registerCancellable((0,je.t)(()=>this.updateTabs())),this.tabs=e.tabs,this.selectedTab=e.selectedTab,this.handleTabElement=e.handleTabElement;const{element:n,tabBar:s}=this;n.className="neuroglancer-tab-view",s.className="neuroglancer-tab-view-bar",n.appendChild(s),this.registerDisposer(t.changed.add(this.debouncedUpdateView));const r=this.stack=this.registerDisposer(new ZC(e.makeTab,e.selectedTab,this.visibility));n.appendChild(r.element),this.registerDisposer(e.tabs.changed.add(this.debouncedUpdateView));let o=this.selectedTab.value;this.registerDisposer(e.selectedTab.changed.add(()=>{this.tabs.value.find(({id:c})=>c===o)?.hidden?(this.tabs.changed.count++,this.debouncedUpdateView()):this.updateTabLabelStyles(),o=this.selectedTab.value})),this.updateTabs()}get visible(){return this.visibility.visible}updateTabLabelStyles(){const e=this.selectedTab.value;for(const[t,n]of this.tabLabels)tx(n,t===e)}updateTabs(){this.tabsGeneration!==this.tabs.changed.count&&(this.destroyTabs(),this.visible&&this.makeTabs())}destroyTabs(){if(this.tabsGeneration!==-1){if(this.tabLabels.clear(),!this.visible)this.stack.invalidateAll();else{const e=this.tabs.value;this.stack.invalidateAll(t=>e.find(({id:n})=>n===t)!==void 0)}Ae(this.tabBar),this.tabsGeneration=-1}}makeTabs(){const{tabBar:e,tabLabels:t,handleTabElement:n}=this;for(const{id:s,label:r,hidden:o}of this.tabs.value){if(o&&s!==this.selectedTab.value)continue;const a=document.createElement("div");a.classList.add("neuroglancer-tab-label"),a.textContent=r,a.addEventListener("click",()=>{this.selectedTab.value=s}),n!==void 0&&n(s,a),t.set(s,a),e.appendChild(a)}this.updateTabLabelStyles(),this.tabsGeneration=this.tabs.changed.count}disposed(){Ae(this.tabBar),this.tabLabels.clear(),lt(this.element),super.disposed()}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const af=Pe.fromObject({"shift?+mousedown0":{action:"set"},"shift?+alt+mousedown0":{action:"adjust-window-via-drag"},"shift?+wheel":{action:"zoom-via-wheel"}});class lf extends D.O8{constructor(e,t,n,s){super(),this.element=e,this.dataType=t,this.getModel=n,this.setModel=s,e.title=af.describe(),this.registerDisposer(new fn(e,af)),X(e,"set",r=>{const o=r.detail,a=this.getModel(),l=this.getTargetValue(o);if(l===void 0)return;const c=qe(a.window,a.range),d=Vn(c,l),u=h=>{const f=this.getModel();this.setModel(gr(f,"range",d,h))};u(l),$t(o,h=>{const f=this.getTargetValue(h);f!==void 0&&u(f)})}),X(e,"adjust-window-via-drag",r=>{const o=r.detail,a=this.getTargetFraction(o),l=this.getWindowLerp(a),c=a<.5?0:1,d=u=>{const h=this.getModel();this.setModel(gr(h,"window",c,u))};$t(o,u=>{const h=this.getModel().window,f=this.getTargetFraction(u);d(c===0?he([l,h[1]],this.dataType,-f/(1-f)):he([h[0],l],this.dataType,1/f))})}),X(e,"zoom-via-wheel",r=>{const o=r.detail,a=gs(o),l=this.getTargetFraction(o),{dataType:c}=this,d=this.getModel(),u=he(d.window,c,l*(1-a)),h=he(d.window,c,(1-l)*a+l);this.setModel({...d,window:[u,h],range:d.range})})}getTargetFraction(e){const t=this.element.getBoundingClientRect();return(e.clientX-t.left)/t.width}getWindowLerp(e){return he(this.getModel().window,this.dataType,e)}getTargetValue(e){const t=this.getTargetFraction(e);if(Number.isFinite(t))return this.getWindowLerp(t)}}const cf=Symbol("histogramSamplerTexture");function gr(i,e,t,n,s=!1){const r={...i},o=i[e];if(r[e]=[o[0],o[1]],r[e][t]=n,e==="window"&&nt(n,o[1-t])*(2*t-1)<0&&(r[e][1-t]=n),e==="range"&&s){const a=[i.window[0],i.window[1]];for(let l=0;l<2;++l)nt(n,a[l])*(2*l-1)>0&&(a[l]=n);r.window=a}return r}const mr=254+1;class ix extends Jl{constructor(e){super(e.display,document.createElement("div"),e.visibility),this.parent=e,this.controller=this.registerDisposer(new lf(this.element,this.parent.dataType,()=>this.parent.trackable.value,n=>{this.parent.trackable.value=n})),this.dataValuesBuffer=this.registerDisposer(Ri(this.gl,WebGL2RenderingContext.ARRAY_BUFFER,()=>{const n=new Uint8Array(mr*gn);for(let s=0;s<mr;++s)for(let r=0;r<gn;++r)n[s*gn+r]=s;return n})).value,this.lineShader=this.registerDisposer((()=>{const n=new hn(this.gl);return Tn(n),n.addTextureSampler("sampler2D","uHistogramSampler",cf),n.addOutputBuffer("vec4","out_color",0),n.addAttribute("uint","aDataValue"),n.addUniform("float","uBoundsFraction"),n.addVertexCode(`
float getCount(int i) {
  return texelFetch(uHistogramSampler, ivec2(i, 0), 0).x;
}
vec4 getVertex(float cdf, int i) {
  float x;
  if (i == 0) {
    x = -1.0;
  } else if (i == 255) {
    x = 1.0;
  } else {
    x = float(i) / 254.0 * uBoundsFraction * 2.0 - 1.0;
  }
  return vec4(x, cdf * (2.0 - uLineParams.y) - 1.0 + uLineParams.y * 0.5, 0.0, 1.0);
}
`),n.setVertexMain(`
int lineNumber = int(aDataValue);
int dataValue = lineNumber;
float cumSum = 0.0;
for (int i = 0; i <= dataValue; ++i) {
  cumSum += getCount(i);
}
float total = cumSum + getCount(dataValue + 1);
float cumSumEnd = dataValue == ${mr-1} ? cumSum : total;
if (dataValue == ${mr-1}) {
  cumSum + getCount(dataValue + 1);
}
for (int i = dataValue + 2; i < 256; ++i) {
  total += getCount(i);
}
total = max(total, 1.0);
float cdf1 = cumSum / total;
float cdf2 = cumSumEnd / total;
emitLine(getVertex(cdf1, lineNumber), getVertex(cdf2, lineNumber + 1), 1.0);
`),n.setFragmentMain(`
out_color = vec4(0.0, 1.0, 1.0, getLineAlpha());
`),n.build()})()),this.regionCornersBuffer=lr(this.gl,0,-1,1,1),this.regionShader=this.registerDisposer((()=>{const n=new hn(this.gl);return n.addAttribute("vec2","aVertexPosition"),n.addUniform("vec2","uBounds"),n.addUniform("vec4","uColor"),n.addOutputBuffer("vec4","out_color",0),n.setVertexMain(`
gl_Position = vec4(mix(uBounds[0], uBounds[1], aVertexPosition.x) * 2.0 - 1.0, aVertexPosition.y, 0.0, 1.0);
`),n.setFragmentMain(`
out_color = uColor;
`),n.build()})());const{element:t}=this;t.classList.add("neuroglancer-invlerp-cdfpanel")}get drawOrder(){return 100}drawIndirect(){const{lineShader:e,gl:t,regionShader:n,parent:{dataType:s,trackable:{value:r}}}=this;this.setGLLogicalViewport(),t.clearColor(0,0,0,0),t.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT),t.enable(WebGL2RenderingContext.BLEND),t.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),t.disable(WebGL2RenderingContext.DEPTH_TEST),t.disable(WebGL2RenderingContext.STENCIL_TEST);{n.bind(),t.uniform4f(n.uniform("uColor"),.2,.2,.2,1);const o=se(r.window,r.range[0]),a=se(r.window,r.range[1]),l=Ce(s,r.window);t.uniform2f(n.uniform("uBounds"),Math.min(o,a)*l,Math.max(o,a)*l+(1-l));const c=n.attribute("aVertexPosition");this.regionCornersBuffer.bindToVertexAttrib(c,2,WebGL2RenderingContext.FLOAT),t.drawArrays(WebGL2RenderingContext.TRIANGLE_FAN,0,4),t.disableVertexAttribArray(c)}if(this.parent.histogramSpecifications.producerVisibility.visible){const{renderViewport:o}=this;e.bind(),In(e,{width:o.logicalWidth,height:o.logicalHeight},1);const a=e.textureUnit(cf);t.uniform1f(e.uniform("uBoundsFraction"),Ce(s,r.window)),t.activeTexture(WebGL2RenderingContext.TEXTURE0+a),t.bindTexture(WebGL2RenderingContext.TEXTURE_2D,this.parent.texture),ki(t);const l=e.attribute("aDataValue");this.dataValuesBuffer.bindToVertexAttribI(l,1,WebGL2RenderingContext.UNSIGNED_BYTE),Dn(t,mr,1),t.disableVertexAttribArray(l),t.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}t.disable(WebGL2RenderingContext.BLEND)}isReady(){return!0}}function sx(){}class rx extends Jl{constructor(e){super(e.display,document.createElement("div"),e.visibility),this.parent=e,this.cornersBuffer=lr(this.gl,-1,-1,1,1);const{element:t}=this;t.classList.add("neuroglancer-invlerp-legend-panel");const n=this.shaderOptions=e.legendShaderOptions;this.shaderGetter=Ii(this,this.gl,{...n,memoizeKey:{id:"colorLegendShader",base:n.memoizeKey},defineShader:(s,r,o)=>{s.addOutputBuffer("vec4","v4f_fragData0",0),s.addAttribute("vec2","aVertexPosition"),s.addUniform("float","uLegendOffset"),s.addVarying("float","vLinearPosition"),s.setVertexMain(`
gl_Position = vec4(aVertexPosition, 0.0, 1.0);
vLinearPosition = -uLegendOffset + ((aVertexPosition.x + 1.0) * 0.5) * (1.0 + 2.0 * uLegendOffset);
`);const a=this.parent.dataType,l=vt(a);s.addFragmentCode(LC(s,"ng_colorLegendLerp",a)),s.addFragmentCode(`
void emit(vec4 v) {
  v4f_fragData0 = v;
}
${l} getDataValue() {
  return ng_colorLegendLerp(vLinearPosition);
}
${l} getDataValue(int dummyChannel) {
  return getDataValue();
}
${l} getInterpolatedDataValue() {
  return getDataValue();
}
${l} getInterpolatedDataValue(int dummyChannel) {
  return getDataValue();
}
`),n.defineShader(s,r,o)}})}drawIndirect(){const e=this.shaderGetter(sx),{shader:t}=e;if(t===null)return;this.setGLLogicalViewport();const{gl:n}=this;n.clearColor(0,0,0,0),n.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT),t.bind(),this.shaderOptions.initializeShader(e),n.enable(WebGL2RenderingContext.BLEND);const{trackable:{value:{window:s}},dataType:r}=this.parent;Pi(t,"ng_colorLegendLerp",this.parent.dataType,s);const o=ae(r,s);n.uniform1f(t.uniform("uLegendOffset"),Number.isFinite(o)?o:0),n.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),n.disable(WebGL2RenderingContext.DEPTH_TEST),n.disable(WebGL2RenderingContext.STENCIL_TEST);const a=t.attribute("aVertexPosition");this.cornersBuffer.bindToVertexAttrib(a,2,WebGL2RenderingContext.FLOAT),n.drawArrays(WebGL2RenderingContext.TRIANGLE_FAN,0,4),n.disableVertexAttribArray(a)}isReady(){return!0}}function df(i,e){const t=document.createElement("input");return t.addEventListener("focus",()=>{t.select()}),t.classList.add("neuroglancer-invlerp-widget-bound"),t.classList.add(`neuroglancer-invlerp-widget-${i}-bound`),t.type="text",t.spellcheck=!1,t.autocomplete="off",t.title=i==="range"?`Data value that maps to ${e}`:`${e===0?"Lower":"Upper"} bound for distribution`,t}function uf(i,e,t){const n=document.createElement("div");n.classList.add("neuroglancer-invlerp-widget-bounds"),n.classList.add(`neuroglancer-invlerp-widget-${i}-bounds`);const s=[df(i,0),df(i,1)];for(let o=0;o<2;++o){const a=s[o];a.addEventListener("input",()=>{pc(a)}),a.addEventListener("change",()=>{const l=t.value,c=l[i];try{const d=qt(e,a.value);t.value=gr(l,i,o,d,!0)}catch{ms(a,c[o])}})}let r;return n.appendChild(s[0]),n.appendChild(s[1]),i==="range"&&(r=[document.createElement("div"),document.createElement("div"),document.createElement("div")],r[1].classList.add("neuroglancer-invlerp-widget-range-spacer"),n.insertBefore(r[0],s[0]),n.insertBefore(r[1],s[1]),n.appendChild(r[2])),{container:n,inputs:s,spacers:r}}function pc(i){Ft(i,Math.max(1,i.value.length+.1))}function ms(i,e){let t;e instanceof M.R||Number.isInteger(e)?t=e.toString():t=e.toPrecision(6),i.value=t,pc(i)}function hf(i){const e=i.value,{range:t}=e;i.value={...e,range:[t[1],t[0]]}}function ox(i,e,t){const n=e.value,s=he(n.range,i,.5-t/2),r=he(n.range,i,.5+t/2);e.value={...n,range:[s,r]}}function ax(i,e,t,n,s){const r=Math.exp(s),o=e.value,a=he(t,i,.5-r/2+n),l=he(t,i,.5+r/2+n);e.value={...o,range:[a,l]}}class pf extends Gt{constructor(e,t,n,s,r,o,a){super(e),this.display=t,this.dataType=n,this.trackable=s,this.histogramSpecifications=r,this.histogramIndex=o,this.legendShaderOptions=a,this.cdfPanel=this.registerDisposer(new ix(this)),this.boundElements={range:uf("range",this.dataType,this.trackable),window:uf("window",this.dataType,this.trackable)},this.registerDisposer(r.visibility.add(this.visibility));const{element:l,boundElements:c}=this;if(a!==void 0){const u=this.registerDisposer(new rx(this));l.appendChild(u.element)}const d=u=>{const h=_e({svg:u,title:"Invert range",onClick:()=>{this.invertRange()}});return c.range.spacers[1].appendChild(h),h};this.invertArrows=[d(of),d(rf)],l.appendChild(c.range.container),l.appendChild(this.cdfPanel.element),l.classList.add("neuroglancer-invlerp-widget"),l.appendChild(c.window.container),this.updateView(),this.registerDisposer(s.changed.add(this.registerCancellable((0,je.t)(()=>this.updateView()))))}get texture(){return this.histogramSpecifications.getFramebuffers(this.display.gl)[this.histogramIndex].colorBuffers[0].texture}invertRange(){hf(this.trackable)}updateView(){const{boundElements:e}=this,{trackable:{value:t},dataType:n}=this;for(let u=0;u<2;++u)ms(e.range.inputs[u],t.range[u]),ms(e.window.inputs[u],t.window[u]);const s=nt(t.range[0],t.range[1])>0;e.range.container.style.flexDirection=s?"row-reverse":"row";const r=qe(t.window,t.range),o=e.range.spacers,a=Ce(n,t.window),l=se(t.window,r[s?1:0])*a,c=se(t.window,r[s?0:1])*a+(1-a);o[s?2:0].style.width=`${l*100}%`,o[s?0:2].style.width=`${(1-c)*100}%`;const{invertArrows:d}=this;d[s?1:0].style.display="",d[s?0:1].style.display="none"}}class lx extends Gt{constructor(e,t,n,s,r,o,a){super(e),this.display=t,this.watchableDataType=n,this.trackable=s,this.histogramSpecifications=r,this.histogramIndex=o,this.legendShaderOptions=a,this.invlerpWidget=this.makeInvlerpWidget(),this.registerDisposer(n.changed.add(()=>{Ae(this.element),this.invlerpWidget.dispose(),this.invlerpWidget=this.makeInvlerpWidget()}))}get dataType(){return this.watchableDataType.value}disposed(){this.invlerpWidget.dispose(),super.disposed()}makeInvlerpWidget(){const{dataType:e}=this,t=new pf(this.visibility,this.display,e,this.trackable,this.histogramSpecifications,this.histogramIndex,this.legendShaderOptions);return this.element.appendChild(t.element),t}}const cx=Pe.fromObject({"at:shift+wheel":{action:"adjust-contrast-via-wheel"},"at:shift+mousedown0":{action:"adjust-via-drag"},"at:shift+mousedown2":{action:"invert-range"}});function ff(i,e){i.bindInputEventMap(cx),i.bindAction("adjust-contrast-via-wheel",t=>{t.stopPropagation();const n=gs(t.detail);ox(e.dataType,e.trackable,n)}),i.bindAction("adjust-via-drag",t=>{t.stopPropagation();let n=t.detail.screenX,s=t.detail.screenY,r=e.trackable.value.range,o=r,a=n,l=s;$t(t.detail,c=>{const d=e.trackable.value.range,u=c.screenX,h=c.screenY;O(e.dataType,d,o)||(r=d,n=a,s=l),ax(e.dataType,e.trackable,r,(h-s)*2/screen.height,(u-n)*4/screen.width),o=e.trackable.value.range,a=u,l=h})}),i.bindAction("invert-range",t=>{t.stopPropagation(),hf(e.trackable)})}var gf=G(5061),mf=G(7349),vf=G(350);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Ni=null;const dx=200;class Se{constructor(e=!1){if(Ni===null){Ni=document.createElement("ul"),Ni.id="statusContainer";const n=document.getElementById("neuroglancer-container");n?n.appendChild(Ni):document.body.appendChild(Ni)}const t=document.createElement("li");this.element=t,e===!0&&(e=dx),e!==!1?(this.setVisible(!1),this.timer=window.setTimeout(this.setVisible.bind(this,!0),e)):this.timer=null,Ni.appendChild(t)}dispose(){Ni.removeChild(this.element),this.element=void 0,this.timer!==null&&clearTimeout(this.timer)}setText(e,t){this.element.textContent=e,t&&this.setVisible(!0)}setHTML(e,t){this.element.innerHTML=e,t&&this.setVisible(!0)}setVisible(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.element.style.display=e?"block":"none"}static forPromise(e,t){const n=new Se(t.delay);n.setText(t.initialMessage);const s=n.dispose.bind(n);return e.then(s,r=>{let o;r instanceof Error?o=r.message:o=""+r;const{errorPrefix:a=""}=t;n.setErrorMessage(a+o),n.setVisible(!0)}),e}setErrorMessage(e){this.element.textContent=e+" ";const t=document.createElement("button");t.textContent="Dismiss",t.addEventListener("click",()=>{this.dispose()}),this.element.appendChild(t)}static showMessage(e){const t=new Se;return t.element.textContent=e,t.setVisible(!0),t}static showTemporaryMessage(e,t=2e3){const n=Se.showMessage(e);return window.setTimeout(()=>n.dispose(),t),n}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ux=/^[A-Z]$/;class yf extends D.O8{constructor(e,t){super(),this.tool=e,this.inputEventMapBinder=t}bindAction(e,t){this.registerDisposer(X(window,e,t))}bindInputEventMap(e){this.inputEventMapBinder(e,this)}cancel(){const{globalBinder:e}=this.tool;this===e.activeTool_&&e.deactivate_()}}class ko extends D.O8{constructor(e,t=!1){super(),this.localBinder=e,this.toggle=t,this.changed=new j.HN,this.keyBinding=void 0}get context(){return this.localBinder.context}get globalBinder(){return this.localBinder.globalBinder}unbind(){const{keyBinding:e}=this;e!==void 0&&this.localBinder.set(e,void 0)}}class vs extends ko{constructor(e,t=!1){super(e.toolBinder,t),this.layer=e}get mouseState(){return this.layer.manager.root.layerSelectedValues.mouseState}}class Sf extends D.O8{constructor(e){super(),this.layer=e,this.changed=new j.HN}get context(){return this.layer}get mouseState(){return this.layer.manager.root.layerSelectedValues.mouseState}deactivate(){}unbind(){const{layer:e}=this;e.tool.value===this&&(e.tool.value=void 0)}}function bf(i,e){if(e===void 0)return;typeof e=="string"&&(e={type:e}),(0,p.Rf)(e);const t=(0,p.cQ)(e,"type",p.zr);let n=i,s;for(;;){if(n=Object.getPrototypeOf(n),n===null)throw new Error(`Invalid tool type: ${JSON.stringify(e)}.`);if(s=fc.get(n)?.get(t),s!==void 0)break}return s(i,e)}function hx(i,e){if(e===void 0)return;typeof e=="string"&&(e={type:e}),(0,p.Rf)(e);const t=(0,p.cQ)(e,"type",p.zr),n=wf.get(t);if(n===void 0)throw new Error(`Invalid tool type: ${JSON.stringify(e)}.`);return n(i,e)}const wf=new Map,fc=new Map;function vr(i,e){wf.set(i,e)}function Rn(i,e,t){const{prototype:n}=i;let s=fc.get(n);s===void 0&&(s=new Map,fc.set(n,s)),s.set(e,t)}class px extends D.O8{constructor(e){super(),this.layer=e,this.changed=new j.HN}get value(){return this.value_}set value(e){e!==this.value_&&(this.unregister(),e!==void 0&&(e.changed.add(this.changed.dispatch),this.value_=e),this.changed.dispatch())}unregister(){const e=this.value_;e!==void 0&&(e.changed.remove(this.changed.dispatch),e.dispose(),this.value_=void 0)}disposed(){this.unregister(),super.disposed()}restoreState(e){this.value=hx(this.layer,e)}reset(){this.value=void 0}toJSON(){const e=this.value_;if(e!==void 0)return e.toJSON()}}class fx extends D.O8{constructor(e){super(),this.inputEventMapBinder=e,this.bindings=new Map,this.changed=new j.HN,this.debounceDeactivate=this.registerCancellable((0,xe.A)(()=>{this.deactivate_(),this.reactivateQueuedTool()},100))}get(e){return this.bindings.get(e)}set(e,t){const{bindings:n}=this,s=n.get(e);if(s!==void 0){s.keyBinding=void 0,n.delete(e);const r=s.localBinder;r.bindings.delete(e),r.jsonToKey.delete(JSON.stringify(s.toJSON())),this.destroyTool(s),r.changed.dispatch()}if(t!==void 0){const r=t.localBinder,o=JSON.stringify(t.toJSON()),a=r.jsonToKey.get(o);if(a!==void 0){const l=r.bindings.get(a);l.keyBinding=void 0,n.delete(a),r.bindings.delete(a),r.jsonToKey.delete(o),this.destroyTool(l)}r.bindings.set(e,t),t.keyBinding=e,r.jsonToKey.set(o,e),n.set(e,t),r.changed.dispatch()}this.changed.dispatch()}activate(e){const t=this.get(e);if(t===void 0){this.deactivate_();return}this.debounceDeactivate.cancel();const n=this.activeTool_;if(t===n?.tool){t.toggle&&this.deactivate_();return}n!==void 0&&(n.tool.toggle&&!t.toggle&&(this.queuedTool=n.tool),this.deactivate_());const s=new yf(t,this.inputEventMapBinder);if(this.activeTool_=s,!t.toggle){const r=`Key${e}`;s.registerEventListener(window,"keydown",o=>{o.stopPropagation(),o.preventDefault()}),s.registerEventListener(window,"keyup",o=>{o.code===r&&this.debounceDeactivate()}),s.registerEventListener(window,"blur",()=>{this.debounceDeactivate()})}return t.activate(s),t}reactivateQueuedTool(){if(this.queuedTool){const e=new yf(this.queuedTool,this.inputEventMapBinder);this.activeTool_=e,this.queuedTool.activate(e),this.queuedTool=void 0}}destroyTool(e){this.queuedTool===e&&(this.queuedTool=void 0),this.activeTool_?.tool===e&&this.deactivate_(),e.dispose()}disposed(){this.deactivate_(),super.disposed()}deactivate_(){this.debounceDeactivate.cancel();const e=this.activeTool_;e!==void 0&&(this.activeTool_=void 0,e.dispose())}}class gc extends D.O8{constructor(e,t){super(),this.context=e,this.globalBinder=t,this.bindings=new Map,this.jsonToKey=new Map,this.changed=new j.HN}disposed(){this.clear(),super.disposed()}get(e){return this.bindings.get(e)}set(e,t){this.globalBinder.set(e,t)}setJson(e,t){const n=bf(this.context,t);n!==void 0&&this.set(e,n)}removeJsonString(e){const t=this.jsonToKey.get(e);t!==void 0&&this.set(t,void 0)}toJSON(){const{bindings:e}=this;if(e.size===0)return;const t={};for(const[n,s]of e)t[n]=s.toJSON();return t}clear(){const{globalBinder:e,bindings:t}=this;if(t.size!==0){for(const[n,s]of t)s.keyBinding=void 0,e.bindings.delete(n),e.destroyTool(s);t.clear(),this.jsonToKey.clear(),e.changed.dispatch(),this.changed.dispatch()}}reset(){this.clear()}restoreState(e){if(e!==void 0){(0,p.Rf)(e);for(const[t,n]of Object.entries(e)){if(!t.match(ux))throw new Error(`Invalid tool key: ${JSON.stringify(t)}`);const s=bf(this.context,n);if(s===void 0)return;this.set(t,s)}}}}class Cf extends D.O8{constructor(e,t){super(),this.localBinder=e,this.toolJson=t,this.element=document.createElement("div"),this.toolJsonString=JSON.stringify(this.toolJson);const{element:n}=this;n.classList.add("neuroglancer-tool-key-binding"),this.registerDisposer(e.changed.add(this.registerCancellable((0,je.t)(()=>this.updateView())))),this.updateView(),n.title="click \u2192 bind key, dbclick \u2192 unbind",n.addEventListener("dblclick",()=>{this.localBinder.removeJsonString(this.toolJsonString)}),xf(this,n,s=>this.localBinder.setJson(s,this.toolJson))}updateView(){const{localBinder:e}=this,t=e.jsonToKey.get(this.toolJsonString);this.element.textContent=t??" "}}function xf(i,e,t){let n;e.addEventListener("mousedown",s=>{if(s.button!==0||n!==void 0)return;s.preventDefault(),s.stopPropagation(),n=new D.O8,i.registerDisposer(n),n.registerDisposer(new Se(!1)).setText("Press A-Z to bind key"),n.registerEventListener(window,"keydown",o=>{const{code:a}=o,l=a.match(/^Key([A-Z])$/);if(l===null)return;o.stopPropagation(),o.preventDefault();const c=l[1];t(c)},{capture:!0}),n.registerEventListener(window,"mouseup",o=>{o.button!==0||n===void 0||(o.preventDefault(),o.stopPropagation(),i.unregisterDisposer(n),n.dispose(),n=void 0)})}),e.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation()})}function ys(i,e,t){const n=document.createElement("div");n.classList.add("neuroglancer-tool-button"),n.appendChild(i.registerDisposer(new Cf(e,t.toolJson)).element);const s=document.createElement("div");s.classList.add("neuroglancer-tool-button-label");const r=t.label;return r!==void 0&&(s.textContent=r),t.title&&(s.title=t.title),n.appendChild(s),n}function Ef(i){const e=i.registerDisposer(new Se(!1));e.element.classList.add("neuroglancer-tool-status");const t=document.createElement("div");t.classList.add("neuroglancer-tool-status-content"),e.element.appendChild(t);const{inputEventMapBinder:n}=i;return i.inputEventMapBinder=(s,r)=>{const o=document.createElement("div");o.textContent=s.describe(),o.classList.add("neuroglancer-tool-status-bindings"),e.element.appendChild(o),n(s,r)},{message:e,content:t}}function Ss(i){const{message:e,content:t}=Ef(i),n=document.createElement("div");n.classList.add("neuroglancer-tool-status-header");const s=document.createElement("div");s.classList.add("neuroglancer-tool-status-header-container"),s.appendChild(n),t.appendChild(s);const r=document.createElement("div");return r.classList.add("neuroglancer-tool-status-body"),t.appendChild(r),{message:e,body:r,header:n}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ai(i,e="text/plain"){let t=!1;const n=(0,D.K6)(document,"copy",s=>{const{clipboardData:r}=s;r!==null&&(r.setData(e,i),t=!0),s.stopPropagation(),s.preventDefault()},!0);try{document.execCommand("copy")}finally{n()}return t}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Lo=new A.B0(0);window.addEventListener("keydown",i=>{Lo.value=cc(i)}),window.addEventListener("keyup",i=>{Lo.value=cc(i)});const gx=new Set(["f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","escape","pause"]),mx=new Set(["color","date","datetime","datetime-local","email","month","number","password","search","tel","text","time","url","week"]);class mn extends D.O8{constructor(e,t){super(),this.target=e,this.eventMap=t,this.modifierShortcutsAreGlobal=!0,this.allShortcutsAreGlobal=!1,this.allowSpaceKeyOnButtons=!1,this.shouldIgnore=void 0,this.registerEventListener(e,"keydown",this.handleKeyDown.bind(this),!1)}shouldIgnoreEvent(e,t){if(this.shouldIgnore?.(t))return!0;const n=t.target,{tagName:s}=n;if(n===this.target)return!1;const r=s==="TEXTAREA"||s==="INPUT"||s==="BUTTON"||s==="SELECT",o=!r&&(n.isContentEditable||n.ownerDocument&&n.ownerDocument.designMode==="on");return!r&&!o||this.allShortcutsAreGlobal||gx.has(e)?!1:o||this.modifierShortcutsAreGlobal&&(t.altKey||t.ctrlKey||t.metaKey)?!0:s==="INPUT"&&mx.has(n.type)?e!=="enter":s==="INPUT"||s==="BUTTON"?this.allowSpaceKeyOnButtons?!1:e==="space":!0}handleKeyDown(e){const t=vx(e);this.shouldIgnoreEvent(t,e)||nf(t,e,e,this.eventMap)}}function vx(i){return i.code.toLowerCase()}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class en extends D.O8{constructor(e,t){super(),this.element=_e({...t,onClick:()=>{e.value=!e.value}}),this.element.classList.add("neuroglancer-checkbox-icon"),this.element.classList.add(t.backgroundScheme==="dark"?"dark-background":"light-background");const n=()=>{const s=e.value;this.element.dataset.checked=s?"true":"false",this.element.title=(s?t.disableTitle:t.enableTitle)||""};this.registerDisposer(e.changed.add(n)),n()}}var yx=G(3112);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function zn(i={}){return _e({svg:yx,...i})}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Sx extends D.O8{constructor(e){super(),this.redraw=e}}class zt extends D.O8{constructor(e,t,n=new ht(ht.VISIBLE)){super(),this.model=e,this.render=t,this.visibility=n,this.element=document.createElement("div"),this.generation=-1,this.currentViewDisposer=void 0,this.debouncedUpdateView=this.registerCancellable((0,je.t)(()=>this.updateView())),this.debouncedForceUpdateView=()=>{this.generation=-1,this.debouncedUpdateView()},this.element.style.display="contents",this.registerDisposer(e.changed.add(this.debouncedUpdateView)),this.registerDisposer(n.changed.add(()=>{this.visible&&this.debouncedUpdateView()})),this.updateView()}get visible(){return this.visibility.visible}updateView(){if(!this.visible)return;const{model:e}=this,t=e.changed.count;if(t===this.generation)return;this.disposeCurrentView();const n=this.currentViewDisposer=new Sx(this.debouncedForceUpdateView);this.render(e.value,this.element,n),this.generation=t}disposeCurrentView(){const{currentViewDisposer:e}=this;e!==void 0&&e.dispose(),Ae(this.element)}disposed(){this.disposeCurrentView(),super.disposed()}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Po extends D.O8{constructor(e){super(),this.model=e,this.element=document.createElement("select"),this.valueIndexMap=new Map;const{element:t,valueIndexMap:n}=this;let s=0;for(const r of Object.keys(e.enumType))if(Number.isNaN(Number(r))){const o=document.createElement("option");o.textContent=o.value=r.toLowerCase(),t.appendChild(o),n.set(e.enumType[r],s),++s}this.registerDisposer(e.changed.add(()=>this.updateView())),this.registerEventListener(t,"change",()=>this.updateModel()),this.registerEventListener(t,"wheel",r=>{r.preventDefault(),r.stopPropagation(),this.adjustViaWheel(r)}),this.updateView()}adjustViaWheel(e){const{element:t}=this,{deltaY:n}=e;n>0?(t.selectedIndex=(t.options.length+t.selectedIndex-1)%t.options.length,this.updateModel()):n<0&&(t.selectedIndex=(t.options.length+t.selectedIndex+1)%t.options.length,this.updateModel())}updateView(){const{element:e}=this;e.selectedIndex=this.valueIndexMap.get(this.model.value)}updateModel(){this.model.restoreState(this.element.value)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class mc extends D.O8{constructor(e,t={}){super(),this.model=e,this.element=document.createElement("label"),this.inputElement=document.createElement("input");let{validator:n,label:s}=t;const{element:r,inputElement:o}=this;n===void 0&&(e instanceof A.DN?n=e.validator:n=a=>a),this.validator=n,s!==void 0&&(r.textContent=s),r.appendChild(o),r.className="neuroglancer-number-input",o.type="text",this.registerDisposer(this.model.changed.add(()=>this.updateView())),this.registerEventListener(o,"change",()=>this.updateModel()),this.updateView()}updateView(){this.inputElement.value=""+this.model.value}updateModel(){let e=parseFloat(this.inputElement.value.trim());if(Number.isNaN(e)){this.updateView();return}try{e=this.validator(e),this.model.value=e}catch{this.updateView()}}disposed(){lt(this.element),super.disposed()}}/**
 * @license
 * Copyright 2017-2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Tf(i,e,t,n){return Math.floor((i-e)*(n-1)/(t-e))}function bx(i,e,t){const{boundingBoxes:n,bounds:s}=i;let[r,o]=kh(s,e);if(r=Math.floor(r),o=Math.floor(o-1),!Number.isFinite(r)||!Number.isFinite(o))return;const a=[],l=d=>Tf(d,r,o,t),{rank:c}=i;for(const d of n){const u=Ph(d,e,c);u!==void 0&&(u.lower=Math.max(0,l(u.lower)),u.upper=Math.min(t-1,l(Math.ceil(u.upper-1))),a.push(u))}return a.sort((d,u)=>{const h=d.lower-u.lower;return h!==0?h:u.upper-u.upper}),(0,z.U8)(a,(d,u)=>{if(u===0)return!0;const h=a[u-1];return h.lower!==d.lower||h.upper!==d.upper}),{lowerBound:r,upperBound:o,normalizedBounds:a}}class Df extends D.O8{constructor(e,t,n="column"){super(),this.position=e,this.dimensionId=t,this.orientation=n,this.element=document.createElement("div"),this.visible=!0,this.dragging=new A.B0(!1),this.tickWidth=this.orientation==="column"?10:5,this.barWidth=this.orientation==="column"?15:10,this.barRightMargin=this.orientation==="column"?10:2,this.canvasWidth=this.tickWidth+this.barWidth+this.barRightMargin;const s=this.element;s.classList.add("neuroglancer-position-dimension-plot"),s.dataset.orientation=n;const r=document.createElement("canvas"),o=r.getContext("2d"),a=document.createElement("div"),l=document.createElement("div");l.appendChild(a);const c=document.createTextNode("");a.appendChild(c);const d=document.createElement("div"),u=document.createElement("div");l.classList.add("neuroglancer-position-dimension-plot-lowerbound"),d.classList.add("neuroglancer-position-dimension-plot-upperbound"),u.classList.add("neuroglancer-position-dimension-plot-hoverposition"),s.appendChild(l),s.appendChild(d),s.appendChild(u),s.appendChild(r);let h,f,m;const g=()=>{const x=this.position.coordinateSpace.value,b=x.ids.indexOf(this.dimensionId);if(b===-1)return;let E;n==="column"?(E=100,r.width=this.canvasWidth,r.height=E,d.style.marginTop=`${E-1}px`):(E=r.clientWidth,r.width=E,r.height=this.canvasWidth);const C=bx(x,b,E);if(C===void 0||x.bounds.lowerBounds[b]+1===x.bounds.upperBounds[b]){this.element.style.display="none",this.visible=!1;return}this.visible=!0;const{lowerBound:k,upperBound:T}=C;h=k,f=T,c.textContent=k.toString(),d.textContent=T.toString();let L,_,R;n!=="column"&&(_=a.clientWidth,R=d.clientWidth,L=Math.max(_,R)/2,r.style.marginLeft=`${L}px`,r.style.marginRight=`${L}px`,d.style.position="relative",d.style.left=`${E+L-R/2}px`,a.style.marginLeft=`${L-_/2}px`),this.drawDimensionBounds(r,o,C);const P=this.position.value[b],V=(ee,ce)=>{if(ee!==void 0&&ee>=k&&Math.floor(ee)<=T){o.fillStyle=ce;const fe=Tf(ee,k,T,E);return n==="column"?o.fillRect(0,fe,this.canvasWidth,1):o.fillRect(fe,0,1,this.canvasWidth),fe}},$=V(P,"#f66"),Q=this.dragging.value;let K=Q?$:V(m,"#66f");if(K!==void 0){u.textContent=(Q?Math.floor(P):m).toString();const ee=n==="column"?a.clientHeight:a.clientWidth,ce=n==="column"?d.clientHeight:d.clientWidth;let fe,le,ve;if(n!=="column"){fe=u.clientWidth,K+=L,K-=fe/2,K=Math.max(0,K);const Ie=E+L-ce/2-fe;le=K>L+ee/2,ve=K<Ie}else le=K>ee,ve=K<E-ce;a.style.visibility=le?"":"hidden",d.style.visibility=ve?"":"hidden",u.style.display="",u.style.visibility="visible",n==="column"?u.style.marginTop=`${K}px`:u.style.marginLeft=`${K}px`}else a.style.visibility="",u.style.display="none",d.style.visibility=""},v=this.registerCancellable((0,je.t)(g));this.registerDisposer(this.position.changed.add(v));const y=x=>{if(h===void 0||f===void 0)return;const b=r.getBoundingClientRect();let E;return n==="column"?E=(x.clientY-b.top)/b.height:E=(x.clientX-b.left)/b.width,E=Math.max(0,E),E=Math.min(1,E),Math.round(E*(f-h))+h},S=x=>{const b=this.position.coordinateSpace.value,E=b.ids.indexOf(this.dimensionId);if(E===-1)return;let C=y(x);if(C===void 0)return;const{position:k}=this,T=k.value;b.bounds.voxelCenterAtIntegerCoordinates[E]||(C+=.5),T[E]=C,k.value=T};r.addEventListener("pointermove",x=>{m=y(x),v()}),r.addEventListener("pointerleave",()=>{m=void 0,v()}),r.addEventListener("pointerdown",x=>{x.preventDefault(),x.stopPropagation(),!(x.ctrlKey||x.altKey||x.metaKey)&&($t(x,b=>{this.wasDisposed||(m=void 0,S(b),v(),this.dragging.value=!0)},()=>{this.dragging.value=!1,v()}),S(x))}),g(),n==="row"&&(r.style.maxWidth="100%",r.style.justifySelf="stretch",new ResizeObserver(g).observe(r))}drawDimensionBounds(e,t,n){const{orientation:s}=this;t.clearRect(0,0,e.width,e.height);const{normalizedBounds:r}=n,o=s==="column"?l=>{t.fillRect(0,l,this.tickWidth,1)}:l=>{t.fillRect(l,0,1,this.tickWidth)};t.fillStyle="#fff";for(const{lower:l,upper:c}of r)o(l),o(c);const a=r.length;t.fillStyle="#ccc";for(let l=0;l<a;++l){const{lower:c,upper:d}=r[l],u=Math.floor(l*this.barWidth/a),h=Math.max(1,this.barWidth/a);s==="column"?t.fillRect(u+this.tickWidth,c,h,d+1-c):t.fillRect(c,u+this.tickWidth,d+1-c,h)}}}/**
 * @license
 * Copyright 2017-2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Ao="neuroglancer-position",If=Pe.fromObject({arrowup:{action:"adjust-up"},arrowdown:{action:"adjust-down"},arrowleft:{action:"maybe-tab-backward",preventDefault:!1},arrowright:{action:"maybe-tab-forward",preventDefault:!1},tab:{action:"tab-forward"},"shift+tab":{action:"tab-backward"},wheel:{action:"adjust-via-wheel"},"alt+wheel":{action:"adjust-velocity-via-wheel"},backspace:{action:"delete-backward",preventDefault:!1},enter:{action:"commit"},escape:{action:"cancel"}}),wx=[i=>i.nameElement,i=>i.coordinate,i=>i.scaleElement];function Mo(i,e){const t=i.coordinateArrays[e];return t===void 0?t:i.units[e]!==""||i.scales[e]!==1?null:t}class Cx{constructor(e,t,n,s){this.coordinateSpace=e,this.id=t,this.container=document.createElement("div"),this.nameContainer=document.createElement("span"),this.nameElement=document.createElement("input"),this.scaleContainer=document.createElement("span"),this.scaleElement=document.createElement("input"),this.coordinate=document.createElement("input"),this.coordinateLabel=document.createElement("span"),this.playButton=document.createElement("div"),this.pauseButton=document.createElement("div"),this.coordinateLabelWidth=0,this.maxPositionWidth=0,this.maxPositionWidthSeen=0,this.dropdownOwner=void 0,this.modified=!1,this.draggingPosition=!1,this.hasFocus=!1;const{container:r,scaleElement:o,scaleContainer:a,coordinate:l,nameElement:c,nameContainer:d,coordinateLabel:u,playButton:h,pauseButton:f}=this;r.title="",r.classList.add("neuroglancer-position-dimension");const{allowFocus:m,showPlayback:g}=s;m&&(r.draggable=!0,r.tabIndex=-1),r.appendChild(d),r.appendChild(o),d.appendChild(c),d.title="Drag to reorder, double click to rename.  Names ending in ' or ^ indicate dimensions local to the layer; names ending in ^ indicate channel dimensions (image layers only).",a.appendChild(o),c.classList.add("neuroglancer-position-dimension-name"),c.disabled=!0,c.spellcheck=!1,c.autocomplete="off",c.required=!0,c.placeholder=" ",a.classList.add("neuroglancer-position-dimension-scale-container"),o.classList.add("neuroglancer-position-dimension-scale"),o.disabled=!0,o.spellcheck=!1,o.autocomplete="off",r.appendChild(a),g&&(h.classList.add("neuroglancer-icon"),f.classList.add("neuroglancer-icon"),h.innerHTML=mf,f.innerHTML=gf,r.appendChild(h),r.appendChild(f)),r.appendChild(l),l.type="text",l.classList.add("neuroglancer-position-dimension-coordinate"),l.spellcheck=!1,l.autocomplete="off",l.pattern=String.raw`(-?\d+(?:\.(?:\d+)?)?)`;const v=Mo(e,n);if(v!=null){let y=0;for(const S of v.labels)y=Math.max(y,S.length);this.coordinateLabelWidth=y,u.style.width=`${y+2}ch`,r.appendChild(u)}l.required=!0,l.placeholder=" ",u.classList.add("neuroglancer-position-dimension-coordinate-label"),m&&(d.addEventListener("dblclick",()=>{c.disabled=!1,c.focus(),c.select()}),a.addEventListener("dblclick",()=>{o.disabled=!1,o.focus(),o.select()}),l.addEventListener("focus",()=>{l.select()}),r.addEventListener("click",y=>{(!(y.target instanceof HTMLInputElement)||y.target.disabled)&&l.focus()}))}}function Rf(i,e){const t=e.length;t>i.maxPositionWidthSeen&&(i.maxPositionWidthSeen=t),Ft(i.coordinate,Math.max(Math.min(i.maxPositionWidth,i.maxPositionWidthSeen),t))}function kf(i){const{value:e}=i;Ft(i),i.parentElement.dataset.isEmpty=e===""?"true":"false"}class bs extends D.O8{constructor(e,t,{copyButton:n=!0,velocity:s=void 0,singleDimensionId:r=void 0,getToolBinder:o=void 0,allowFocus:a=!0,showPlayback:l=!0}={}){super(),this.position=e,this.combiner=t,this.element=document.createElement("div"),this.dimensionContainer=document.createElement("div"),this.coordinateSpace=void 0,this.dimensionWidgets=new Map,this.dimensionWidgetList=[],this.dragSource=void 0;const{element:c,dimensionContainer:d}=this;if(this.velocity=s,this.singleDimensionId=r,this.getToolBinder=o,this.allowFocus=a,this.showPlayback=l,this.registerDisposer(e.coordinateSpace.changed.add(this.registerCancellable((0,je.t)(()=>this.updateDimensions())))),c.className="neuroglancer-position-widget",d.style.display="contents",c.appendChild(d),n){const m=zn({title:"Copy position to clipboard",onClick:()=>{const g=ai(this.getPositionText());Se.showTemporaryMessage(g?"Position copied to clipboard":"Failed to copy position to clipboard")}});m.addEventListener("dragstart",g=>{g.dataTransfer.setData(Ao,JSON.stringify({position:e.toJSON(),dimensions:e.coordinateSpace.value.names})),g.dataTransfer.setData("text",this.getPositionText()),g.stopPropagation()}),m.draggable=!0,c.appendChild(m)}const u=this.registerCancellable((0,je.t)(()=>this.updateView()));this.registerDisposer(e.changed.add(u)),s!==void 0&&this.registerDisposer(s.changed.add(u));const h=m=>{const g=m.target;return!!(g instanceof Element&&g.matches(".neuroglancer-position-dimension-playback *"))};if(a){const m=this.registerDisposer(new mn(c,If));m.allShortcutsAreGlobal=!0,m.shouldIgnore=h}const f=this.registerDisposer(new fn(c,If));f.shouldIgnore=h,this.registerDisposer(X(c,"cancel",m=>{this.coordinateSpace=void 0,this.updateView(),this.closeDropdown();const{target:g}=m;g instanceof HTMLElement&&g.blur()})),this.updateView()}getDimensionIndex(e){return this.position.coordinateSpace.value.ids.indexOf(e)}openRegularDropdown(e,t){t.classList.add("neuroglancer-position-dimension-dropdown");const n=e.dropdownOwner,s=this.getToolBinder?.();if(s!==void 0){const a=this.getDimensionIndex(e.id),l=ys(n,s,{toolJson:{type:yr,dimension:e.coordinateSpace.names[a]}});t.appendChild(l)}const r=n.registerDisposer(new Df(this.position,e.id));t.appendChild(r.element);const o=this.velocity?.dimensionVelocity(n,e.id);if(o!==void 0){const a=document.createElement("div");a.classList.add("neuroglancer-position-dimension-playback");const l=document.createElement("div");l.classList.add("neuroglancer-position-dimension-playback-header"),a.appendChild(l),l.appendChild(n.registerDisposer(new en(this.velocity.playbackEnabled(e.id),{svg:vf,enableTitle:"Enable playback/velocity",disableTitle:"Disable playback/velocity",backgroundScheme:"dark"})).element),l.appendChild(document.createTextNode("Playback")),t.appendChild(a);const c=n.registerDisposer((0,A.Uq)(d=>d!==void 0,[o]));a.appendChild(n.registerDisposer(new zt(c,(d,u,h)=>{if(!d)return;const f=new A.B0(0);f.changed.add(()=>{const b=f.value,E=o.value;E!==void 0&&E.velocity!==b&&(o.value={...E,velocity:b})});const m=_e({text:"\xB1",title:"Negate velocity",onClick:()=>{f.value=-f.value}}),g=h.registerDisposer(new mc(f));g.element.insertBefore(m,g.element.firstChild),g.element.title="Velocity in coordinates per second";const v=document.createElement("span");v.textContent="/s",g.element.appendChild(v),u.appendChild(g.element);const y=new Mi.F(Gn,Gn.STOP),S=()=>{y.value=o.value?.atBoundary??Gn.STOP,f.value=o.value?.velocity??0};S(),h.registerDisposer(o.changed.add(S)),y.changed.add(()=>{const b=y.value,E=o.value;E!==void 0&&E.atBoundary!==b&&(o.value={...E,atBoundary:b})});const x=new Po(y).element;u.appendChild(x),x.title="Behavior when lower/upper bound is reached"})).element)}r.dragging.changed.add(()=>{(e.draggingPosition=r.dragging.value)===!1&&this.updateDropdownVisibility(e)})}openCoordinateArrayDropdown(e,t,n){t.classList.add("neuroglancer-position-dimension-coordinate-dropdown");const{coordinates:s,labels:r}=n,o=[],a=s.length;t.style.setProperty("--neuroglancer-coordinate-label-width",`${e.coordinateLabelWidth}ch`);for(let l=0;l<a;++l){const c=document.createElement("div");c.classList.add("neuroglancer-dimension-dropdown-coordinate-entry");const d=document.createElement("div");d.classList.add("neuroglancer-dimension-dropdown-coordinate");const u=document.createElement("div");u.classList.add("neuroglancer-dimension-dropdown-coordinate-label"),u.textContent=r[l],d.textContent=s[l].toString(),c.appendChild(d),c.appendChild(u),c.addEventListener("click",()=>{const h=this.getDimensionIndex(e.id);if(h===-1)return;const{position:f}=this,m=f.value;m[h]=s[l]+.5,e.modified=!1,f.value=m}),t.appendChild(c),o.push({entryElement:c,coordinateElement:d,labelElement:u})}}openDropdown(e){if(e.dropdownOwner!==void 0)return;const t=this.getDimensionIndex(e.id);if(t===-1)return;this.closeDropdown();const n=e.dropdownOwner=new D.O8,s=document.createElement("div");s.draggable=!0,s.addEventListener("dragstart",o=>{o.stopPropagation(),o.preventDefault()}),s.addEventListener("pointerenter",()=>{e.hasFocus=!0}),s.tabIndex=-1,e.container.appendChild(s);const r=Mo(e.coordinateSpace,t);r==null?this.openRegularDropdown(e,s):this.openCoordinateArrayDropdown(e,s,r),this.widgetWithOpenDropdown=e,n.registerDisposer(()=>{lt(s),e.dropdownOwner=void 0,e.container.dataset.dropdownVisible=void 0,this.widgetWithOpenDropdown=void 0}),n.registerEventListener(document,"pointerdown",o=>{const{target:a}=o;a instanceof Node&&e.container.contains(a)||this.closeDropdown(e)},{capture:!0})}closeDropdown(e=this.widgetWithOpenDropdown){if(e===void 0)return;const{dropdownOwner:t}=e;t!==void 0&&t.dispose()}pasteString(e,t){for(;;){e.coordinate.focus();const n=t.match(/^\s*(-?\d+(?:\.(?:\d+)?)?)((?:\s+(?![\s,]))|(?:\s*,\s*))?/);if(n===null)break;if(n[1]!==void 0&&document.execCommand("insertText",void 0,n[1]),n[2]!==void 0){const{dimensionWidgetList:s}=this,r=s.indexOf(e);if(r===-1||r+1===s.length)break;const o=t.substring(n[0].length);e=s[r+1],t=o;continue}break}}reorderDimensionTo(e,t){if(e===t)return;const{coordinateSpace:n}=this.position;n.value=Gh(n.value,e,t)}updateDropdownVisibility(e){e.hasFocus||e.draggingPosition?this.openDropdown(e):this.closeDropdown(e)}newDimension(e,t,n){const s=new Cx(e,t,n,{allowFocus:this.allowFocus,showPlayback:this.showPlayback});this.singleDimensionId===void 0&&(s.container.addEventListener("dragstart",r=>{this.dragSource=s,r.stopPropagation(),r.dataTransfer.setData("neuroglancer-dimension","")}),s.container.addEventListener("dragenter",r=>{const{dragSource:o}=this;if(o===void 0||o===s)return;const{dimensionWidgetList:a}=this,l=a.indexOf(o),c=a.indexOf(s);l===-1||c===-1||(r.preventDefault(),this.reorderDimensionTo(c,l))}),s.container.addEventListener("dragend",r=>{this.dragSource===s&&(this.dragSource=void 0)})),this.allowFocus?(s.container.addEventListener("focusin",()=>{s.hasFocus=!0,this.updateDropdownVisibility(s)}),s.container.addEventListener("focusout",r=>{const{relatedTarget:o}=r;o instanceof Node&&s.container.contains(o)||(s.hasFocus=!1,this.updateDropdownVisibility(s))}),s.coordinate.addEventListener("paste",r=>{const o=s.coordinate,a=o.value,{clipboardData:l}=r;if(l===null)return;let c=l.getData("text"),{selectionEnd:d,selectionStart:u}=o;if(u!==0||d!==a.length){u==null&&(u=0),d==null&&(d=0);const h=c.match(/[^\-0-9.]/);h!==null&&(c=c.substring(0,h.index)),c.length>0&&document.execCommand("insertText",void 0,c)}else this.pasteString(s,c);r.preventDefault(),r.stopPropagation()}),s.coordinate.addEventListener("input",()=>{s.modified=!0;const r=s.coordinate,o=r.value;let{selectionDirection:a,selectionEnd:l,selectionStart:c}=r;c===null&&(c=0),l===null&&(l=c);let d="";const u=/[^\-0-9.]/g;d+=o.substring(0,c).replace(u,"");const h=d.length;d+=o.substring(c,l).replace(u,"");const f=d.length;d+=o.substring(l).replace(u,""),r.value=d,r.selectionStart=h,r.selectionEnd=f,r.selectionDirection=a,Rf(s,d),l===c&&l===o.length&&o.match(/^(-?\d+(?:\.(?:\d+)?)?)((?:\s+(?![\s,]))|(?:\s*,\s*))$/)&&this.selectAdjacentCoordinate(s,1)}),s.nameElement.addEventListener("input",()=>{const{nameElement:r}=s;Ft(r),this.updateNameValidity()}),s.scaleElement.addEventListener("input",()=>{const{scaleElement:r}=s;kf(r),this.updateScaleValidity(s)}),s.coordinate.addEventListener("blur",r=>{const{relatedTarget:o}=r;this.dimensionWidgetList.some(a=>a.coordinate===o)||s.modified&&this.updatePosition()}),s.nameElement.addEventListener("blur",r=>{s.nameElement.disabled=!0;const{relatedTarget:o}=r;this.dimensionWidgetList.some(a=>a.nameElement===o)||this.updateNames()||this.forceUpdateDimensions()}),s.scaleElement.addEventListener("blur",r=>{s.scaleElement.disabled=!0;const{relatedTarget:o}=r;this.dimensionWidgetList.some(a=>a.scaleElement===o)||this.updateScales()||this.forceUpdateDimensions()})):s.coordinate.disabled=!0,X(s.container,"adjust-via-wheel",r=>{const o=r.detail,{deltaY:a}=o;a!==0&&this.adjustDimensionPosition(s.id,Math.sign(a))}),X(s.container,"adjust-velocity-via-wheel",r=>{const o=r.detail;this.adjustDimensionVelocity(s,gs(o))}),X(s.container,"adjust-up",()=>{this.adjustDimensionPosition(s.id,-1)}),X(s.container,"adjust-down",()=>{this.adjustDimensionPosition(s.id,1)});for(const r of wx){const o=r(s);X(o,"maybe-tab-forward",a=>{this.handleLeftRightMovement(a,s,1,r)}),X(o,"maybe-tab-backward",a=>{this.handleLeftRightMovement(a,s,-1,r)}),X(o,"tab-forward",()=>{this.selectAdjacentField(s,1,r)}),X(o,"tab-backward",()=>{this.selectAdjacentField(s,-1,r)})}if(X(s.coordinate,"commit",()=>{this.updatePosition()}),X(s.nameElement,"commit",()=>{this.updateNames()}),X(s.scaleElement,"commit",()=>{this.updateScales()}),X(s.coordinate,"delete-backward",r=>{r.stopPropagation();const{coordinate:o}=s;o.selectionStart===o.selectionEnd&&o.selectionStart===0&&(r.preventDefault(),this.selectAdjacentCoordinate(s,-1))}),this.showPlayback){const r=o=>{this.velocity?.togglePlayback(s.id,o)};s.playButton.addEventListener("click",()=>r(!1)),s.pauseButton.addEventListener("click",()=>r(!0))}return s}forceUpdateDimensions(){let{position:{coordinateSpace:{value:e}}}=this;e.valid||(e=Bn),this.coordinateSpace=e;const{dimensionWidgets:t,dimensionWidgetList:n}=this;n.length=0;const{names:s,ids:r,scales:o,units:a,bounds:{lowerBounds:l,upperBounds:c}}=e,d=(h,f)=>{const m=l[f],g=c[f],v=Math.max(Number.isFinite(m)?Math.floor(m).toString().length:0,Number.isFinite(g)?Math.ceil(g).toString().length:0);let y=t.get(h);y===void 0?(y=this.newDimension(e,h,f),t.set(h,y),y.maxPositionWidthSeen=v):y.coordinateSpace=e,y.maxPositionWidth=v;const S=s[f];y.nameElement.value=S,y.nameElement.dataset.isValid=void 0,Ft(y.nameElement);const x=Mo(e,f);x===void 0?y.container.dataset.coordinateArray="none":x===null?y.container.dataset.coordinateArray="invalid":y.container.dataset.coordinateArray="valid",y.scaleContainer.title="Drag to reorder, double click to change scale",x===null&&(y.scaleContainer.title+=".  Coordinate array disabled.  To use the coordinate array, remove the unit/scale.");const{scale:b,prefix:E,unit:C}=Eh(o[f],a[f]),k=`${b}${E}${C}`;return y.scaleElement.value=k,y.scaleElement.dataset.isValid=void 0,kf(y.scaleElement),n.push(y),y.container},{singleDimensionId:u}=this;if(u!==void 0){const h=this.getDimensionIndex(u);h===-1?Zt(this.dimensionContainer,[]):Zt(this.dimensionContainer,[d(u,h)])}else Zt(this.dimensionContainer,r.map(d));for(const[h,f]of t)f.coordinateSpace!==e&&(this.closeDropdown(f),t.delete(h))}updateDimensions(){const{position:{coordinateSpace:{value:e}}}=this;e!==this.coordinateSpace&&this.forceUpdateDimensions()}selectAdjacentField(e,t,n){const{dimensionWidgetList:s}=this;let r=s.indexOf(e);if(r!==-1)for(;;){if(r+=t,r<0||r>=s.length)return!1;const o=s[r],a=n(o);if(a.style.display!=="none")return a.disabled=!1,a.focus(),a.selectionStart=0,a.selectionEnd=a.value.length,a.selectionDirection=t===1?"forward":"backward",!0}}selectAdjacentCoordinate(e,t){return this.selectAdjacentField(e,t,n=>n.coordinate)}handleLeftRightMovement(e,t,n,s){e.stopPropagation();const r=s(t);r.selectionStart!==r.selectionEnd||r.selectionStart!==(n===1?r.value.length:0)||this.selectAdjacentField(t,n,s)&&e.preventDefault()}updateNameValidity(){const{dimensionWidgetList:e}=this,t=e.map(r=>r.nameElement.value),n=t.length,s=this.combiner.getRenameValidity(t);for(let r=0;r<n;++r)e[r].nameElement.dataset.isValid=s[r]===!1?"false":"true"}updateScaleValidity(e){const t=Zs(e.scaleElement.value)!==void 0;e.scaleElement.dataset.isValid=t.toString()}adjustDimensionPosition(e,t){const n=this.getDimensionIndex(e);if(n===-1)return;this.updatePosition();const{position:s}=this;if(!s.valid)return;const r=s.coordinateSpace.value,{bounds:o}=r,a=Float32Array.from(s.value);a[n]=Nl(o,n,a[n]+t),this.position.value=a,this.updateView()}adjustDimensionVelocity(e,t){const{velocity:n}=this;n!==void 0&&n.multiplyVelocity(e.id,t)}updatePosition(){if(!this.allowFocus)return;const{dimensionWidgetList:e}=this,{position:t}=this,{value:n}=t,s=t.coordinateSpace.value;if(n===void 0)return;const r=e.length;let o=!1;for(let a=0;a<r;++a){const l=e[a];if(!l.modified)continue;l.modified=!1,o=!0;const c=l.coordinate.value;let d=Number(c);Number.isFinite(d)&&(Number.isInteger(d)&&!c.includes(".")&&s!==void 0&&!s.bounds.voxelCenterAtIntegerCoordinates[a]&&(d+=.5),n[a]=d)}o&&(t.value=n)}updateNames(){if(!this.allowFocus)return;const{dimensionWidgetList:e}=this,{position:{coordinateSpace:t}}=this,n=t.value,s=e.map(l=>l.nameElement.value);if(this.combiner.getRenameValidity(s).includes(!1))return!1;const r=n.names;if((0,z.r1)(r,s))return!1;const o=n.timestamps.map((l,c)=>r[c]===s[c]?l:Date.now()),a={...n,names:s,timestamps:o};return t.value=a,!0}updateScales(){if(!this.allowFocus)return;const{dimensionWidgetList:e}=this,{position:{coordinateSpace:t}}=this,n=t.value,s=e.map(u=>Zs(u.scaleElement.value));if(s.includes(void 0))return!1;const r=Float64Array.from(s,u=>u.scale),o=Array.from(s,u=>u.unit),{scales:a,units:l}=n;if((0,z.r1)(a,r)&&(0,z.r1)(l,o))return!1;const c=n.timestamps.map((u,h)=>r[h]===a[h]&&o[h]===l[h]?u:Date.now()),d=ke({valid:n.valid,rank:n.rank,scales:r,units:o,timestamps:c,ids:n.ids,names:n.names,boundingBoxes:n.boundingBoxes,coordinateArrays:n.coordinateArrays});return t.value=d,!0}getPositionText(){const{position:e}=this;return e.valid?e.value.map(t=>Math.floor(t)).join(", "):""}updateView(){this.updateDimensions();const{position:{value:e},dimensionWidgetList:t}=this,n=t.length;if(e===void 0)return;const s=this.coordinateSpace,{velocity:r}=this;for(let o=0;o<n;++o){const a=t[o],l=a.coordinate,c=Math.floor(e[o]),d=c.toString();Rf(a,d),l.value=d;const u=Mo(s,o);let h="";if(u!=null){const{coordinates:m}=u,g=(0,z.El)(m,c,(v,y)=>v-y);g!==m.length&&(h=u.labels[g])}const f=a.coordinateLabel;if(f.textContent=h,this.showPlayback){const m=r?.value?.[o];if(m!==void 0){const g=m.paused;a.playButton.style.display=g?"":"none",a.pauseButton.style.display=g?"none":""}else a.playButton.style.display="none",a.pauseButton.style.display="none"}}}disposed(){this.closeDropdown(),lt(this.element),super.disposed()}}class xx extends D.O8{constructor(e,t,n){super(),this.element=e,this.mouseState=t,this.coordinateSpace=n,this.tempPosition=w.eR.create(),e.className="neuroglancer-mouse-position-widget";const s=this.registerCancellable((0,je.t)(()=>this.updateView()));this.registerDisposer(t.changed.add(s)),this.registerDisposer(n.changed.add(s))}updateView(){let e="";const{mouseState:t,coordinateSpace:{value:n}}=this;if(t.active&&n!==void 0){const s=t.position,{rank:r,names:o}=n;for(let a=0;a<r;++a)a!==0&&(e+="  "),e+=`${o[a]} ${Math.floor(s[a])}`}this.element.textContent=e}disposed(){lt(this.element),super.disposed()}}const yr="dimension",Ex=Pe.fromObject({"at:shift?+wheel":{action:"adjust-position-via-wheel"},"at:shift?+alt+wheel":{action:"adjust-velocity-via-wheel"},"shift?+alt?+space":{action:"toggle-playback"},"at:shift?+alt?+mousedown0":{action:"toggle-playback"}});class Tx extends ko{constructor(e,t){super(e.toolBinder),this.viewer=e,this.dimensionId=t;const n=this.coordinateSpace.value,s=this.dimensionIndex=n.ids.indexOf(t);this.dimensionName=n.names[s],this.registerDisposer(this.coordinateSpace.changed.add(()=>{const r=this.coordinateSpace.value,o=this.dimensionIndex=this.coordinateSpace.value.ids.indexOf(t);if(o===-1){this.unbind();return}const a=r.names[o];this.dimensionName!==a&&(this.dimensionName=a,this.changed.dispatch())}))}get position(){return this.viewer.position}get velocity(){return this.viewer.velocity}get coordinateSpace(){return this.viewer.coordinateSpaceCombiner.combined}activate(e){const{viewer:t}=this,{content:n}=Ef(e);n.classList.add("neuroglancer-position-tool"),e.bindInputEventMap(Ex);const s=new bs(t.position,t.coordinateSpaceCombiner,{velocity:t.velocity,singleDimensionId:this.dimensionId,copyButton:!1,allowFocus:!1,showPlayback:!1});s.element.style.userSelect="none",n.appendChild(e.registerDisposer(s).element);const r=e.registerDisposer(new Df(t.position,this.dimensionId,"row"));r.element.style.flex="1",n.appendChild(r.element),e.bindAction("adjust-position-via-wheel",l=>{l.stopPropagation();const c=l.detail,{deltaY:d}=c;d!==0&&s.adjustDimensionPosition(this.dimensionId,Math.sign(d))});const o=this.velocity.dimensionVelocity(e,this.dimensionId),a=e.registerDisposer((0,A.Uq)(l=>l!==void 0,[o]));n.appendChild(e.registerDisposer(new zt(a,(l,c,d)=>{if(!l)return;c.classList.add("neuroglancer-position-dimension-playback");const u=document.createElement("div"),h=document.createElement("div");u.classList.add("neuroglancer-icon"),h.classList.add("neuroglancer-icon"),u.innerHTML=mf,h.innerHTML=gf,c.appendChild(u),c.appendChild(h);const f=()=>t.velocity.togglePlayback(this.dimensionId);u.addEventListener("click",f),h.addEventListener("click",f);const m=()=>{const C=o.value?.paused;u.style.display=C?"":"none",h.style.display=C?"none":""};d.registerDisposer(o.changed.add(m)),m();const g=new A.B0(0);g.changed.add(()=>{const C=g.value,k=o.value;k!==void 0&&k.velocity!==C&&(o.value={...k,velocity:C})});const v=_e({text:"\xB1",title:"Negate velocity",onClick:()=>{g.value=-g.value}}),y=d.registerDisposer(new mc(g));y.inputElement.disabled=!0,y.element.insertBefore(v,y.element.firstChild),y.element.title="Velocity in coordinates per second";const S=document.createElement("span");S.textContent="/s",y.element.appendChild(S),c.appendChild(y.element);const x=new Mi.F(Gn,Gn.STOP),b=()=>{x.value=o.value?.atBoundary??Gn.STOP,g.value=o.value?.velocity??0};b(),d.registerDisposer(o.changed.add(b)),x.changed.add(()=>{const C=x.value,k=o.value;k!==void 0&&k.atBoundary!==C&&(o.value={...k,atBoundary:C})});const E=new Po(x).element;c.appendChild(E),E.title="Behavior when lower/upper bound is reached"})).element),n.appendChild(e.registerDisposer(new en(t.velocity.playbackEnabled(this.dimensionId),{svg:vf,enableTitle:"Enable playback/velocity",disableTitle:"Disable playback/velocity",backgroundScheme:"dark"})).element),e.bindAction("adjust-velocity-via-wheel",l=>{l.stopPropagation();const c=gs(l.detail);t.velocity.multiplyVelocity(this.dimensionId,c)}),e.bindAction("toggle-playback",l=>{l.stopPropagation(),t.velocity.togglePlayback(this.dimensionId)})}get description(){return`dim ${this.dimensionName}`}toJSON(){return{type:yr,dimension:this.dimensionName}}}function vc(i,e){const t=(0,p.cQ)(e,"dimension",p.zr),n=i.coordinateSpaceCombiner.combined.value,s=n.names.indexOf(t);if(s===-1)throw new Error(`Invalid dimension name: ${JSON.stringify(t)}`);return new Tx(i,n.ids[s])}function Dx(i){Rn(i,yr,(e,t)=>vc({position:e.position,velocity:e.velocity,coordinateSpaceCombiner:e.layerSpecification.coordinateSpaceCombiner,toolBinder:e.toolBinder},t))}function Ix(i){Rn(i,yr,(e,t)=>vc({position:e.localPosition,velocity:e.localVelocity,coordinateSpaceCombiner:e.localCoordinateSpaceCombiner,toolBinder:e.toolBinder},t))}function Rx(i){Rn(i,yr,(e,t)=>vc({position:e.viewerNavigationState.position.value,velocity:e.viewerNavigationState.velocity.velocity,coordinateSpaceCombiner:e.layerSpecification.root.coordinateSpaceCombiner,toolBinder:e.toolBinder},t))}/**
 * @license
 * Copyright 2024 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const No=512,Sr=4,Lf=4,yc=.05,Oo=.05,Pf=Symbol("transferFunctionSamplerTexture"),Af={[I.UINT8]:256,[I.INT8]:256,[I.UINT16]:8192,[I.INT16]:8192,[I.UINT32]:8192,[I.INT32]:8192,[I.UINT64]:8192,[I.FLOAT32]:8192};class kn{constructor(e,t=w.yb){this.inputValue=e,this.outputColor=t}normalizedInput(e){return se(e,this.inputValue)}transferFunctionIndex(e,t){return Math.floor(this.normalizedInput(e)*(t-1))}interpolateColor(e,t){const n=w.ln.create();for(let s=0;s<4;++s)n[s]=he([this.outputColor[s],e.outputColor[s]],I.UINT8,t);return n}static copyFrom(e){const t=e.inputValue,n=w.ln.clone(e.outputColor);return new kn(t,n)}}class Vo{constructor(e=[],t,n=!0){this.controlPoints=e,this.dataType=t,this.autoComputeRange=n,this.controlPoints=e,this.range=ue[t],this.sortAndComputeRange()}get length(){return this.controlPoints.length}addPoint(e){const{inputValue:t,outputColor:n}=e,s=this.controlPoints.findIndex(o=>o.inputValue===t);s!==-1&&this.updatePointColor(s,n);const r=new kn(t,n);this.controlPoints.push(r),this.sortAndComputeRange()}removePoint(e){this.controlPoints.splice(e,1),this.computeRange()}updatePoint(e,t){this.controlPoints[e]=t;const n=t.inputValue,s=t.outputColor;this.sortAndComputeRange();for(let r=0;r<this.controlPoints.length;++r)if(this.controlPoints[r].inputValue===n&&(0,z.r1)(this.controlPoints[r].outputColor,s))return r;return-1}updatePointColor(e,t){let n=w.ln.create();if(t.length===3){const s=this.controlPoints[e].outputColor[3];n=w.ln.fromValues(t[0],t[1],t[2],s)}else n=w.ln.clone(t);this.controlPoints[e].outputColor=n}findNearestControlPointIndex(e){const n=new kn(e).normalizedInput(this.range);return this.findNearestControlPointIndexByNormalizedInput(n)}findNearestControlPointIndexByNormalizedInput(e){return(0,z.Lp)(this.controlPoints.map(t=>t.normalizedInput(this.range)),e,(t,n)=>t-n)}sortAndComputeRange(){this.controlPoints.sort((e,t)=>e.normalizedInput(this.range)-t.normalizedInput(this.range)),this.computeRange()}computeRange(){if(this.autoComputeRange)if(this.controlPoints.length==0)this.range=ue[this.dataType];else if(this.controlPoints.length===1){let e=ue[this.dataType][1];this.dataType===I.FLOAT32&&e<=this.controlPoints[0].inputValue&&(e=this.controlPoints[0].inputValue+1),this.range=[this.controlPoints[0].inputValue,e]}else this.range=[this.controlPoints[0].inputValue,this.controlPoints[this.controlPoints.length-1].inputValue];this.range[0]===this.range[1]&&(this.range=ue[this.dataType])}copy(){const e=new Vo([],this.dataType,this.autoComputeRange);return e.range=this.range,e.controlPoints=this.controlPoints.map(t=>kn.copyFrom(t)),e}}class ws{constructor(e){this.lookupTableSize=e,this.outputValues=new Uint8Array(e*Sr).fill(0)}resize(e){this.lookupTableSize=e,this.outputValues=new Uint8Array(e*Sr).fill(0)}updateFromControlPoints(e,t=void 0){const n=t||e.range,{controlPoints:s}=e,r=this.outputValues,o=this.lookupTableSize;function a(u,h){r[u]=h[0],r[u+1]=h[1],r[u+2]=h[2],r[u+3]=h[3]}function l(u){return u.transferFunctionIndex(n,o)}if(s.length===0){r.fill(0);return}const c=l(s[0]);if(c>0){const u=w.ln.fromValues(0,0,0,0);for(let h=0;h<c;++h){const f=h*Sr;a(f,u)}}let d=0;for(let u=c;u<o;++u){const h=s[d],f=u*Sr;if(d===s.length-1)a(f,h.outputColor);else{const m=s[d+1],g=l(h),v=l(m),y=(u-g)/(v-g),S=h.interpolateColor(m,y);a(f,S),u>=v&&d++}}}static equal(e,t){return(0,z.r1)(e.outputValues,t.outputValues)}copy(){const e=new ws(this.lookupTableSize);return e.outputValues.set(this.outputValues),e}}class kx extends D.O8{constructor(e,t,n=Af[e]){super(),this.dataType=e,this.trackable=t,this.lookupTable=new ws(n),this.updateLookupTable()}get sortedControlPoints(){return this.trackable.value.sortedControlPoints}get range(){return this.sortedControlPoints.range}get size(){return this.lookupTable.lookupTableSize}updateLookupTable(e=void 0){this.lookupTable.updateFromControlPoints(this.sortedControlPoints,e)}addPoint(e){this.sortedControlPoints.addPoint(e)}updatePoint(e,t){return this.sortedControlPoints.updatePoint(e,t)}removePoint(e){this.sortedControlPoints.removePoint(e)}updatePointColor(e,t){this.sortedControlPoints.updatePointColor(e,t)}findNearestControlPointIndex(e,t){const n=he(t,this.dataType,e);return this.sortedControlPoints.findNearestControlPointIndex(n)}}class Mf extends D.O8{constructor(e){super(),this.gl=e,this.texture=null,this.height=1,this.priorOptions=void 0}updateAndActivate(e){const{gl:t}=this;if(t===null)return;let{texture:n}=this;function s(o,a){if(a===void 0)throw new Error("Texture unit must be defined for transfer function texture");o.activeTexture(WebGL2RenderingContext.TEXTURE0+a),o.bindTexture(WebGL2RenderingContext.TEXTURE_2D,n)}if(n!==null&&this.optionsEqual(e))return s(t,e.textureUnit),this.width*this.height;n===null&&(n=this.texture=t.createTexture()),s(t,e.textureUnit),ki(t);const r=this.createLookupTable(e);return t.texImage2D(WebGL2RenderingContext.TEXTURE_2D,0,WebGL2RenderingContext.RGBA,this.width,this.height,0,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.UNSIGNED_BYTE,r.outputValues),this.setOptions(e),this.width*this.height}setTextureWidthAndHeightFromSize(e){this.width=e}disposed(){this.gl?.deleteTexture(this.texture),this.texture=null,this.priorOptions=void 0,super.disposed()}}class Lx extends Mf{constructor(e){super(e),this.gl=e,this.texture=null,this.priorOptions=void 0}optionsEqual(e){const t=this.priorOptions;if(t===void 0)return!1;const n=ws.equal(t.lookupTable,e.lookupTable),s=t.textureUnit===e.textureUnit;return n&&s}createLookupTable(e){return this.setTextureWidthAndHeightFromSize(e.lookupTable.lookupTableSize),e.lookupTable}setOptions(e){this.priorOptions={...e,lookupTable:e.lookupTable.copy()}}}class Px extends Mf{constructor(e){super(e),this.gl=e}optionsEqual(e){const t=this.priorOptions;if(t===void 0)return!1;const n=(0,z.wm)(t.sortedControlPoints.controlPoints,e.sortedControlPoints.controlPoints,(o,a)=>o.inputValue===a.inputValue&&(0,z.r1)(o.outputColor,a.outputColor)),s=t.textureUnit===e.textureUnit,r=t.dataType===e.dataType;return n&&s&&r}setOptions(e){this.priorOptions={...e,sortedControlPoints:e.sortedControlPoints.copy()}}createLookupTable(e){const t=this.ensureTextureSize(e.lookupTableSize);if(t===void 0)return new ws(0);this.setTextureWidthAndHeightFromSize(t);const n=new ws(t),s=e.sortedControlPoints;return n.updateFromControlPoints(s),n}ensureTextureSize(e){const t=this.gl;if(t===null)return;const n=t.getParameter(t.MAX_TEXTURE_SIZE);return Math.min(e,n)}}class Ax extends Jl{constructor(e){super(e.display,document.createElement("div"),e.visibility),this.parent=e,this.controlPointsPositionArray=new Float32Array,this.controlPointsColorArray=new Float32Array,this.linePositionArray=new Float32Array,this.transferFunction=this.registerDisposer(new kx(this.parent.dataType,this.parent.trackable,No)),this.controller=this.registerDisposer(new Nx(this.element,this.parent.dataType,this.transferFunction,()=>this.parent.trackable.value,r=>{this.parent.trackable.value=r})),this.transferFunctionLineShader=this.registerDisposer((()=>{const r=new hn(this.gl);return Tn(r),r.addAttribute("vec4","aLineStartEnd"),r.addOutputBuffer("vec4","out_color",0),r.addVarying("float","vColor"),r.setVertexMain(`
vec4 start = vec4(aLineStartEnd[0], aLineStartEnd[1], 0.0, 1.0);
vec4 end = vec4(aLineStartEnd[2], aLineStartEnd[3], 0.0, 1.0);
emitLine(start, end, 1.0);
`),r.setFragmentMain(`
out_color = vec4(0.0, 1.0, 1.0, getLineAlpha());
`),r.build()})()),this.transferFunctionShader=this.registerDisposer((()=>{const r=new hn(this.gl);return r.addAttribute("vec2","aVertexPosition"),r.addVarying("vec2","vTexCoord"),r.addOutputBuffer("vec4","out_color",0),r.addTextureSampler("sampler2D","uSampler",Pf),r.addUniform("float","uTransferFunctionEnd"),r.setVertexMain(`
gl_Position = vec4(aVertexPosition, 0.0, 1.0);
vTexCoord = (aVertexPosition + 1.0) / 2.0;
`),r.setFragmentMain(`
ivec2 texel = ivec2(floor(vTexCoord.x * uTransferFunctionEnd), 0);
out_color = texelFetch(uSampler, texel, 0);
`),r.build()})()),this.controlPointsShader=this.registerDisposer((()=>{const r=new hn(this.gl);return r.addAttribute("vec2","aVertexPosition"),r.addAttribute("vec3","aVertexColor"),r.addVarying("vec3","vColor"),r.addOutputBuffer("vec4","out_color",0),r.setVertexMain(`
gl_Position = vec4(aVertexPosition, 0.0, 1.0);
gl_PointSize = 14.0;
vColor = aVertexColor;
`),r.setFragmentMain(`
float vColorSum = vColor.r + vColor.g + vColor.b;
vec3 bordercolor = vec3(0.0, 0.0, 0.0);
if (vColorSum < 0.4) {
  bordercolor = vec3(1.0, 1.0, 1.0);
}
float dist = distance(gl_PointCoord, vec2(0.5, 0.5));
float alpha = smoothstep(0.25, 0.4, dist);
vec4 tempColor = vec4(mix(vColor, bordercolor, alpha), 1.0);
alpha = 1.0 - smoothstep(0.4, 0.5, dist);
out_color = tempColor * alpha;
`),r.build()})());const{element:t,gl:n}=this;t.classList.add("neuroglancer-transfer-function-panel"),this.textureVertexBufferArray=sf(No),this.texture=this.registerDisposer(new Lx(n));function s(r){return Ri(n,WebGL2RenderingContext.ARRAY_BUFFER,()=>r).value}this.textureVertexBuffer=this.registerDisposer(s(this.textureVertexBufferArray)),this.controlPointsVertexBuffer=this.registerDisposer(s(this.controlPointsPositionArray)),this.controlPointsColorBuffer=this.registerDisposer(s(this.controlPointsColorArray)),this.linePositionBuffer=this.registerDisposer(s(this.linePositionArray))}get drawOrder(){return 1}updateTransferFunctionPointsAndLines(){const e=this.parent.trackable.value.window;function t(T){return se(e,T)*2-1}function n(T){return T/255*2-1}function s(T){return T/255}function r(T,L,_){for(let R=0;R<gn;++R)T[L++]=_[0],T[L++]=_[1],T[L++]=_[2],T[L++]=_[3];return L}function o(T){return T>=-1&&T<=1}const{transferFunction:a}=this,{controlPoints:l}=a.trackable.value.sortedControlPoints;let c=Math.max(l.length-1,0);const d=Sr-1,u=new Float32Array(l.length*d),h=new Float32Array(l.length*2);let f=0,m=null,g=null;const v=l.map(T=>{const L=t(T.inputValue),_=n(T.outputColor[3]);return{input:L,output:_}});if(l.length>0){const{firstPointIndexInWindow:T,lastPointIndexInWindow:L,pointClosestToLeftEdge:_,pointClosestToRightEdge:R}=C();if(T===null){const P=v[l.length-1].input<-1,V=v[0].input>1;P?k():!V&&l.length>1&&E(_,R)}else{const P=v[T];P.input>-1&&(T>0?b(T,P):m=w.ln.fromValues(P.input,-1,P.input,P.output),c+=1);const V=v[L];V.input<1&&(L<l.length-1?x(L,V):g=w.ln.fromValues(V.input,V.output,1,V.output),c+=1)}}const y=[];for(let T=0;T<l.length;++T){const L=T*d,_=T*2,R=v[T].input,P=v[T].output,{outputColor:V}=l[T];if(u[L]=s(V[0]),u[L+1]=s(V[1]),u[L+2]=s(V[2]),h[_]=R,h[_+1]=P,T===l.length-1)break;if(!(o(R)&&o(P)))continue;c+=1;const $=w.ln.fromValues(R,P,v[T+1].input,v[T+1].output);y.push($)}const S=new Float32Array(c*Lf*gn);m!==null&&(f=r(S,f,m));for(const T of y)f=r(S,f,T);g!==null&&r(S,f,g),this.controlPointsColorArray=u,this.controlPointsPositionArray=h,this.linePositionArray=S,this.controlPointsVertexBuffer.setData(this.controlPointsPositionArray),this.controlPointsColorBuffer.setData(this.controlPointsColorArray),this.linePositionBuffer.setData(this.linePositionArray);function x(T,L){const _=v[T+1],R=se([L.input,_.input],1),P=he([L.output,_.output],I.FLOAT32,R);g=w.ln.fromValues(L.input,L.output,1,P)}function b(T,L){const _=v[T-1],R=se([_.input,L.input],-1),P=he([_.output,L.output],I.FLOAT32,R);m=w.ln.fromValues(-1,P,L.input,L.output)}function E(T,L){if(c+=1,T===null||L===null)throw new Error("Could not find points closest to the left and right edges");const _=se([T.input,L.input],-1),R=se([T.input,L.input],1),P=he([T.output,L.output],I.FLOAT32,_),V=he([T.output,L.output],I.FLOAT32,R);m=w.ln.fromValues(-1,P,1,V)}function C(){let T=null,L=null,_=null,R=null;for(let P=0;P<l.length;++P){const V=v[P];if(o(V.input)&&(T=T??P,L=P),V.input<-1)_=V;else if(V.input>1){R=V;break}}return{firstPointIndexInWindow:T,lastPointIndexInWindow:L,pointClosestToLeftEdge:_,pointClosestToRightEdge:R}}function k(){const T=l.length-1;c+=1;const L=v[T].output;m=w.ln.fromValues(-1,L,1,L)}}drawIndirect(){const{transferFunctionLineShader:e,gl:t,transferFunctionShader:n,controlPointsShader:s}=this;this.setGLLogicalViewport(),t.clearColor(0,0,0,0),t.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT),t.enable(WebGL2RenderingContext.BLEND),t.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),t.disable(WebGL2RenderingContext.DEPTH_TEST),t.disable(WebGL2RenderingContext.STENCIL_TEST);{n.bind();const r=n.attribute("aVertexPosition");t.uniform1f(n.uniform("uTransferFunctionEnd"),No-1),this.textureVertexBuffer.bindToVertexAttrib(r,2,WebGL2RenderingContext.FLOAT);const o=n.textureUnit(Pf);this.texture.updateAndActivate({lookupTable:this.transferFunction.lookupTable,textureUnit:o}),Do(this.gl,No,1),t.disableVertexAttribArray(r),t.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}if(this.controlPointsPositionArray.length>0){const{renderViewport:r}=this;e.bind();const o=e.attribute("aLineStartEnd");this.linePositionBuffer.bindToVertexAttrib(o,4,WebGL2RenderingContext.FLOAT),In(e,{width:r.logicalWidth,height:r.logicalHeight},1),Dn(t,this.linePositionArray.length/(gn*Lf),1),t.disableVertexAttribArray(o),s.bind();const a=s.attribute("aVertexPosition");this.controlPointsVertexBuffer.bindToVertexAttrib(a,2,WebGL2RenderingContext.FLOAT);const l=s.attribute("aVertexColor");this.controlPointsColorBuffer.bindToVertexAttrib(l,3,WebGL2RenderingContext.FLOAT),t.drawArrays(t.POINTS,0,this.controlPointsPositionArray.length/2),t.disableVertexAttribArray(a),t.disableVertexAttribArray(l)}t.disable(WebGL2RenderingContext.BLEND)}update(){this.transferFunction.updateLookupTable(this.parent.trackable.value.window),this.updateTransferFunctionPointsAndLines()}isReady(){return!0}}function Mx(i,e){function t(r){const o=document.createElement("input");return o.addEventListener("focus",()=>{o.select()}),o.classList.add("neuroglancer-transfer-function-widget-bound"),o.type="text",o.spellcheck=!1,o.autocomplete="off",o.title=`${r===0?"Lower":"Upper"} window for transfer function`,o}const n=document.createElement("div");n.classList.add("neuroglancer-transfer-function-window-bounds");const s=[t(0),t(1)];for(let r=0;r<2;++r){const o=s[r];o.addEventListener("input",()=>{pc(o)}),o.addEventListener("change",()=>{const a=e.value.window,l={range:a,window:a};try{const c=qt(i,o.value),d=gr(l,"window",r,c,!0).window;if(d[0]===d[1])throw new Error("Window bounds cannot be equal");e.value={...e.value,window:d}}catch{ms(o,a[r])}})}return n.appendChild(s[0]),n.appendChild(s[1]),{container:n,inputs:s}}const Sc=Pe.fromObject({"shift?+mousedown0":{action:"add-or-drag-point"},"shift+dblclick0":{action:"remove-point"},"shift?+mousedown2":{action:"change-point-color"}});class Nx extends D.O8{constructor(e,t,n,s,r){super(),this.element=e,this.dataType=t,this.transferFunction=n,this.getModel=s,this.setModel=r,this.currentGrabbedControlPointIndex=-1,e.title=Sc.describe(),this.registerDisposer(new fn(e,Sc)),X(e,"add-or-drag-point",o=>{const a=o.detail;this.updateValue(this.addControlPoint(a)),$t(a,l=>{this.updateValue(this.moveControlPoint(l))})}),X(e,"remove-point",o=>{const a=o.detail,l=this.findControlPointIfNearCursor(a);l!==-1&&(this.transferFunction.removePoint(l),this.updateValue({...this.getModel(),sortedControlPoints:this.transferFunction.trackable.value.sortedControlPoints}))}),X(e,"change-point-color",o=>{const a=o.detail,l=this.findControlPointIfNearCursor(a);if(l!==-1){const c=this.transferFunction.trackable.value.defaultColor,d=this.convertPanelSpaceColorToAbsoluteValue(c);this.transferFunction.updatePointColor(l,d),this.updateValue({...this.getModel(),sortedControlPoints:this.transferFunction.trackable.value.sortedControlPoints})}})}updateValue(e){e!==void 0&&this.setModel(e)}convertPanelSpaceInputToAbsoluteValue(e){return he(this.transferFunction.trackable.value.window,this.dataType,e)}convertPanelSpaceColorToAbsoluteValue(e){return e.length===3?w.eR.fromValues(Math.round(e[0]*255),Math.round(e[1]*255),Math.round(e[2]*255)):w.ln.fromValues(Math.round(e[0]*255),Math.round(e[1]*255),Math.round(e[2]*255),Math.round(e[3]*255))}addControlPoint(e){const t=this.transferFunction.trackable.value.defaultColor,n=this.findControlPointIfNearCursor(e);if(n!==-1){this.currentGrabbedControlPointIndex=n;return}const s=this.getControlPointPosition(e);if(s===void 0)return;const{normalizedX:r,normalizedY:o}=s,a=w.ln.fromValues(t[0],t[1],t[2],o);return this.transferFunction.addPoint(new kn(this.convertPanelSpaceInputToAbsoluteValue(r),this.convertPanelSpaceColorToAbsoluteValue(a))),this.currentGrabbedControlPointIndex=this.findControlPointIfNearCursor(e),{...this.getModel(),sortedControlPoints:this.transferFunction.trackable.value.sortedControlPoints}}moveControlPoint(e){if(this.currentGrabbedControlPointIndex!==-1){const t=this.getControlPointPosition(e);if(t===void 0)return;const{normalizedX:n,normalizedY:s}=t,r=this.transferFunction.trackable.value.sortedControlPoints.controlPoints[this.currentGrabbedControlPointIndex].outputColor;return r[3]=Math.round(s*255),this.currentGrabbedControlPointIndex=this.transferFunction.updatePoint(this.currentGrabbedControlPointIndex,new kn(this.convertPanelSpaceInputToAbsoluteValue(n),r)),{...this.getModel(),sortedControlPoints:this.transferFunction.trackable.value.sortedControlPoints}}}getControlPointPosition(e){const t=this.element.getBoundingClientRect();let n=(e.clientX-t.left)/t.width,s=(t.bottom-e.clientY)/t.height;if(!(n<0||n>1||s<0||s>1))return n<Oo/3?n=0:n>1-Oo/3&&(n=1),s<Oo?s=0:s>1-Oo&&(s=1),{normalizedX:n,normalizedY:s}}findControlPointIfNearCursor(e){const{transferFunction:t}=this,{window:n}=t.trackable.value,s=t.sortedControlPoints.controlPoints.length;function r(S){return S<0||S>=s?null:se(n,t.sortedControlPoints.controlPoints[S].inputValue)}function o(S){return S<0||S>=s?null:t.sortedControlPoints.controlPoints[S].outputColor[3]/255}const a=this.getControlPointPosition(e);if(a===void 0)return-1;const l=a.normalizedX,c=a.normalizedY,d=t.findNearestControlPointIndex(l,n);if(d===-1)return-1;const u=r(d);if(Math.abs(l-u)>yc)return-1;const h=[[d,Math.abs(o(d)-c)]],f=r(d+1);(f!==null?Math.abs(f-l):1/0)<=yc&&h.push([d+1,Math.abs(o(d+1)-c)]);const g=r(d-1);return(g!==null?Math.abs(g-l):1/0)<=yc&&h.push([d-1,Math.abs(o(d-1)-c)]),h.sort((S,x)=>S[1]-x[1])[0][0]}}class Ox extends Gt{constructor(e,t,n,s){super(e),this.display=t,this.dataType=n,this.trackable=s,this.transferFunctionPanel=this.registerDisposer(new Ax(this)),this.window=Mx(this.dataType,this.trackable);const{element:r}=this;r.classList.add("neuroglancer-transfer-function-widget"),r.appendChild(this.transferFunctionPanel.element),r.appendChild(this.window.container),this.window.container.dispatchEvent(new Event("change"));const o=document.createElement("div");o.classList.add("neuroglancer-transfer-function-color-picker");const a=this.registerDisposer(new Ro((0,A.Uq)(l=>l.defaultColor,[s]),()=>w.eR.fromValues(1,1,1)));a.element.title="Transfer Function Color Picker",a.element.id="neuroglancer-tf-color-widget",a.element.addEventListener("change",()=>{s.value={...this.trackable.value,defaultColor:a.model.value}}),a.element.addEventListener("input",()=>{s.value={...this.trackable.value,defaultColor:a.model.value}}),o.appendChild(a.element),r.appendChild(o),this.updateControlPointsAndDraw(),this.registerDisposer(this.trackable.changed.add(()=>{this.updateControlPointsAndDraw()})),ms(this.window.inputs[0],this.trackable.value.window[0]),ms(this.window.inputs[1],this.trackable.value.window[1])}updateView(){this.transferFunctionPanel.scheduleRedraw()}updateControlPointsAndDraw(){this.transferFunctionPanel.update(),this.updateView()}}function Vx(i,e,t,n){i.addUniform("highp float",`uTransferFunctionEnd_${e}`),i.addTextureSampler("sampler2D",`uTransferFunctionSampler_${e}`,`TransferFunction.${e}`);const s=us(i,e,t,!0),r=vt(t);let o=`
vec4 ${e}_(float inputValue) {
  int index = clamp(int(round(inputValue * uTransferFunctionEnd_${e})), 0, int(uTransferFunctionEnd_${e}));
  return texelFetch(uTransferFunctionSampler_${e}, ivec2(index, 0), 0);
}
vec4 ${e}(${r} inputValue) {
  float v = computeInvlerp(inputValue, uLerpParams_${e});
  defaultMaxProjectionIntensity = v;
  return v < 0.0 ? vec4(0.0, 0.0, 0.0, 0.0) : ${e}_(clamp(v, 0.0, 1.0));
}
vec4 ${e}() {
  return ${e}(getDataValue(${n.join(",")}));
}
`;if(t!==I.UINT64&&t!==I.FLOAT32){const a=re[t]?"int":"uint";o+=`
vec4 ${e}(${a} inputValue) {
  return ${e}(${r}(inputValue));
}
`}return[s[0],s[1],s[2],o]}function _x(i,e,t,n,s=Af[t]){const{gl:r}=i;i.transferFunctionTextures.get(`TransferFunction.${e}`)===void 0&&i.transferFunctionTextures.set(`TransferFunction.${e}`,new Px(r));const a=i.bindAndUpdateTransferFunctionTexture(`TransferFunction.${e}`,n,t,s);if(a===void 0)throw new Error("Failed to create transfer function texture");r.uniform1f(i.uniform(`uTransferFunctionEnd_${e}`),a-1);const l=n.range;Pi(i,e,t,l)}function Bx(i,e){i.bindInputEventMap(Sc)}function Fx(i){return{makeControl:(e,t,n)=>{const{watchableValue:s,channelCoordinateSpaceCombiner:r,defaultChannel:o,dataType:a}=i(e);if(r!==void 0&&o.length!==0){const c=t.registerDisposer(new oi(r.combined)),d=t.registerDisposer(new bs(c,r,{copyButton:!1}));t.registerDisposer(c.changed.add(()=>{const h=c.value,f=Array.from(h,g=>Math.floor(g)),m=s.value;(0,z.r1)(m.channel,f)||(s.value={...s.value,channel:f})}));const u=()=>{const h=c.value,f=s.value;(0,z.r1)(f.channel,h)||(h.set(f.channel),c.changed.dispatch())};u(),t.registerDisposer(s.changed.add(u)),n.labelContainer.appendChild(d.element)}const l=t.registerDisposer(new Ox(n.visibility,n.display,a,s));return{control:l,controlElement:l.element}},activateTool:(e,t)=>{Bx(e,t)}}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ux(i){const e=/\/\/.*?$|\/\*(?:.|\n)*?\*\/|'(?:\\.|[^\\'])*'|"(?:\\.|[^\\"])*"/gm;return i.replace(e,t=>t.startsWith("/")?t.replace(/[^\s]/g," "):t)}function $x(i){const e=/^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|"(?:\\.|[^\\"])*"|true|false|:|\s+|,|\[|\]|\{|\})/;let t=0;const n=i;e:for(;i.length;){const s=i.match(e);if(s===null)break;const r=s[0];switch(r.charAt(0)){case"[":case"{":++t;break;case"]":case"}":if(--t<0)return-1;break;case",":if(t===0)break e;break;default:if(t===0){i=i.substring(r.length);break e}break}i=i.substring(r.length)}return t!==0?-1:n.length-i.length}function Gx(i){const e=[],t=new Map;if(i===void 0)return{errors:e,parameters:t};const n=/^([_a-z][_a-zA-Z0-9]*)[ \t]*=/;for(;i=i.trim(),i.length!==0;){const s=i.match(n);if(s===null){e.push("Invalid #uicontrol parameter syntax, expected: <param>=<value>, ...");break}const r=s[1];i=i.substring(s[0].length);const o=$x(i);if(o<=0){e.push("Invalid #uicontrol parameter syntax, expected: <param>=<value>, ...");break}let a;try{a=JSON.parse(i.substring(0,o))}catch{e.push(`Invalid #uicontrol parameter value for ${r}: ${a}`);break}t.has(r)?e.push(`Duplicate #uicontrol parameter: ${r}`):t.set(r,a),i=i.substring(o),i=i.trim(),i.length>0&&!i.startsWith(",")&&e.push("Invalid #uicontrol parameter syntax, expected: <param>=<value>, ..."),i=i.substring(1)}return{parameters:t,errors:e}}function zx(i,e){let t,n,s,r;const o=[];i!=="float"&&i!=="uint"&&i!=="int"&&o.push("type must be float, int, or uint");for(const[a,l]of e){const c=()=>{if(typeof l!="number"){o.push(`Expected ${a} argument to be a number`);return}return(i==="int"||i==="uint")&&(Number.isInteger(l)||o.push(`Expected ${a} argument to be an integer`),i==="uint"&&l<0&&o.push(`Expected ${a} argument to be an unsigned integer`)),l};a==="min"?t=c():a==="max"?n=c():a==="default"?r=c():a==="step"?s=c():o.push(`Invalid parameter: ${a}`)}return t===void 0&&o.push("min must be specified"),n===void 0&&o.push("max must be specified"),t!==void 0&&n!==void 0&&(t>n&&o.push("min must be less than max"),s===void 0&&(i==="float"?s=(n-t)/100:s=1),r!==void 0?(r<t||r>n)&&o.push("default must be within valid range"):i==="float"?r=(t+n)/2:r=t),o.length>0?{errors:o}:{control:{type:"slider",valueType:i,min:t,max:n,step:s,default:r},errors:void 0}}function Wx(i,e){let t=!1;const n=[];i!=="bool"&&n.push("type must be bool");for(const[s,r]of e)if(s==="default"){if(typeof r!="boolean"){n.push(`Expected ${s} argument to be a boolean`);continue}t=r}else n.push(`Invalid parameter: ${s}`);return n.length>0?{errors:n}:{control:{type:"checkbox",valueType:i,default:t},errors:void 0}}function Hx(i,e){let t="white";const n=[];i!=="vec3"&&n.push("type must be vec3");for(const[s,r]of e)s==="default"?typeof r!="string"?n.push("Expected default argument to be a string"):t=r:n.push(`Invalid parameter: ${s}`);return n.length>0?{errors:n}:{control:{type:"color",valueType:i,defaultString:t,default:me(t)},errors:void 0}}function _o(i,e){typeof i=="number"&&(i=[i]);const t=new Array(e);return(0,p.Xu)(t,i,n=>{if(!Number.isInteger(n)||n<0)throw new Error(`Expected non-negative integer, but received: ${JSON.stringify(n)}`);return n}),t}function Jx(i,e,t){const{imageData:n,properties:s}=t;if(n!==void 0)return jx(i,e,n);if(s!==void 0)return Yx(i,e,s);const r=[];return r.push("invlerp control not supported"),{errors:r}}function jx(i,e,t){const n=[];i!=="invlerp"&&n.push("type must be invlerp");let s=new Array(t.channelRank).fill(0);const{dataType:r}=t;let o=!0,a=ue[r],l;for(const[c,d]of e)try{switch(c){case"range":{a=Et(d,r);break}case"window":{l=Xe(Et(d,r));break}case"clamp":{typeof d!="boolean"?n.push(`Invalid clamp value: ${JSON.stringify(d)}`):o=d;break}case"channel":{s=_o(d,s.length);break}default:n.push(`Invalid parameter: ${c}`);break}}catch(u){n.push(`Invalid ${c} value: ${u.message}`)}return n.length>0?{errors:n}:{control:{type:"imageInvlerp",dataType:r,clamp:o,default:{range:a,window:l??tt(a),channel:s}},errors:void 0}}function Yx(i,e,t){const n=[];i!=="invlerp"&&n.push("type must be invlerp");let s=!0,r,o,a;for(const[c,d]of e)try{switch(c){case"range":{r=wi(d);break}case"window":{o=wi(d);break}case"clamp":{typeof d!="boolean"?n.push(`Invalid clamp value: ${JSON.stringify(d)}`):s=d;break}case"property":{const u=(0,p.zr)(d);if(!t.has(u))throw new Error(`Property not defined: ${JSON.stringify(a)}`);a=u;break}default:n.push(`Invalid parameter: ${c}`);break}}catch(u){n.push(`Invalid ${c} value: ${u.message}`)}if(n.length>0)return{errors:n};if(a===void 0)for(const c of t.keys()){a=c;break}const l=t.get(a);return r!==void 0&&(r=De(r,l)),o!==void 0&&(o=De(o,l)),{control:{type:"propertyInvlerp",clamp:s,properties:t,default:{range:r,window:o,property:a,dataType:l}},errors:void 0}}function Qx(i,e,t){const n=t.imageData,s=n?.dataType,r=n?.channelRank,o=[];let a=new Array(r).fill(0),l=w.eR.fromValues(1,1,1),c,d=new Vo([],s!==void 0?s:I.FLOAT32),u=!1;i!=="transferFunction"&&o.push("type must be transferFunction"),s===void 0&&o.push("image data must be provided to use a transfer function");for(const[h,f]of e)try{switch(h){case"channel":{a=_o(f,a.length);break}case"defaultColor":{l=me(f);break}case"window":{s!==void 0&&(c=Xe(Et(f,s)));break}case"controlPoints":{u=!0,s!==void 0&&(d=Vf(f,s));break}default:o.push(`Invalid parameter: ${h}`);break}}catch(m){o.push(`Invalid ${h} value: ${m.message}`)}if(c===void 0&&(c=d.range),d.length===0&&!u&&s!==void 0){const h=he(c,s,.4),f=he(c,s,.7);d.addPoint(new kn(h,w.yb)),d.addPoint(new kn(f,w.ln.fromValues(255,255,255,255)))}return o.length>0?{errors:o}:{control:{type:"transferFunction",dataType:s,default:{sortedControlPoints:d,channel:a,defaultColor:l,window:c}},errors:void 0}}const qx=new Map([["slider",zx],["color",Hx],["invlerp",Jx],["checkbox",Wx],["transferFunction",Qx]]);function br(i,e={}){i=Ux(i);const t=/^[ \t]*#[ \t]*uicontrol[ \t]+(.*)$/gm,n=/^([_a-zA-Z][_a-zA-Z0-9]*)[ \t]+([a-z][a-zA-Z0-9_]*)(?:[ \t]+([a-z]+))?[ \t]*(?:\([ \t]*(.*)\)[ \t]*)?/,s=[],r=new Map,o=i.replace(t,(a,l,c)=>{const d=l.match(n),u=()=>Math.max(0,i.substring(0,c).split(`
`).length-1);if(d===null)return s.push({line:u(),message:"Invalid #uicontrol syntax, expected: #uicontrol <type> <name> <control>(<param>=<value>, ...)"}),"";const h=d[1],f=d[2],m=d[3]??h,g=d[4],{parameters:v,errors:y}=Gx(g);for(const b of y)s.push({line:u(),message:b});if(r.has(f)&&s.push({line:u(),message:`Duplicate definition for control ${f}`}),y.length>0)return"";const S=qx.get(m);if(S===void 0)return s.push({line:u(),message:`Invalid control type ${m}`}),"";const x=S(h,v,e);if(x.errors!==void 0){for(const b of x.errors)s.push({line:u(),message:b});return""}return r.set(f,x.control),""});return{source:i,code:o,errors:s,controls:r}}function Nf(i){return`u_shaderControl_${i}`}function Cs(i,e){const{builderValues:t}=i;for(const[n,s]of i.parseResult.controls){const r=Nf(n),o=t[n];switch(s.type){case"imageInvlerp":{const a=[us(e,r,s.dataType,s.clamp),`
float ${r}() {
  return ${r}(getDataValue(${o.channel.join(",")}));
}
`];e.addFragmentCode(a),e.addFragmentCode(`#define ${n} ${r}
`);break}case"propertyInvlerp":{const a=o.property,l=s.properties.get(a),c=[us(e,r,l,s.clamp),`
float ${r}() {
  return ${r}(prop_${a}());
}
`];e.addVertexCode(c),e.addVertexCode(`#define ${n} ${r}
`);break}case"checkbox":{const a=`#define ${n} ${o.value}
`;e.addFragmentCode(a),e.addVertexCode(a);break}case"transferFunction":{e.addFragmentCode(`#define ${n} ${r}
`),e.addFragmentCode(Vx(e,r,s.dataType,o.channel));break}default:{e.addUniform(`highp ${s.valueType}`,r),e.addVertexCode(`#define ${n} ${r}
`),e.addFragmentCode(`#define ${n} ${r}
`);break}}}}function Kx(i){const e={};for(const[t,n]of i)e[t]=n;return e}function Xx(i,e){return e instanceof Map?Array.from(e.entries()):e}function Of(i){if(i!==void 0)return JSON.stringify(Kx(i),Xx)}class Zx{constructor(){this.changed=new j.IY,this.controls=void 0}get value(){return this.controls}set value(e){Of(e)!==Of(this.controls)&&(this.controls=e,this.changed.dispatch())}}function eE(i,e,t){return i===void 0?t:((0,p.Rf)(i),{range:(0,p.MM)(i,"range",n=>Et(n,e),t.range),window:(0,p.MM)(i,"window",n=>Xe(Et(n,e)),t.window),channel:(0,p.MM)(i,"channel",n=>_o(n,t.channel.length),t.channel)})}class tE extends A.DN{constructor(e,t){super(t,n=>eE(n,e,t)),this.dataType=e,this.defaultValue=t}toJSON(){const{value:{range:e,window:t,channel:n},dataType:s,defaultValue:r}=this,o=H(e,s,r.range),a=H(t,s,r.window),l=(0,z.r1)(r.channel,n)?void 0:n;if(!(o===void 0&&a===void 0&&l===void 0))return{range:o,window:a,channel:l}}}function nE(i,e,t){if(i===void 0)return t;(0,p.Rf)(i);const n=(0,p.MM)(i,"property",r=>{if(r=(0,p.zr)(r),!e.has(r))throw new Error(`Invalid value: ${JSON.stringify(r)}`);return r},t.property),s=e.get(n);return{property:n,dataType:s,range:(0,p.MM)(i,"range",r=>Et(r,s),t.range),window:(0,p.MM)(i,"window",r=>Xe(Et(r,s)),t.window)}}class iE extends A.DN{constructor(e,t){super(t,n=>nE(n,e,t)),this.properties=e,this.defaultValue=t}toJSON(){const{value:{range:e,window:t,property:n,dataType:s},defaultValue:r}=this,o=ue[s],a=H(e??o,s,r.range??o),l=H(t??o,s,r.window??o),c=n===r.property?void 0:n;if(!(a===void 0&&l===void 0&&c===void 0))return{range:a,window:l,property:c}}}function Vf(i,e){const t=(0,p.$v)(i,n=>{const s=e===I.UINT64&&typeof n[0]=="string"||typeof n[0]=="number";if(n.length!==3||!s||typeof n[1]!="string"||typeof n[2]!="number")throw new Error(`Expected array of length 3 (x, "#RRGGBB", A), but received: ${JSON.stringify(n)}`);const r=qt(e,n[0]);if(n[1].length!==7||n[1][0]!=="#")throw new Error(`Expected #RRGGBB, but received: ${JSON.stringify(n[1])}`);if(n[2]<0||n[2]>1)throw new Error(`Expected opacity in range [0, 1], but received: ${JSON.stringify(n[2])}`);const o=me(n[1]);function a(l){return Math.min(255,Math.max(Math.round(l*255),0))}return new kn(r,w.ln.fromValues(a(o[0]),a(o[1]),a(o[2]),a(n[2])))});return new Vo(t,e)}function sE(i,e,t){if(i===void 0)return t;(0,p.Rf)(i);const n=(0,p.MM)(i,"controlPoints",r=>Vf(r,e),t.sortedControlPoints),s=(0,p.MM)(i,"window",r=>Et(r,e),t.window);return{sortedControlPoints:n,channel:(0,p.MM)(i,"channel",r=>_o(r,t.channel.length),t.channel),defaultColor:(0,p.MM)(i,"defaultColor",r=>me(r),t.defaultColor),window:s}}function rE(i){return{...i,sortedControlPoints:i.sortedControlPoints.copy()}}class oE extends A.DN{constructor(e,t){const n=rE(t);super(n,s=>sE(s,e,n)),this.dataType=e,this.defaultValue=t}controlPointsToJson(e,t){function n(s){return t===I.UINT64?s.toJSON():s}return e.map(s=>[n(s.inputValue),ze(w.eR.fromValues(s.outputColor[0]/255,s.outputColor[1]/255,s.outputColor[2]/255)),s.outputColor[3]/255])}toJSON(){const{value:{channel:e,sortedControlPoints:t,defaultColor:n,window:s},dataType:r,defaultValue:o}=this,a=H(s,r,o.window),l=(0,z.r1)(o.channel,e)?void 0:e,c=(0,z.r1)(o.defaultColor,n)?void 0:ze(n),d=(0,z.wm)(o.sortedControlPoints.controlPoints,t.controlPoints,(u,h)=>(0,z.r1)(u.outputColor,h.outputColor)&&u.inputValue===h.inputValue)?void 0:this.controlPointsToJson(t.controlPoints,r);if(!(l===void 0&&c===void 0&&d===void 0&&a===void 0))return{channel:l,defaultColor:c,controlPoints:d,window:a}}}function _f(i){switch(i.type){case"slider":return{trackable:new A.DN(i.default,e=>{let t;if(i.valueType==="float"?t=(0,p.zo)(e):t=(0,p.bX)(e),t<i.min||t>i.max)throw new Error(`${JSON.stringify(e)} is outside valid range [${i.min}, ${i.max}]`);return t}),getBuilderValue:()=>null};case"color":return{trackable:new q(i.default),getBuilderValue:()=>null};case"imageInvlerp":return{trackable:new tE(i.dataType,i.default),getBuilderValue:e=>({channel:e.channel,dataType:i.dataType})};case"propertyInvlerp":return{trackable:new iE(i.properties,i.default),getBuilderValue:e=>({property:e.property,dataType:e.dataType})};case"checkbox":return{trackable:new rt(i.default),getBuilderValue:e=>({value:e})};case"transferFunction":return{trackable:new oE(i.dataType,i.default),getBuilderValue:e=>({channel:e.channel,dataType:i.dataType})}}}function Bf(i,e){return JSON.stringify(i)+"\0"+e.source}function Bo(i){const e={},t=[];for(const[n,s]of i.controls){const{trackable:r,getBuilderValue:o}=_f(s),a=o(r.value);e[n]=a,s.type==="propertyInvlerp"&&t.push(a.property)}return{builderValues:e,parseResult:i,key:Bf(e,i),referencedProperties:t}}class Fo extends D.O8{constructor(e,t=(0,A.XZ)({}),n){super(),this.fragmentMain=e,this.dataContext=t,this.channelCoordinateSpaceCombiner=n,this.changed=new j.IY,this.controls=new Zx,this.fragmentMainGeneration=-1,this.dataContextGeneration=-1,this.parseErrors_=[],this.processedFragmentMain_="",this.controlsGeneration=-1,this.parseResultChanged=new j.IY,this.state_=new Map,this.unparsedJson=void 0,this.registerDisposer(e.changed.add(()=>this.handleFragmentMainChanged())),this.registerDisposer(this.controls.changed.add(()=>this.handleControlsChanged())),this.registerDisposer(this.dataContext.changed.add(()=>this.handleFragmentMainChanged())),this.handleFragmentMainChanged();const s=this;this.parseErrors={changed:this.parseResultChanged,get value(){return s.handleFragmentMainChanged(),s.parseErrors_}},this.processedFragmentMain={changed:this.parseResultChanged,get value(){return s.handleFragmentMainChanged(),s.processedFragmentMain_}},this.parseResult={changed:this.parseResultChanged,get value(){return s.parseResult_}},this.builderState=(0,A.Uq)((l,c)=>{const d={},u=[];for(const[h,{control:f,trackable:m,getBuilderValue:g}]of c){const v=g(m.value);d[h]=v,f.type==="propertyInvlerp"&&u.push(v.property)}return{key:Bf(d,l),parseResult:l,builderValues:d,referencedProperties:u}},[this.parseResult,this],(l,c)=>l.key===c.key);const r=(0,A.Uq)(l=>{const c=[];for(const{control:d,trackable:u}of l.values())d.type==="imageInvlerp"&&c.push({channel:u.value.channel});return c},[this],(l,c)=>(0,z.wm)(l,c,(d,u)=>(0,z.r1)(d.channel,u.channel))),o=(0,A.Uq)(l=>{const c=[];for(const{control:d,trackable:u}of l.values())d.type==="propertyInvlerp"&&c.push(u.value.property);return c},[this],z.r1),a=(0,A.ol)(l=>{const c=[];for(const{control:d,trackable:u}of l.values())if(d.type==="imageInvlerp")c.push(u.value.window);else if(d.type==="propertyInvlerp"){const{dataType:h,range:f,window:m}=u.value;c.push(m??f??ue[h])}return c},this);this.histogramSpecifications=this.registerDisposer(new Rp(r,o,a))}handleFragmentMainChanged(){const e=this.fragmentMain.changed.count,t=this.dataContext.changed.count;if(e===this.fragmentMainGeneration&&t===this.dataContextGeneration)return;this.fragmentMainGeneration=e,this.dataContextGeneration=t;const n=this.dataContext.value;if(n===null)this.parseResult_={source:"",code:"",controls:new Map,errors:[{line:0,message:"Loading"}]},this.parseErrors_=[],this.processedFragmentMain_="",this.controls.value=void 0;else{const s=this.parseResult_=br(this.fragmentMain.value,n);this.parseErrors_=s.errors,this.processedFragmentMain_=s.code,s.errors.length===0&&(this.controls.value=s.controls)}this.parseResultChanged.dispatch()}handleControlsChanged(){const e=this.controls.changed.count;if(e===this.controlsGeneration)return;this.controlsGeneration=e;const t=this.controls.value;if(t===void 0)return;let n=!1;const{state_:s,unparsedJson:r}=this;for(const[o,a]of s)t.get(o)===void 0&&(a.trackable.changed.remove(this.changed.dispatch),s.delete(o),n=!0);for(const[o,a]of t){let l=s.get(o);if(l!==void 0&&JSON.stringify(l.control)!==JSON.stringify(a)&&(l.trackable.changed.remove(this.changed.dispatch),l=void 0),l===void 0){const{trackable:c,getBuilderValue:d}=_f(a);l={control:a,trackable:c,getBuilderValue:d},l.trackable.changed.add(this.changed.dispatch),s.set(o,l),n=!0}if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,o)){n=!0;try{l.trackable.restoreState(r[o])}catch{}}}r!==void 0&&(n=!0),this.unparsedJson=void 0,n&&this.changed.dispatch()}get state(){return this.controls.changed.count!==this.controlsGeneration&&this.handleControlsChanged(),this.state_}get value(){return this.state}restoreState(e){if(e===void 0)return;const{state:t}=this;if((0,p.Rf)(e),this.controls.value===void 0){this.unparsedJson=e,this.changed.dispatch();return}for(const[s,r]of t){const{trackable:o}=r;if(o.reset(),Object.prototype.hasOwnProperty.call(e,s))try{o.restoreState(e[s])}catch{}}this.unparsedJson=void 0}reset(){for(const e of this.state.values())e.trackable.reset();this.unparsedJson!==void 0&&(this.unparsedJson=void 0,this.changed.dispatch())}toJSON(){const{state:e}=this,{unparsedJson:t}=this;if(t!==void 0)return t;const n={};let s=!0;for(const[r,o]of e){const a=o.trackable.toJSON();a!==void 0&&(n[r]=a,s=!1)}if(!s)return n}}function Ff(i,e,t,n,s){const r=Nf(t),o=e.uniform(r);switch(n.type){case"slider":switch(n.valueType){case"int":case"uint":i.uniform1i(o,s);break;case"float":i.uniform1f(o,s)}break;case"color":i.uniform3fv(o,s);break;case"imageInvlerp":Pi(e,r,n.dataType,s.range);break;case"propertyInvlerp":{const{dataType:a}=s;Pi(e,r,a,s.range??ue[a]);break}case"checkbox":break;case"transferFunction":_x(e,r,n.dataType,s.sortedControlPoints)}}function Oi(i,e,t,n){const{state:s}=t;if(t.controls.value===n)for(const[r,o]of s)Ff(i,e,r,o.control,o.trackable.value);else for(const[r,o]of n){const a=s.get(r),l=a!==void 0&&JSON.stringify(a.control)===JSON.stringify(o)?a.trackable.value:o.default;Ff(i,e,r,o,l)}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class aE extends A.B0{}class lE extends Yl{constructor(){super((e,{showMatches:t,segmentationState:n})=>{e.registerDisposer(t.changed.add(this.changed.dispatch)),e.registerDisposer(n.changed.add(this.changed.dispatch)),e.registerDisposer((0,A.no)((s,r)=>{if(r==null)return;const{segmentationGroupState:o}=r;s.registerDisposer(o.changed.add(this.changed.dispatch)),s.registerDisposer((0,A.no)((a,l)=>{const{visibleSegments:c}=l;let d=c.size===0;a.registerDisposer(c.changed.add(()=>{const u=c.size===0;u!==d&&(d=u,this.changed.dispatch())}))},o))},n))})}get(e){let t=super.get(e);return t===void 0&&(t={segmentationState:new A.B0(void 0),showMatches:new rt(!1)},super.set(e,t)),t}}const Uf=`
void main() {
  setColor(defaultColor());
}
`;class $f extends D.O8{constructor(){super(...arguments),this.annotationProperties=new A.B0(void 0),this.shader=mo(Uf),this.shaderControls=new Fo(this.shader,(0,A.ol)(e=>{const t=new Map;if(e===void 0)return null;for(const n of e){const s=bl[n.type];s!==void 0&&t.set(n.identifier,s)}return{properties:t}},this.annotationProperties)),this.fallbackShaderControls=new A.B0(Bo(br(Uf))),this.shaderError=ar(),this.color=new q(w.eR.fromValues(1,1,0)),this.relationshipStates=this.registerDisposer(new lE),this.ignoreNullSegmentFilter=new rt(!0),this.disablePicking=new A.B0(!1),this.displayUnfiltered=(0,A.ol)((e,t)=>{for(const n of e.values())if(n.showMatches.value){if(!t)return!1;const s=n.segmentationState.value;if(s!=null&&s.segmentationGroupState.value.visibleSegments.size>0)return!1}return!0},this.relationshipStates,this.ignoreNullSegmentFilter),this.hoverState=new aE(void 0)}}class Uo extends D.O8{constructor(e){super();const{transform:t,localPosition:n,source:s,role:r=si.ANNOTATION}=e;this.transform=t,this.localPosition=n,this.source=this.registerDisposer(s),this.role=r,this.displayState=e.displayState,this.chunkTransform=this.registerDisposer((0,A.ol)(o=>go(()=>ao(rr(o))),this.transform)),this.dataSource=e.dataSource,this.subsourceId=e.subsourceId,this.subsourceIndex=e.subsourceIndex,this.subsubsourceId=e.subsubsourceId}get sourceIndex(){const{dataSource:e}=this;return e.layer.dataSources.indexOf(e)}}var Gf=G(9459);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const $o=!1,cE=!1,dE=w.pB.create();function uE(i,e){let t=0,n=Math.abs(i.detTransform);const{transform:s,size:r}=i;for(let o=0;o<3;++o){let a=0;for(let c=0;c<3;++c)a+=e[c*4+2]*s[4*o+c];const l=r[o];t+=Math.abs(a)*l,n*=l}return n/t}function zf(i,e,t){const{curPositionInChunks:n,fixedPositionWithinChunk:s}=i,{nonDisplayLowerClipBound:r,nonDisplayUpperClipBound:o}=i,{rank:a,chunkDataSize:l}=i.source.spec;if(!as(n,e,t,i.layerRank,i.fixedLayerToChunkTransform))return!1;for(let c=0;c<a;++c){const d=n[c];if(d<r[c]||d>=o[c])return $o&&console.log("excluding source",i,`because of chunkDim=${c}, sum=${d}`,r,o,i.fixedLayerToChunkTransform),!1;const u=l[c],h=n[c]=Math.floor(d/u);s[c]=d-h*u}return!0}function hE(i,e){const t=e.length;let n=0;if($o&&console.log(e),t>1){let s=0;for(let r=0;r<t;++r){const o=e[r],{chunkLayout:a}=o,l=uE(a,i);$o&&console.log(`chunksize = ${a.size}, sliceArea = ${l}`),l>s&&(s=l,n=r)}}return n}const xs=new Gf.i(w.eR.create(),w.pB.create(),0);class pE extends ep{constructor(){super(...arguments),this.viewportNormalInGlobalCoordinates=w.eR.create(),this.viewportNormalInCanonicalCoordinates=w.eR.create(),this.centerDataPosition=w.eR.create(),this.pixelSize=0}}function fE(i,e){if(i.displayDimensionRenderInfo!==e.displayDimensionRenderInfo||i.pixelSize!==e.pixelSize)return!0;const{viewMatrix:t}=i,{viewMatrix:n}=e;for(let s=0;s<12;++s)if(t[s]!==n[s])return!0;return!1}class gE extends un{constructor(e){super(),this.projectionParameters=e,this.visibleLayers=new Map,this.visibleSourcesStale=!0,this.registerDisposer(e.changed.add((t,n)=>{fE(t,n)&&this.invalidateVisibleSources(),this.invalidateVisibleChunks()}))}invalidateVisibleSources(){this.visibleSourcesStale=!0}invalidateVisibleChunks(){}updateVisibleSources(){if(!this.visibleSourcesStale)return;this.visibleSourcesStale=!1;const e=this.projectionParameters.value.displayDimensionRenderInfo,{visibleLayers:t}=this;for(const[n,s]of t){const{allSources:r,visibleSources:o}=s;if(o.length=0,r.length===0||!BC(s,e))continue;const a=hE(this.projectionParameters.value.viewMatrix,r.map(c=>c[0])),l=r[a];for(const c of n.filterVisibleSources(this,l))o.push(c);o.reverse(),$o&&console.log("visible sources chosen",o)}}}const Wf=18;function Go(i){let{rank:e,upperVoxelBound:t,maxVoxelsPerChunkLog2:n=Wf,chunkToViewTransform:s,displayRank:r,minBlockSize:o,maxBlockSize:a}=i;const{lowerVoxelBound:l=new Uint32Array(e)}=i,c=new Float32Array(e);for(let f=0;f<e;++f){let m=0;for(let g=0;g<r;++g){const v=s[f*r+g];m+=v*v}c[f]=Math.sqrt(m)}const d=new Uint32Array(e);o!==void 0?d.set(o):d.fill(1);const u=new Array(e);for(let f=0;f<e;++f){let m=Number.POSITIVE_INFINITY;c[f]===0?m=d[f]:(t!==void 0&&(m=2**Math.floor(Math.log2(t[f]-l[f]))),a!==void 0&&(m=Math.min(m,a[f]))),u[f]=m}function h(){let f=1/0,m=-1;for(let g=0;g<e;++g){if(d[g]>=u[g])continue;const v=d[g]*c[g];v<f&&(f=v,m=g)}return m}n-=Math.log2(Al(d));for(let f=0;f<n;++f){const m=h();if(m===-1)break;d[m]*=2}return d}function mE(i){const e=[],{displayRank:t,chunkToViewTransform:n,rank:s}=i;if(t>3)throw new Error("Unsupported view transform");if(t<3)return[Go(i)];for(let r=0;r<3;++r){const o=(r+2)%3,a=new Float32Array(n);for(let l=0;l<s;++l)a[l*t+o]=0;e[r]=Go({...i,chunkToViewTransform:a})}return e}var Vi=(i=>(i[i.ISOTROPIC=0]="ISOTROPIC",i[i.FLAT=1]="FLAT",i))(Vi||{});function x_(i,e,t){return t===void 0?e:matrix.multiply(new Float32Array((i+1)*(i+1)),i+1,e,i+1,t,i+1,i+1,i+1,i+1)}function vE(i){if(i.chunkDataSizes!==void 0)return i.chunkDataSizes;const{chunkLayoutPreference:e=0}=i;switch(e){case 0:return[Go(i)];case 1:return mE(i)}}function zo(i){const{rank:e,chunkDataSize:t,upperVoxelBound:n}=i,{lowerVoxelBound:s=new Float32Array(e)}=i,r=new Float32Array(e),o=new Float32Array(e);for(let a=0;a<e;++a)r[a]=Math.floor(s[a]/t[a]),o[a]=Math.floor((n[a]-1)/t[a]+1);return{rank:e,chunkDataSize:t,lowerChunkBound:r,upperChunkBound:o,lowerVoxelBound:s,upperVoxelBound:n}}function*yE(i,e,t){const n=i.projectionParameters.value.pixelSize*1.1,s=t[0].effectiveVoxelSize,r=e.renderScaleTarget.value,o=d=>{const u=n*r;for(let h=0;h<3;++h){const f=d[h];if(f>u&&f>1.01*s[h])return!0}return!1},a=(d,u)=>{const h=n*r;for(let f=0;f<3;++f){const m=d[f],g=u[f];if(Math.abs(h-m)<Math.abs(h-g)&&m<1.01*g)return!0}return!1};let l=t.length-1,c;for(;;){const d=t[l];if(c!==void 0&&!a(d.effectiveVoxelSize,c)||(yield d,l===0||!o(d.effectiveVoxelSize)))break;c=d.effectiveVoxelSize,--l}}const SE="SliceView",bE="sliceview/RenderLayer",wE="SliceView.addVisibleLayer",CE="SliceView.removeVisibleLayer",xE="ChunkManager.requestChunk",bc=new Float32Array(3),wc=new Float32Array(3),Hf=w.pB.create(),Jf=new Float32Array(24);function jf(i,e,t,n){const s=bc,r=wc,{lowerChunkDisplayBound:o,upperChunkDisplayBound:a}=e;for(let u=0;u<3;++u)s[u]=Math.max(s[u],o[u]),r[u]=Math.min(r[u],a[u]);const{curPositionInChunks:l,chunkDisplayDimensionIndices:c}=e;function d(){if(!n(s[0],s[1],s[2],r[0],r[1],r[2],i))return;let u=0,h=Math.max(0,r[0]-s[0]),f=h;for(let y=1;y<3;++y){const S=Math.max(0,r[y]-s[y]);f*=S,S>h&&(h=S,u=y)}if(f===0)return;if(f===1){l[c[0]]=s[0],l[c[1]]=s[1],l[c[2]]=s[2],t(s,i);return}const m=s[u],g=r[u],v=Math.floor(.5*(m+g));r[u]=v,d(),r[u]=g,s[u]=v,d(),s[u]=m}d()}function Yf(i,e,t,n){if(!zf(t,i.globalPosition,e))return;const{size:s}=t.chunkLayout,r=w.pB.multiply(Hf,i.viewProjectionMat,t.chunkLayout.transform);for(let c=0;c<3;++c){const d=s[c];for(let u=0;u<4;++u)r[4*c+u]*=d}const o=Jf;(0,w._S)(o,r);const a=bc,l=wc;a.fill(Number.NEGATIVE_INFINITY),l.fill(Number.POSITIVE_INFINITY),jf(o,t,n,w.T_)}function EE(i,e,t,n,s){if(!zf(t,i.globalPosition,e))return;const{size:r}=n,o=w.pB.multiply(Hf,i.viewProjectionMat,n.transform);for(let h=0;h<3;++h){const f=r[h];for(let m=0;m<4;++m)o[4*h+m]*=f}const a=dE;w.pB.invert(a,o);const l=bc,c=wc,d=.001;for(let h=0;h<3;++h){const f=a[12+h]+d/r[h],m=Math.abs(a[h]),g=Math.abs(a[4+h]);l[h]=Math.floor(f-m-g),c[h]=Math.floor(f+m+g+1)}const u=Jf;for(let h=0;h<3;++h){const f=o[4*h],m=o[4*h+1],g=o[4*h+2];u[h]=f,u[4+h]=-f,u[8+h]=+m,u[12+h]=-m,u[16+h]=+g,u[20+h]=-g}{const f=o[12],m=o[4*3+1],g=o[4*3+2];u[3]=1+f,u[7]=1-f,u[11]=1+m,u[15]=1-m,u[19]=g,u[23]=-g}cE&&(console.log("clippingPlanes",u),console.log("modelViewProjection",o.join(",")),console.log(`lower=${l.join(",")}, upper=${c.join(",")}`)),jf(u,t,s,w.qp)}function Cc(i,e){const{finiteRank:t}=e;if(t===3)return e;xs.finiteRank=t,w.eR.copy(xs.size,e.size);const n=w.pB.copy(xs.transform,e.transform),s=w.pB.copy(xs.invTransform,e.invTransform);xs.detTransform=e.detTransform;const{invViewMatrix:r,width:o,height:a}=i,l=(0,w.sJ)(i.projectionMat);for(let c=t;c<3;++c){const d=r[12+c];let u=d,h=d;const f=Math.abs(r[c]*o);u-=f,h+=f;const m=Math.abs(r[c+4]*a);u-=m,h+=m;const g=Math.abs(r[c+8]*l);u-=g,h+=g;const v=Math.max(1,h-u);n[12+c]=u,n[5*c]=v}return w.pB.invert(s,n),xs}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const TE="annotation.MetadataChunkSource",DE="annotation.GeometryChunkSource",IE="annotation.SubsetGeometryChunkSource",RE="annotation.reference.add",kE="annotation.reference.delete",LE="annotation.commit",PE="annotation.commit",AE="annotation/SpatiallyIndexedRenderLayer",ME="annotation/PerspectiveRenderLayer:updateSources",NE="annotation/RenderLayer",OE="annotation/RenderLayer.updateSegmentation",VE=w.w0.create();function Qf(i,e,t,n,s,r){const{displayDimensionRenderInfo:o,viewMatrix:a,projectionMat:l,width:c,height:d}=i,{voxelPhysicalScales:u}=o,h=Math.abs(w.w0.determinant((0,w._A)(VE,a))),f=(0,w.xK)(u),m=(0,w.I1)(l)/h*f;if(n.length===0)return;const g=n[0];let v=Math.abs(g.chunkLayout.detTransform)*f;const{lowerClipDisplayBound:y,upperClipDisplayBound:S}=g;for(let T=0;T<3;++T)v*=S[T]-y[T];const x=Math.min(v,m),b=c*d,C=b/t**2/x;let k=0;for(let T=n.length-1;T>=0&&k<C;--T){const L=n[T],_=L.source.spec,{chunkLayout:R}=L,P=(0,w.xK)(R.size)*Math.abs(R.detTransform)*f,{limit:V,rank:$}=_,{nonDisplayLowerClipBound:Q,nonDisplayUpperClipBound:K}=L;let ee=1;for(let Ct=0;Ct<$;++Ct){const ln=K[Ct]-Q[Ct];Number.isFinite(ln)&&(ee/=ln)}const ce=V*ee/P;let fe=!0;const le=k+ce,ve=(1/le)**(1/3),Ie=Math.sqrt(b/(le*x)),mt=(C-k)*P/ee,Fe=Math.min(1,mt/_.limit);Yf(i,e,L,()=>{fe&&(s(L,T),fe=!1),r(L,T,Fe,ve,Ie)}),k=le}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Es=`vec3 colormapJet(float x) {
  vec3 result;
  result.r = x < 0.89 ? ((x - 0.35) / 0.31) : (1.0 - (x - 0.89) / 0.11 * 0.5);
  result.g = x < 0.64 ? ((x - 0.125) * 4.0) : (1.0 - (x - 0.64) / 0.27);
  result.b = x < 0.34 ? (0.5 + x * 0.5 / 0.11) : (1.0 - (x - 0.34) / 0.31);
  return clamp(result, 0.0, 1.0);
}
vec3 colormapCubehelix(float x) {
  float xclamp = clamp(x, 0.0, 1.0);
  float angle = 2.0 * 3.1415926 * (4.0 / 3.0 + xclamp);
  float amp = xclamp * (1.0 - xclamp) / 2.0;
  vec3 result;
  float cosangle = cos(angle);
  float sinangle = sin(angle);
  result.r = -0.14861 * cosangle + 1.78277 * sinangle;
  result.g = -0.29227 * cosangle + -0.90649 * sinangle;
  result.b = 1.97294 * cosangle;
  result = clamp(xclamp + amp * result, 0.0, 1.0);
  return result;
}
`;/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const _E=!1;function qf(i,e){return{defineShader(t,n){const s=`prop_${n}`,r=`a_${s}`;t.addAttribute(`${i}`,r),t.addVertexCode(`${i} ${s}() { return ${r}; }`),t.addInitializer(o=>{const a=o.attribute(r),{gl:l}=o;o.vertexShaderInputBinders[s]=a===-1?{enable(){},disable(){},bind(){}}:{enable(c){l.enableVertexAttribArray(a),l.vertexAttribDivisor(a,c)},disable(){l.vertexAttribDivisor(a,0),l.disableVertexAttribArray(a)},bind(c,d){e(l,a,c,d)}}})}}}function xc(i,e,t,n){return qf(i,(s,r,o,a)=>{s.vertexAttribPointer(r,e,t,n,o,a)})}function Ts(i,e,t){return qf(i,(n,s,r,o)=>{n.vertexAttribIPointer(s,e,t,r,o)})}const Kf={rgb:xc("highp vec3",3,WebGL2RenderingContext.UNSIGNED_BYTE,!0),rgba:xc("highp vec4",4,WebGL2RenderingContext.UNSIGNED_BYTE,!0),float32:xc("highp float",1,WebGL2RenderingContext.FLOAT,!1),uint32:Ts("highp uint",1,WebGL2RenderingContext.UNSIGNED_INT),int32:Ts("highp int",1,WebGL2RenderingContext.INT),uint16:Ts("highp uint",1,WebGL2RenderingContext.UNSIGNED_SHORT),int16:Ts("highp int",1,WebGL2RenderingContext.SHORT),uint8:Ts("highp uint",1,WebGL2RenderingContext.UNSIGNED_BYTE),int8:Ts("highp int",1,WebGL2RenderingContext.BYTE)};class BE extends D.O8{constructor(e,t,n,s){super(),this.gl=e,this.annotationType=t,this.rank=n,this.properties=s;const r=this.serializedGeometryBytesPerAnnotation=Bt[t].serializedBytes(n),{offsets:o,serializedBytes:a,propertyGroupBytes:l}=vh(n,r,s);this.serializedBytesPerAnnotation=a,this.propertyOffsets=o,this.propertyGroupBytes=l,this.geometryDataStride=l[0];const c=this.propertyGroupCumulativeBytes=new Array(l.length);c[0]=0;for(let d=1;d<l.length;++d)c[d]=c[d-1]+l[d-1]}defineProperties(e,t){const{properties:n,rank:s}=this;for(const l of t){const c=n[l];Kf[c.type].defineShader(e,c.identifier,s)}const{propertyOffsets:r}=this,{propertyGroupBytes:o,propertyGroupCumulativeBytes:a}=this;e.addInitializer(l=>{const c=t.map(u=>l.vertexShaderInputBinders[`prop_${n[u].identifier}`]),d=c.length;l.vertexShaderInputBinders.properties={enable(u){for(let h=0;h<d;++h)c[h].enable(u)},bind(u,h){for(let f=0;f<d;++f){const{group:m,offset:g}=r[t[f]];c[f].bind(o[m],h+g+a[m]*u)}},disable(){for(let u=0;u<d;++u)c[u].disable()}}})}}class Wo extends BE{constructor(e,t,n,s,r,o,a){super(e,t,n,s),this.shaderControlState=r,this.fallbackShaderParameters=o,this.shaderError=a,this.histogramShaders=new Map}getDependentShader(e,t){return Ii(this,this.gl,{memoizeKey:{t:"annotation",targetIsSliceView:this.targetIsSliceView,type:this.annotationType,subType:e,properties:this.properties,rank:this.rank},fallbackParameters:this.fallbackShaderParameters,parameters:this.shaderControlState.builderState,shaderError:this.shaderError,defineShader:(n,s)=>{const{rank:r,properties:o}=this,a=[],l=s.referencedProperties,c=s.parseResult.code;for(let u=0,h=o.length;u<h;++u){const f=o[u],m=`prop_${f.identifier}`;!l.includes(f.identifier)&&!c.match(new RegExp(`\\b${m}\\b`))||a.push(u)}this.defineProperties(n,a),n.addUniform("highp vec3","uColor"),n.addUniform("highp uint","uSelectedIndex"),n.addVarying("highp vec4","vColor"),n.addUniform("highp vec3","uSubspaceMatrix",r),n.addUniform("highp mat4","uModelViewProjection"),n.addUniform("highp float","uModelClipBounds",r*2),n.addUniform("highp uint","uPickID"),n.addVarying("highp uint","vPickID","flat"),n.addVertexCode(Es),n.addVertexCode(`
vec3 defaultColor() { return uColor; }
highp uint getPickBaseOffset() { return uint(gl_InstanceID) * ${this.pickIdsPerInstance}u; }
`),n.addFragmentCode(`
void emitAnnotation(vec4 color) {
  emit(color, vPickID);
}
`);const d=`
float getSubspaceClipCoefficient(float modelPoint[${this.rank}]) {
  float coefficient = 1.0;
  for (int i = 0; i < ${r}; ++i) {
    float d = abs(modelPoint[i] - uModelClipBounds[i]) * uModelClipBounds[${r} + i];
    coefficient *= max(0.0, 1.0 - d);
  }
  return coefficient;
}
`;n.addVertexCode(d),n.addFragmentCode(d),n.addVertexCode(`
vec3 projectModelVectorToSubspace(float modelPoint[${this.rank}]) {
  vec3 result = vec3(0.0, 0.0, 0.0);
  for (int i = 0; i < ${r}; ++i) {
    result += uSubspaceMatrix[i] * modelPoint[i];
  }
  return result;
}

float getMaxEndpointSubspaceClipCoefficient(float modelPointA[${this.rank}],  float modelPointB[${this.rank}]) {
  float coefficient = 1.0;
  for (int i = 0; i < ${r}; ++i) {
    float dA = abs(modelPointA[i] - uModelClipBounds[i]) * uModelClipBounds[${r} + i];
    float dB = abs(modelPointB[i] - uModelClipBounds[i]) * uModelClipBounds[${r} + i];
    coefficient *= max(0.0, 1.0 - min(dA, dB));
  }
  return coefficient;
}

float getMaxSubspaceClipCoefficient(float modelPointA[${this.rank}],  float modelPointB[${this.rank}]) {
  float coefficient = 1.0;
  for (int i = 0; i < ${r}; ++i) {
    float a = modelPointA[i];
    float b = modelPointB[i];
    float c = uModelClipBounds[i];
    float x = clamp(c, min(a, b), max(a, b));
    float d = abs(x - c) * uModelClipBounds[${r} + i];
    coefficient *= max(0.0, 1.0 - d);
  }
  return coefficient;
}

`),Cs(s,n),n.addVertexCode(`
const bool PROJECTION_VIEW = ${!this.targetIsSliceView};
bool ng_discardValue;
#define discard ng_discard()
void ng_discard() {
  ng_discardValue = true;
}
void setLineColor(vec4 startColor, vec4 endColor);
void setLineWidth(float width);

void setEndpointMarkerColor(vec4 startColor, vec4 endColor);
void setEndpointMarkerBorderColor(vec4 startColor, vec4 endColor);
void setEndpointMarkerSize(float startSize, float endSize);
void setEndpointMarkerBorderWidth(float startSize, float endSize);

void setPointMarkerColor(vec4 color);
void setPointMarkerColor(vec3 color) { setPointMarkerColor(vec4(color, 1.0)); }
void setPointMarkerBorderColor(vec4 color);
void setPointMarkerSize(float size);
void setPointMarkerBorderWidth(float size);
void setPointMarkerBorderColor(vec3 color) { setPointMarkerBorderColor(vec4(color, 1.0)); }

void setEllipsoidFillColor(vec4 color);

void setBoundingBoxBorderColor(vec4 color);
void setBoundingBoxBorderWidth(float size);
void setBoundingBoxFillColor(vec4 color);

void setEndpointMarkerColor(vec3 startColor, vec3 endColor) {
  setEndpointMarkerColor(vec4(startColor, 1.0), vec4(endColor, 1.0));
}
void setEndpointMarkerBorderColor(vec3 startColor, vec3 endColor) {
  setEndpointMarkerBorderColor(vec4(startColor, 1.0), vec4(endColor, 1.0));
}
void setEndpointMarkerColor(vec3 color) { setEndpointMarkerColor(color, color); }
void setEndpointMarkerColor(vec4 color) { setEndpointMarkerColor(color, color); }
void setEndpointMarkerBorderColor(vec3 color) { setEndpointMarkerBorderColor(color, color); }
void setEndpointMarkerBorderColor(vec4 color) { setEndpointMarkerBorderColor(color, color); }
void setEndpointMarkerSize(float size) { setEndpointMarkerSize(size, size); }
void setEndpointMarkerBorderWidth(float size) { setEndpointMarkerBorderWidth(size, size); }
void setLineColor(vec4 color) { setLineColor(color, color); }
void setLineColor(vec3 color) { setLineColor(vec4(color, 1.0)); }
void setLineColor(vec3 startColor, vec3 endColor) { setLineColor(vec4(startColor, 1.0), vec4(endColor, 1.0)); }
void setColor(vec4 color) {
  setPointMarkerColor(color);
  setLineColor(color);
  setEndpointMarkerColor(color);
  setBoundingBoxBorderColor(color);
  setEllipsoidFillColor(vec4(color.rgb, color.a * (PROJECTION_VIEW ? 1.0 : 0.5)));
}
void setEllipsoidFillColor(vec3 color) { setEllipsoidFillColor(vec4(color, 1.0)); }

void setBoundingBoxFillColor(vec3 color) { setBoundingBoxFillColor(vec4(color, 1.0)); }
void setBoundingBoxBorderColor(vec3 color) { setBoundingBoxBorderColor(vec4(color, 1.0)); }

void setColor(vec3 color) { setColor(vec4(color, 1.0)); }
void userMain();
`);for(const[u,h]of Ec)u!==this.annotationType&&h.defineShaderNoOpSetters(n);t(n),n.addVertexCode(`
#define main userMain
`+ls(s.parseResult.code)+`
#undef main
`)}})}setPartIndex(e,...t){let n=`
void setPartIndex(${t.map((s,r)=>`highp uint partIndex${r}`).join()}) {
  highp uint pickID = uPickID;
  highp uint pickBaseOffset = getPickBaseOffset();
${t.map((s,r)=>`highp uint pickOffset${r} = pickBaseOffset + partIndex${r};`).join(`
`)}
`;return t.length===0&&(n+=`
  highp uint pickOffset0 = pickBaseOffset;
`),n+=`
  vPickID = pickID + pickOffset0;
  highp uint selectedIndex = uSelectedIndex;
if (selectedIndex == pickBaseOffset${t.map((s,r)=>` || selectedIndex == pickOffset${r}`).join("")}) {
    vColor = vec4(mix(vColor.rgb, vec3(1.0, 1.0, 1.0), 0.75), vColor.a);
  }
}
`,e.addVertexCode(n),`setPartIndex(${t.join()})`}get invokeUserMain(){return`
ng_discardValue = false;
userMain();
if (ng_discardValue) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
`}getCrossSectionFadeFactor(){return this.targetIsSliceView?"(clamp(1.0 - 2.0 * abs(0.5 - gl_FragCoord.z), 0.0, 1.0))":"(1.0)"}enable(e,t,n){const{shader:s,parameters:r}=e(t.renderContext.emitter);if(s===null)return;s.bind();const{gl:o}=this,{renderContext:a}=t,{annotationLayer:l}=t;if(Oi(o,s,this.shaderControlState,r.parseResult.controls),o.uniform3fv(s.uniform("uSubspaceMatrix"),t.subspaceMatrix),o.uniform1fv(s.uniform("uModelClipBounds"),t.modelClipBounds),o.uniformMatrix4fv(s.uniform("uModelViewProjection"),!1,t.modelViewProjectionMatrix),a.emitPickID&&o.uniform1ui(s.uniform("uPickID"),t.basePickId),a.emitColor){const d=l.state.displayState.color.value;o.uniform3f(s.uniform("uColor"),d[0],d[1],d[2]),o.uniform1ui(s.uniform("uSelectedIndex"),t.selectedIndex)}const c=s.vertexShaderInputBinders.properties;c.enable(1),o.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,t.buffer.buffer),c.bind(t.count,t.bufferOffset),n(s),c.disable()}getHistogramShader(e){const{histogramShaders:t}=this;let n=t.get(e);if(n===void 0){const{gl:s}=this;n=s.memoize.get(JSON.stringify({t:"propertyHistogramGenerator",propertyType:e}),()=>{const r=new hn(s);return this.defineHistogramShader(r,e),r.build()}),t.set(e,n)}return n}defineHistogramShader(e,t){Kf[t].defineShader(e,"histogram",0),e.addOutputBuffer("vec4","out_histogram",0);const s="invlerpForHistogram",r=bl[t];e.addVertexCode(us(e,s,r,!1)),e.setVertexMain(`
float x = invlerpForHistogram(prop_histogram());
if (x < 0.0) x = 0.0;
else if (x > 1.0) x = 1.0;
else x = (1.0 + x * 253.0) / 255.0;
gl_Position = vec4(2.0 * (x * 255.0 + 0.5) / 256.0 - 1.0, 0.0, 0.0, 1.0);
gl_PointSize = 1.0;
`),e.setFragmentMain("out_histogram = vec4(1.0, 1.0, 1.0, 1.0);")}computeHistograms(e,t){const{histogramSpecifications:n}=this.shaderControlState,s=n.properties.value,r=s.length,{properties:o}=this,a=o.length,{propertyOffsets:l}=this,{propertyGroupBytes:c,propertyGroupCumulativeBytes:d}=this,{gl:u}=this;u.enable(WebGL2RenderingContext.BLEND),u.disable(WebGL2RenderingContext.SCISSOR_TEST),u.disable(WebGL2RenderingContext.DEPTH_TEST),u.blendFunc(WebGL2RenderingContext.ONE,WebGL2RenderingContext.ONE);const h=n.getFramebuffers(u),f=n.frameNumber;n.frameNumber=t,u.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,e.buffer.buffer);for(let m=0;m<r;++m){const g=s[m];for(let v=0;v<a;++v){const y=o[v];if(y.identifier!==g)continue;const S=y.type,x=bl[S],b=this.getHistogramShader(S);b.bind();const E=b.vertexShaderInputBinders.prop_histogram;E.enable(0);const{group:C,offset:k}=l[v];if(Pi(b,"invlerpForHistogram",x,n.bounds.value[m]),E.bind(c[C],e.bufferOffset+k+d[C]*e.count),h[m].bind(256,1),t!==f&&(u.clearColor(0,0,0,0),u.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT)),u.drawArrays(WebGL2RenderingContext.POINTS,0,e.count),_E){const T=new Float32Array(1024);u.readPixels(0,0,256,1,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.FLOAT,T);const L=new Float32Array(256);for(let _=0;_<256;++_)L[_]=T[_*4];console.log("histogram",L.join(" "))}E.disable();break}}u.disable(WebGL2RenderingContext.BLEND)}}const Ec=new Map;function Ho(i,e){Ec.set(i,e)}function wr(i){return Ec.get(i)}var Tc=G(4704),FE=Object.defineProperty,UE=Object.getOwnPropertyDescriptor,Dc=(i,e,t,n)=>{for(var s=n>1?void 0:n?UE(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&FE(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Xf=!1;class Wn{constructor(e){this.source=e,this.state=Be.SYSTEM_MEMORY}get gl(){return this.source.gl}copyToGPU(e){this.state=Be.GPU_MEMORY}freeGPUMemory(e){this.state=Be.SYSTEM_MEMORY}}function Zf(i){if(typeof i!="number"||i<0)throw new Error(`Expected non-negative number as limit, but received: ${JSON.stringify(i)}`);return i}class Jo{constructor({defaultItemLimit:e=Number.POSITIVE_INFINITY,defaultSizeLimit:t=Number.POSITIVE_INFINITY}={}){this.sizeLimit=new A.DN(t,Zf),this.itemLimit=new A.DN(e,Zf)}}let Ic=class extends un{constructor(i,e,t,n){super(),this.gl=e,this.frameNumberCounter=t,this.capacities=n,this.visibleChunksChanged=new j.IY,this.pendingChunkUpdates=null,this.pendingChunkUpdatesTail=null,this.chunkUpdateDeadline=null,this.chunkUpdateDelay=30,this.enablePrefetch=new rt(!0,!0);const s=r=>({itemLimit:this.registerDisposer(ut.makeFromExisting(i,r.itemLimit)).rpcId,sizeLimit:this.registerDisposer(ut.makeFromExisting(i,r.sizeLimit)).rpcId});this.initializeCounterpart(i,{gpuMemoryCapacity:s(n.gpuMemory),systemMemoryCapacity:s(n.systemMemory),downloadCapacity:s(n.download),computeCapacity:s(n.compute),enablePrefetch:this.registerDisposer(ut.makeFromExisting(i,this.enablePrefetch)).rpcId})}scheduleChunkUpdate(){const i=this.chunkUpdateDeadline;let e;i===null||Date.now()<i?e=0:e=this.chunkUpdateDelay,setTimeout(this.processPendingChunkUpdates.bind(this),e)}processPendingChunkUpdates(i=!1){let e=this.chunkUpdateDeadline;!i&&e===null&&(e=Date.now()+30);let t=!1,n=0;for(;;){if(!i&&Date.now()>e){this.chunkUpdateDeadline=null,setTimeout(()=>this.processPendingChunkUpdates(),this.chunkUpdateDelay);break}const s=this.pendingChunkUpdates;if(s==null)break;try{this.applyChunkUpdate(s)&&(t=!0)}finally{if(++n,(this.pendingChunkUpdates=s.nextUpdate)==null){this.pendingChunkUpdatesTail=null;break}}}return t&&this.visibleChunksChanged.dispatch(),n}handleFetch_(i,e){const{resolve:t,reject:n,cancellationToken:s}=e.promise;if(s.isCanceled){n(at.wS);return}const r=e.key,o=i.chunks.get(r);if(!o){n(new Error(`No chunk found at ${r} for source ${i.constructor.name}`));return}const a=o.data;if(!a){n(new Error(`At ${r} for source ${i.constructor.name}: chunk has no data`));return}t({value:a})}applyChunkUpdate(i){let e=!1;const{rpc:t}=this,n=t.get(i.source);if(n!==void 0){if(Xf&&console.log(`${Date.now()} Chunk.update processed: ${n.rpcId} ${i.id} ${i.state}`),i.promise!==void 0)this.handleFetch_(n,i);else if(i.id===void 0){for(const s of n.chunks.keys())n.deleteChunk(s);e=!0}else{const s=i.state;if(s===Be.EXPIRED)n.deleteChunk(i.id);else{let r;const o=i.id;i.new?(r=n.getChunk(i),n.addChunk(o,r)):r=n.chunks.get(o);const a=r.state;if(s!==a)switch(s){case Be.GPU_MEMORY:r.copyToGPU(this.gl),e=!0;break;case Be.SYSTEM_MEMORY:a===Be.GPU_MEMORY&&r.freeGPUMemory(this.gl);break;default:throw new Error(`INTERNAL ERROR: Invalid chunk state: ${Be[s]}`)}if(s<=Be.SYSTEM_MEMORY){const{chunkRequesters:l}=n;if(l!==void 0){const c=l.get(o);if(c!==void 0)for(const d of c)d(r)}}}}return e}}flushPendingChunkUpdates(){return this.processPendingChunkUpdates(!0)}async getStatistics(){const i=this.rpc,e=await i.promiseInvoke(kw,{queue:this.rpcId}),t=new Map;for(const[n,s]of e){const r=i.get(n);r!==void 0&&t.set(r,s)}return t}};Ic=Dc([Kt(Dw)],Ic);function eg(i,e){const t=i.get(e.source);Xf&&console.log(`${Date.now()} Chunk.update received: ${t.rpcId} ${e.id} ${e.state} with chunkDataSize ${e.chunkDataSize}`);const n=t.chunkManager.chunkQueueManager;if(t.immediateChunkUpdates){n.applyChunkUpdate(e)&&n.visibleChunksChanged.dispatch();return}const s=n.pendingChunkUpdatesTail;s==null?(n.pendingChunkUpdates=e,n.pendingChunkUpdatesTail=e,n.scheduleChunkUpdate()):(s.nextUpdate=e,n.pendingChunkUpdatesTail=e)}dt("Chunk.update",function(i){eg(this,i)}),ap("Chunk.retrieve",function(i,e){return new Promise((t,n)=>{i.promise={resolve:t,reject:n,cancellationToken:e},eg(this,i)})}),dt(Lw,function(i){const e=this.get(i.id);for(const t of e.prevStatisticsLayers)t.numVisibleChunksNeeded=0,t.numVisibleChunksAvailable=0,t.numPrefetchChunksNeeded=0,t.numPrefetchChunksAvailable=0;e.prevStatisticsLayers.length=0;for(const t of i.layers){const n=this.get(t.id);if(n===void 0)continue;const s=n.layerChunkProgressInfo;s.numVisibleChunksAvailable=t.numVisibleChunksAvailable,s.numVisibleChunksNeeded=t.numVisibleChunksNeeded,s.numPrefetchChunksAvailable=t.numPrefetchChunksAvailable,s.numPrefetchChunksNeeded=t.numPrefetchChunksNeeded,e.prevStatisticsLayers.push(s)}e.layerChunkStatisticsUpdated.dispatch()});let Rc=class extends un{constructor(i){super(),this.chunkQueueManager=i,this.memoize=new Tc.e,this.prevStatisticsLayers=[],this.layerChunkStatisticsUpdated=new j.IY,this.registerDisposer(i.addRef()),this.initializeCounterpart(i.rpc,{chunkQueueManager:i.rpcId})}get gl(){return this.chunkQueueManager.gl}getChunkSource(i,e){const t=i.encodeOptions(e);t.constructorId=St(i);const n=(0,p.JB)(t);return this.memoize.get(n,()=>{const s=new i(this,e);return s.initializeCounterpart(this.rpc,{}),s.key=t,s})}};Rc=Dc([Kt(Iw)],Rc);class tn extends un{constructor(e,t={}){super(),this.chunkManager=e,this.chunks=new Map,this.immediateChunkUpdates=!1}initializeCounterpart(e,t){t.chunkManager=this.chunkManager.rpcId,super.initializeCounterpart(e,t)}get gl(){return this.chunkManager.chunkQueueManager.gl}deleteChunk(e){const t=this.chunks.get(e);t.state===Be.GPU_MEMORY&&t.freeGPUMemory(this.gl),this.chunks.delete(e)}addChunk(e,t){this.chunks.set(e,t)}getChunk(e){throw new Error("Not implemented.")}invalidateCache(){this.rpc.invoke(Rw,{id:this.rpcId})}static encodeOptions(e){return{}}}function Ke(i,e){let t=class extends i{constructor(...n){super(...n);const s=n[1];this.parameters=s.parameters}initializeCounterpart(n,s){s.parameters=this.parameters,super.initializeCounterpart(n,s)}static encodeOptions(n){return Object.assign({parameters:n.parameters},i.encodeOptions(n))}};return t=Dc([Kt(e.RPC_ID)],t),t}class Cr extends un{constructor(e){super(),this.layerChunkProgressInfo=e}}var Tt=G(4242);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const tg=["visibleSegments","segmentEquivalences","temporaryVisibleSegments","temporarySegmentEquivalences","useTemporaryVisibleSegments","useTemporarySegmentEquivalences"];function $E(i,e,t){i.registerDisposer(e.visibleSegments.changed.add(t)),i.registerDisposer(e.segmentEquivalences.changed.add(t))}function GE(i,e,t){i.registerDisposer(e.temporaryVisibleSegments.changed.add(t)),i.registerDisposer(e.temporarySegmentEquivalences.changed.add(t)),i.registerDisposer(e.useTemporaryVisibleSegments.changed.add(t)),i.registerDisposer(e.useTemporarySegmentEquivalences.changed.add(t))}function vn(i){return`${i.low},${i.high}`}function zE(i){return!!(i.high>>>31)}function ng(i){return i.useTemporaryVisibleSegments.value?i.temporaryVisibleSegments:i.visibleSegments}function WE(i){return i.useTemporarySegmentEquivalences.value?i.temporarySegmentEquivalences:i.segmentEquivalences}function Ds(i,e){const t=ng(i),n=WE(i),s=n.disjointSets.visibleSegmentEquivalencePolicy.value;for(const r of t.unsafeKeys())if(s&Tt.y6.NONREPRESENTATIVE_EXCLUDED){const o=n.get(r);e(r,o)}else{if(!n.disjointSets.isMinElement(r))continue;for(const o of n.setElements(r))s&Tt.y6.REPRESENTATIVE_EXCLUDED&&s&Tt.y6.MAX_REPRESENTATIVE&&zE(o)||e(o,r)}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ft=40,xr=.5,Is=-4;function jo(i,e=Is){return(Math.log2(i)-e)/xr}function HE(i,e=Is){return 2**(i*xr+e)}function _i(i,e=2**Is,t){t===void 0&&(t=2**Math.round(xr*ft+Is)-1);const n=(0,p.JY)(e,t);return new A.DN(i,n)}class Rs{constructor(e=Is){this.visibility=new nr,this.changed=new j.IY,this.frameNumber=-1,this.spatialScales=new Map,this.numHistogramRows=1,this.value=new Uint32Array(ft*this.numHistogramRows*2),this.fakeChunkCount=0,this.logScaleOrigin=e}begin(e){e!==this.frameNumber&&(this.value.fill(0),this.frameNumber=e,this.spatialScales.clear(),this.fakeChunkCount=0,this.changed.dispatch())}add(e,t,n,s,r=!1){let{spatialScales:o,numHistogramRows:a,value:l}=this,c=o.get(e);if(c===void 0&&(c=o.size,o.set(e,c)),c>=a){this.numHistogramRows=a*=2;const u=new Uint32Array(a*ft*2);u.set(l),this.value=l=u}const d=c*ft*2+Math.min(Math.max(0,Math.round(jo(t,this.logScaleOrigin))),ft-1);l[d]+=n,l[d+ft]+=s,r&&(this.fakeChunkCount=this.fakeChunkCount+s)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class kc extends dp{constructor(e,t,n){super(),this.chunkManager=e,this.multiscaleSource=t,this.rpcId=null,this.rpcTransfer={},this.visibleSources=new Map,this.visibleSourcesList_=[];const{renderScaleTarget:s=_i(1)}=n;this.renderScaleTarget=s,this.renderScaleHistogram=n.renderScaleHistogram,this.transform=n.transform,this.localPosition=n.localPosition,this.rpcTransfer=n.rpcTransfer||{},this.dataHistogramSpecifications=this.registerDisposer(n.dataHistogramSpecifications??new Rp((0,A.XZ)([]),(0,A.XZ)([]),(0,A.XZ)([]))),this.registerDisposer(this.dataHistogramSpecifications.visibility.changed.add(this.redrawNeeded.dispatch))}getDataHistogramCount(){return this.dataHistogramSpecifications.visibleHistograms}getSources(e){return this.multiscaleSource.getSources(e)}addSource(e,t){const{visibleSources:n}=this,s=n.get(e);s!==void 0?(++s.refCount,s.chunkTransform=t):(n.set(e,{source:e,refCount:1,chunkTransform:t}),this.visibleSourcesList_.length=0)}removeSource(e){const{visibleSources:t}=this,n=t.get(e);n.refCount!==1?--n.refCount:(t.delete(e),this.visibleSourcesList_.length=0)}get visibleSourcesList(){const{visibleSources:e,visibleSourcesList_:t}=this;if(t.length===0&&e.size!==0){for(const n of e.values())t.push(n);t.sort((n,s)=>Math.abs(n.chunkTransform.chunkToLayerTransformDet)-Math.abs(s.chunkTransform.chunkToLayerTransformDet))}return t}initializeCounterpart(){const e=this.registerDisposer(new Cr(this.layerChunkProgressInfo)),t=this.chunkManager.rpc;e.RPC_TYPE_ID=this.RPC_TYPE_ID,e.initializeCounterpart(t,{localPosition:this.registerDisposer(ut.makeFromExisting(t,this.localPosition)).rpcId,renderScaleTarget:this.registerDisposer(ut.makeFromExisting(t,this.renderScaleTarget)).rpcId,...this.rpcTransfer}),this.rpcId=e.rpcId}get gl(){return this.chunkManager.chunkQueueManager.gl}setGLBlendMode(e,t){t>0?(e.enable(WebGL2RenderingContext.BLEND),e.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA)):e.disable(WebGL2RenderingContext.BLEND)}filterVisibleSources(e,t){return yE(e,this,t)}}kc.prototype.RPC_TYPE_ID=bE;class Bi extends up{draw(e,t){}isReady(e,t){return!0}}var JE=Object.defineProperty,jE=Object.getOwnPropertyDescriptor,YE=(i,e,t,n)=>{for(var s=n>1?void 0:n?jE(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&JE(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class QE extends gE{}const qE=ir(QE);function KE(i){return{source:i.source.addCounterpartRef(),effectiveVoxelSize:i.effectiveVoxelSize,layerRank:i.layerRank,nonDisplayLowerClipBound:i.nonDisplayLowerClipBound,nonDisplayUpperClipBound:i.nonDisplayUpperClipBound,lowerClipBound:i.lowerClipBound,upperClipBound:i.upperClipBound,lowerClipDisplayBound:i.lowerClipDisplayBound,upperClipDisplayBound:i.upperClipDisplayBound,chunkDisplayDimensionIndices:i.chunkDisplayDimensionIndices,lowerChunkDisplayBound:i.lowerChunkDisplayBound,upperChunkDisplayBound:i.upperChunkDisplayBound,fixedLayerToChunkTransform:i.fixedLayerToChunkTransform,combinedGlobalLocalToChunkTransform:i.combinedGlobalLocalToChunkTransform,chunkLayout:i.chunkLayout.toObject()}}function Yo(i){return i.map(e=>e.map(KE))}function Lc(i,e){for(const t of e)for(const{source:n}of t)i.removeSource(n),n.dispose()}let Qo=class extends qE{constructor(i,e,t,n){super(new hp({parametersConstructor:pE,navigationState:t,update:(o,a)=>{const{invViewMatrix:l,centerDataPosition:c}=o;a.toMat4(l);const{canonicalVoxelFactors:d,voxelPhysicalScales:u}=o.displayDimensionRenderInfo;for(let b=0;b<3;++b)c[b]=l[12+b];const{logicalWidth:h,logicalHeight:f,projectionMat:m,viewportNormalInGlobalCoordinates:g,viewportNormalInCanonicalCoordinates:v}=o,{relativeDepthRange:y}=a;w.pB.ortho(m,-h/2,h/2,f/2,-f/2,-y,y),Kh(o,m),tp(o);const{viewMatrix:S}=o;for(let b=0;b<3;++b){const E=g[b]=S[b*4+2];v[b]=E/d[b]}w.eR.normalize(g,g),w.eR.normalize(v,v);let x=0;for(let b=0;b<3;++b){const E=u[b],C=l[b];x+=(E*C)**2}x=Math.sqrt(x),o.pixelSize=x}})),this.chunkManager=i,this.layerManager=e,this.navigationState=t,this.wireFrame=n,this.gl=this.chunkManager.gl,this.viewChanged=new j.IY,this.renderingStale=!0,this.visibleChunksStale=!0,this.visibleLayerList=new Array,this.offscreenFramebuffer=this.registerDisposer(new $n(this.gl,{colorBuffers:cs(this.gl,1),depthBuffer:new dC(this.gl)})),this.histogramInputTextures=[],this.offscreenFramebuffersWithHistograms=[this.offscreenFramebuffer],this.histogramGenerator=tc.get(this.gl),this.updateVisibleLayers=this.registerCancellable((0,xe.A)(()=>{this.updateVisibleLayersNow()},0)),this.registerDisposer(t),this.registerDisposer(this.projectionParameters),this.registerDisposer(this.projectionParameters.changed.add((o,a)=>{o.displayDimensionRenderInfo!==a.displayDimensionRenderInfo&&this.updateVisibleLayers()}));const s=this.chunkManager.rpc,r=this.sharedProjectionParameters=this.registerDisposer(new fo(s,this.projectionParameters));this.initializeCounterpart(s,{chunkManager:i.rpcId,projectionParameters:r.rpcId}),this.registerDisposer(e.layersChanged.add(()=>{this.updateVisibleLayers()})),this.wireFrame.changed.add(this.viewChanged.dispatch),this.viewChanged.add(()=>{this.renderingStale=!0}),this.registerDisposer(i.chunkQueueManager.visibleChunksChanged.add(this.viewChanged.dispatch)),this.updateVisibleLayers()}get displayDimensionRenderInfo(){return this.navigationState.displayDimensionRenderInfo}computeHistograms(i,e){this.histogramGenerator.compute(i,this.offscreenFramebuffer.depthBuffer.texture,this.histogramInputTextures,e,this.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber)}flushBackendProjectionParameters(){this.sharedProjectionParameters.flush()}forEachVisibleChunk(i,e,t){EE(this.projectionParameters.value,i.renderLayer.localPosition.value,i,e,()=>{t(i.curPositionInChunks.join())})}isReady(){if(!this.navigationState.valid)return!1;this.updateVisibleLayers.flush(),this.updateVisibleSources();let i=0,e=0;for(const{visibleSources:t}of this.visibleLayers.values())for(const n of t){const s=Cc(this.projectionParameters.value,n.chunkLayout),{source:r}=n,{chunks:o}=r;this.forEachVisibleChunk(n,s,a=>{const l=o.get(a);++e,l&&l.state===Be.GPU_MEMORY&&++i})}return i===e}invalidateVisibleSources(){super.invalidateVisibleSources(),this.viewChanged.dispatch()}bindVisibleRenderLayer(i,e){e.push(i.localPosition.changed.add(()=>this.invalidateVisibleChunks())),e.push(i.redrawNeeded.add(this.viewChanged.dispatch)),e.push(i.transform.changed.add(this.updateVisibleLayers)),e.push(i.renderScaleTarget.changed.add(()=>this.invalidateVisibleSources()));const{renderScaleHistogram:t}=i;t!==void 0&&e.push(t.visibility.add(this.visibility)),e.push(i.dataHistogramSpecifications.producerVisibility.add(this.visibility))}updateVisibleLayersNow(){if(this.wasDisposed||!this.navigationState.valid)return!1;const i=Date.now(),{visibleLayers:e,visibleLayerList:t}=this,{displayDimensionRenderInfo:n}=this.projectionParameters.value,s=this.rpc,r={id:this.rpcId};let o=!1;t.length=0;for(const a of this.layerManager.readyRenderLayers())if(a instanceof kc){t.push(a);let l=e.get(a);if(l===void 0){const c=[],d=new Di;l={messages:d,allSources:this.getTransformedSources(a,d),transformGeneration:a.transform.changed.count,visibleSources:[],disposers:c,lastSeenGeneration:i,displayDimensionRenderInfo:n},c.push(a.messages.addChild(l.messages)),e.set(a.addRef(),l),this.bindVisibleRenderLayer(a,c)}else{l.lastSeenGeneration=i;const c=a.transform.changed.count;if(l.transformGeneration===c&&l.displayDimensionRenderInfo===n)continue;const d=l.allSources;l.allSources=this.getTransformedSources(a,l.messages),Lc(a,d),l.visibleSources.length=0,l.displayDimensionRenderInfo=n,l.transformGeneration=c}r.layerId=a.rpcId,r.sources=Yo(l.allSources),r.displayDimensionRenderInfo=n,this.flushBackendProjectionParameters(),s.invoke(wE,r),o=!0}for(const[a,l]of e)l.lastSeenGeneration!==i&&(r.layerId=a.rpcId,s.invoke(CE,r),e.delete(a),Lc(a,l.allSources),(0,D.$F)(l.disposers),a.dispose(),o=!0);return o&&(this.visibleSourcesStale=!0),this.viewChanged.dispatch(),o}invalidateVisibleChunks(){super.invalidateVisibleChunks(),this.viewChanged.dispatch()}get valid(){return this.navigationState.valid}getOffscreenFramebufferWithHistograms(i){const{offscreenFramebuffersWithHistograms:e}=this;let t=e[i];if(t===void 0){const{gl:n,histogramInputTextures:s,offscreenFramebuffer:r}=this;s.length<i&&s.push(...cs(n,i-s.length,WebGL2RenderingContext.R8,WebGL2RenderingContext.RED));const o=[r.colorBuffers[0].addRef()];for(let a=0;a<i;++a)o.push(s[a].addRef());t=this.registerDisposer(new $n(n,{colorBuffers:o,depthBuffer:r.depthBuffer.addRef()})),e[i]=t}return t}updateRendering(){const i=this.projectionParameters.value,{width:e,height:t}=i;if(!this.renderingStale||!this.valid||e===0||t===0)return;this.renderingStale=!1,this.updateVisibleLayers.flush(),this.updateVisibleSources();const{gl:n,offscreenFramebuffer:s}=this;s.bind(e,t),n.disable(n.SCISSOR_TEST),n.clearColor(0,0,0,0),n.colorMask(!0,!0,!0,!0),n.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT);let r=0;const o=this.wireFrame.value,a={sliceView:this,projectionParameters:i,wireFrame:o};for(const l of this.visibleLayerList){const c=o?0:l.getDataHistogramCount();this.getOffscreenFramebufferWithHistograms(c).bind(e,t);for(let u=0;u<c;++u)n.clearBufferfv(WebGL2RenderingContext.COLOR,1+u,w.yb);n.enable(WebGL2RenderingContext.DEPTH_TEST),n.depthFunc(WebGL2RenderingContext.LESS),n.clearDepth(1),n.clear(WebGL2RenderingContext.DEPTH_BUFFER_BIT),l.setGLBlendMode(n,r),l.draw(a),++r}n.disable(WebGL2RenderingContext.BLEND),n.disable(WebGL2RenderingContext.DEPTH_TEST),s.unbind()}disposed(){for(const[i,e]of this.visibleLayers)Lc(i,e.allSources),(0,D.$F)(e.disposers),i.dispose();this.visibleLayers.clear(),this.visibleLayerList.length=0}getTransformedSources(i,e){const t=Ko(this.projectionParameters.value.displayDimensionRenderInfo,i.transform.value,n=>i.getSources(n),e,i);for(const n of t)for(const s of n)i.addSource(s.source,s.chunkTransform);return t}};Qo=YE([Kt(SE)],Qo);class Er extends tn{constructor(e,t){super(e,t),this.spec=t.spec}static encodeSpec(e){return{chunkDataSize:Array.from(e.chunkDataSize),lowerVoxelBound:Array.from(e.lowerVoxelBound),upperVoxelBound:Array.from(e.upperVoxelBound)}}static encodeOptions(e){const t=tn.encodeOptions(e);return t.spec=Er.encodeSpec(e.spec),t}initializeCounterpart(e,t){t.spec=this.spec,super.initializeCounterpart(e,t)}async fetchChunk(e,t,n=at.fx){const s=e.join(),r=this.chunks.get(s);if(r!==void 0&&r.state<=Be.SYSTEM_MEMORY)return t(r);this.addRef();let{chunkRequesters:o}=this;o===void 0&&(o=this.chunkRequesters=new Map);let a,l=o.get(s);l===void 0&&(l=[],o.set(s,l));const c=new Promise(d=>{a=u=>d(t(u)),l.push(a)});try{return await this.rpc.promiseInvoke(xE,{source:this.rpcId,chunkGridPosition:e},n),await c}finally{const d=l.indexOf(a);l.splice(d,1),l.length===0&&o.delete(s),o.size===0&&(this.chunkRequesters=void 0),this.dispose()}}}class ig extends Wn{constructor(e,t){super(e),this.chunkGridPosition=t.chunkGridPosition,this.state=Be.SYSTEM_MEMORY}}class qo extends D.O8{constructor(e,t){super(),this.gl=e,this.copyVertexPositionsBuffer=lr(this.gl),this.textureCoordinateAdjustment=new Float32Array(4);const n=new hn(e);n.addVarying("vec2","vTexCoord"),n.addUniform("sampler2D","uSampler"),n.addInitializer(s=>{e.uniform1i(s.uniform("uSampler"),0)}),n.addUniform("vec4","uColorFactor"),n.addUniform("vec4","uBackgroundColor"),n.addUniform("mat4","uProjectionMatrix"),n.addUniform("vec4","uTextureCoordinateAdjustment"),n.require(t),n.setFragmentMain(`
vec4 sampledColor = texture(uSampler, vTexCoord);
if (sampledColor.a == 0.0) {
  sampledColor = uBackgroundColor;
}
emit(sampledColor * uColorFactor, 0u);
`),n.addAttribute("vec4","aVertexPosition"),n.setVertexMain(`
vTexCoord = uTextureCoordinateAdjustment.xy + 0.5 * (aVertexPosition.xy + 1.0) * uTextureCoordinateAdjustment.zw;
gl_Position = uProjectionMatrix * aVertexPosition;
`),this.shader=this.registerDisposer(n.build())}draw(e,t,n,s,r,o,a,l){const{gl:c,shader:d,textureCoordinateAdjustment:u}=this;u[0]=r,u[1]=o,u[2]=a-r,u[3]=l-o,d.bind(),c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,e),c.disable(WebGL2RenderingContext.BLEND),c.uniformMatrix4fv(d.uniform("uProjectionMatrix"),!1,t),c.uniform4fv(d.uniform("uColorFactor"),n),c.uniform4fv(d.uniform("uBackgroundColor"),s),c.uniform4fv(d.uniform("uTextureCoordinateAdjustment"),u);const h=d.attribute("aVertexPosition");this.copyVertexPositionsBuffer.bindToVertexAttrib(h,2),c.drawArrays(c.TRIANGLE_FAN,0,4),c.disableVertexAttribArray(h),c.bindTexture(c.TEXTURE_2D,null)}static get(e,t){return e.memoize.get(`sliceview/SliceViewRenderHelper:${St(t)}`,()=>new qo(e,t))}}class XE{constructor(e){this.chunkManager=e}}function Ko(i,e,t,n,s){n.clearMessages();const r=y=>(n.addMessage({severity:xn.error,message:y}),[]);if(e.error!==void 0)return r(e.error);const o=e.rank,a=e.unpaddedRank,{displayDimensionIndices:l,displayRank:c,canonicalVoxelFactors:d}=i,u=Jh(e,l),{displayToLayerDimensionIndices:h}=u,f=new Float32Array(c*a),{modelToRenderLayerTransform:m}=e;for(let y=0;y<c;++y){const S=h[y];if(S===-1)continue;const x=d[y];for(let b=0;b<a;++b)f[c*b+y]=m[(o+1)*b+S]*x}const g=t({displayRank:c,multiscaleToViewTransform:f,modelChannelDimensionIndices:e.channelToRenderLayerDimensions}),{voxelPhysicalScales:v}=i;try{const y=S=>{const{chunkSource:x}=S,{spec:b}=x,{lowerClipBound:E=b.lowerVoxelBound,upperClipBound:C=b.upperVoxelBound}=S,k=ao(e,S.chunkToMultiscaleTransform),{chunkDataSize:T}=b,{channelToChunkDimensionIndices:L}=k,_=new Float32Array(a),R=new Float32Array(a);_.set(E),R.set(C);const P=L.length,{channelSpaceShape:V}=e;for(let Ue=0;Ue<P;++Ue){const et=L[Ue];if(et===-1)continue;const Lt=V[Ue];if(T[et]!==Lt)throw new Error("Channel dimension "+e.layerDimensionNames[e.channelToRenderLayerDimensions[Ue]]+` has extent ${Lt} but corresponding chunk dimension has extent ${T[et]}`);_[et]=Number.NEGATIVE_INFINITY,R[et]=Number.POSITIVE_INFINITY}const $=jh(k,u),Q=w.eR.create(),K=w.eR.create(),ee=w.eR.create(),ce=w.eR.create(),fe=w.eR.create(),{numChunkDisplayDims:le,chunkDisplayDimensionIndices:ve}=$,{combinedGlobalLocalToChunkTransform:Ie,layerRank:mt,combinedGlobalLocalRank:Fe}=k,Ct=new Float32Array(Ie);for(let Ue=0;Ue<le;++Ue){const et=ve[Ue];for(let Lt=0;Lt<=Fe;++Lt)Ct[et+Lt*mt]=0;et<a?(fe[Ue]=b.chunkDataSize[et],Q[Ue]=b.lowerChunkBound[et],K[Ue]=b.upperChunkBound[et],ee[Ue]=E[et],ce[Ue]=C[et],_[et]=Number.NEGATIVE_INFINITY,R[et]=Number.POSITIVE_INFINITY):(fe[Ue]=1,Q[Ue]=0,K[Ue]=1,ee[Ue]=0,ce[Ue]=1)}fe.fill(1,le),Q.fill(0,le),K.fill(1,le),ee.fill(0,le),ce.fill(1,le);const ln=new Gf.i(fe,$.displaySubspaceModelMatrix,le),kt=ln.localSpatialVectorToGlobal(w.eR.create(),w.Oi);for(let Ue=0;Ue<c;++Ue)kt[Ue]=Math.abs(kt[Ue]*v[Ue]);return kt.fill(1,c),{layerRank:mt,lowerClipBound:E,upperClipBound:C,nonDisplayLowerClipBound:_,nonDisplayUpperClipBound:R,renderLayer:s,source:x,lowerChunkDisplayBound:Q,upperChunkDisplayBound:K,lowerClipDisplayBound:ee,upperClipDisplayBound:ce,effectiveVoxelSize:kt,chunkLayout:ln,chunkDisplayDimensionIndices:ve,fixedLayerToChunkTransform:Ct,curPositionInChunks:new Float32Array(a),combinedGlobalLocalToChunkTransform:k.combinedGlobalLocalToChunkTransform,fixedPositionWithinChunk:new Uint32Array(a),chunkTransform:k,chunkDisplayTransform:$}};return g.map(S=>S.map(x=>y(x)))}catch(y){for(const E of g)for(const{chunkSource:C}of E)C.dispose();const{globalDimensionNames:S}=i,b=`Cannot render (${Array.from(i.displayDimensionIndices.filter(E=>E!==-1),E=>S[E]).join(",\xA0")}) cross section: ${y.message}`;return r(b)}}var ZE=Object.defineProperty,eT=Object.getOwnPropertyDescriptor,Pc=(i,e,t,n)=>{for(var s=n>1?void 0:n?eT(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&ZE(e,t,s),s};/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function sg(i){let e=0;const{typeToIds:t}=i;for(const n of _n)e+=wr(n).pickIdsPerInstance*t[n].length;return e}class rg{constructor(e){this.bufferValid=!1,this.numPickIds=0,this.serializedAnnotations={data:e.data,typeToIds:e.typeToIds,typeToOffset:e.typeToOffset,typeToIdMaps:e.typeToIdMaps}}freeGPUMemory(e){const{buffer:t}=this;t!==void 0&&(t.dispose(),this.bufferValid=!1,this.buffer=void 0)}}class tT extends Wn{constructor(e,t){super(e),t.data!==void 0&&(this.data=new rg(t))}freeGPUMemory(e){super.freeGPUMemory(e);const{data:t}=this;t!==void 0&&t.freeGPUMemory(e)}dispose(){this.data=void 0}}class og extends ig{constructor(e,t){super(e,t),t.data!==void 0&&(this.data=new rg(t))}freeGPUMemory(e){super.freeGPUMemory(e);const{data:t}=this;t!==void 0&&t.freeGPUMemory(e)}dispose(){this.data=void 0}}let Xo=class extends Er{constructor(i,e){super(i,e),this.immediateChunkUpdates=!0,(this.parent=e.parent).spatiallyIndexedSources.add(this);const{rank:n,chunkDataSize:s}=this.spec,r=this.multiscaleToChunkTransform=new Float32Array((n+1)**2);we.DI(r,n+1,this.spec.chunkToMultiscaleTransform,n+1,n+1);for(let o=0;o<n;++o)for(let a=0;a<n+1;++a)r[(n+1)*a+o]/=s[o]}disposed(){this.parent.spatiallyIndexedSources.delete(this),super.disposed()}initializeCounterpart(i,e){e.parent=this.parent.rpcId,super.initializeCounterpart(i,e)}addChunk(i,e){super.addChunk(i,e)}getChunk(i){return new og(this,i)}};Xo=Pc([Kt(DE)],Xo);let Ac=class extends tn{constructor(i,e,t){super(i,{}),this.parent=e,this.relationshipIndex=t,this.immediateChunkUpdates=!0}addChunk(i,e){super.addChunk(i,e)}getChunk(i){return new tT(this,i)}};Ac=Pc([Kt(IE)],Ac);class nT extends Wn{constructor(e,t){super(e),this.annotation=Ch(t.annotation)}}let Mc=class extends tn{constructor(i,e){super(i),this.parent=e}getChunk(i){return new nT(this,i)}addChunk(i,e){super.addChunk(i,e);const{references:t}=this.parent,n=t.get(i);n!==void 0&&(n.value=e.annotation,n.changed.dispatch())}deleteChunk(i){const{references:e}=this.parent,t=e.get(i);t!==void 0&&(t.value=void 0,t.changed.dispatch())}};Mc=Pc([Kt(TE)],Mc);function ag(i,e,t,n){const s=new Uint8Array(i.data.length+n);for(const r of _n){if(r===t)continue;const o=i.typeToOffset[r];let a=o;r>t&&(a+=n,i.typeToOffset[r]=a),s.set(i.data.subarray(o,o+i.typeToIds[r].length*e[r].serializedBytes),a)}return s}function Nc(i,e,t,n,s,r,o,a){const l=i.typeToOffset[t];let c=l,d=l;const{propertyGroupBytes:u}=e[t],h=u.length,f=i.typeToIds[t].length;for(let m=0;m<h;++m){const g=u[m];n.set(i.data.subarray(c+s*g,c+r*g),d+o*g),c+=g*f,d+=g*a}}function Zo(i,e,t){const n=e.type,{rank:s}=t[n],{serializedAnnotations:r}=i,o=r.typeToIds[n],a=r.typeToIdMaps[n],l=Bt[n],c=t[n].serializedBytes;let d=a.get(e.id);if(d===void 0){d=a.size,a.set(e.id,d);const g=ag(r,t,n,c);Nc(r,t,n,g,0,d,0,d+1),o.push(e.id),r.data=g}const u=r.typeToOffset[n],h=new DataView(r.data.buffer,r.data.byteOffset,r.data.byteLength),f=te===F.LITTLE,m=t[n];l.serialize(h,u+m.propertyGroupBytes[0]*d,f,s,e),m.serialize(h,u,d,o.length,f,e.properties),i.bufferValid=!1}function ea(i,e,t,n){const{serializedAnnotations:s}=i,r=s.typeToIdMaps[e],o=r.get(t);if(o===void 0)return!1;const a=s.typeToIds[e],l=n[e].serializedBytes,c=ag(s,n,e,-l);Nc(s,n,e,c,0,o,0,a.length-1),Nc(s,n,e,c,o+1,a.length,o,a.length-1),a.splice(o,1),r.delete(t);for(let d=o,u=a.length;d<u;++d)r.set(a[d],d);return s.data=c,i.bufferValid=!1,!0}function iT(){const i=[],e=[],t=[];for(const n of _n)i[n]=[],e[n]=0,t[n]=new Map;return new og(void 0,{data:new Uint8Array(0),numPickIds:0,typeToOffset:e,typeToIds:i,typeToIdMaps:t})}class Tr extends un{constructor(e,t){super(),this.chunkManager=e,this.metadataChunkSource=this.registerDisposer(new Mc(this.chunkManager,this)),this.spatiallyIndexedSources=new Set,this.temporary=iT(),this.references=new Map,this.localUpdates=new Map,this.numCommitsInProgress=0,this.changed=new j.IY,this.readonly=!1,this.rank=t.rank,this.properties=t.properties,this.annotationPropertySerializers=wl(this.rank,this.properties);const n=this.segmentFilteredSources=[],{relationships:s}=t;this.relationships=s;for(let r=0,o=s.length;r<o;++r)n.push(this.registerDisposer(new Ac(e,this,r)))}hasNonSerializedProperties(){return this.relationships.length>0}getSources(e){throw new Error("not implemented")}initializeCounterpart(e,t){this.metadataChunkSource.initializeCounterpart(e,{});for(const n of this.segmentFilteredSources)n.initializeCounterpart(e,{});t.segmentFilteredSource=this.segmentFilteredSources.map(n=>n.addCounterpartRef()),t.metadataChunkSource=this.metadataChunkSource.addCounterpartRef(),t.chunkManager=this.chunkManager.rpcId,super.initializeCounterpart(e,t)}add(e,t=!0){e.id=Il();const n=new ei(e.id);return n.value=e,this.references.set(n.id,n),n.registerDisposer(()=>{this.references.delete(n.id)}),this.applyLocalUpdate(n,!1,t,e),n}applyLocalUpdate(e,t,n,s){const{localUpdates:r}=this,{id:o}=e;let a=this.localUpdates.get(o);const l=e.value;if(l==null)throw new Error("Cannot create local update from null annotation");if(a===void 0?(a={type:l.type,reference:e.addRef(),existingAnnotation:t?l:void 0,pendingCommit:void 0,commitInProgress:void 0},r.set(o,a),this.forEachPossibleChunk(l,c=>{const{data:d}=c;if(d===void 0)return;const u=l.type;ea(d,u,o,this.annotationPropertySerializers)}),s!==null&&Zo(this.temporary.data,s,this.annotationPropertySerializers)):(s===null?ea(this.temporary.data,l.type,l.id,this.annotationPropertySerializers):Zo(this.temporary.data,s,this.annotationPropertySerializers),e.value=s),n)if(a.commitInProgress!==void 0)a.pendingCommit=s;else{if(s===null&&a.existingAnnotation===void 0){r.delete(o),a.reference.dispose();return}this.sendCommitRequest(a,s)}this.notifyChanged(e.id,s||void 0)}sendCommitRequest(e,t){this.updateCommitsInProgress(1),e.commitInProgress=t,this.rpc.invoke(LE,{id:this.rpcId,annotationId:e.existingAnnotation&&e.reference.id,newAnnotation:t})}delete(e){this.applyLocalUpdate(e,!0,!0,null)}update(e,t){this.applyLocalUpdate(e,!0,!1,t)}notifyChanged(e,t){const n=this.references.get(e),s=this.metadataChunkSource.chunks.get(e);s!==void 0&&(s.annotation=t||null),n!==void 0&&(n.value=t||null,n.changed.dispatch()),this.chunkManager.chunkQueueManager.visibleChunksChanged.dispatch()}commit(e){this.applyLocalUpdate(e,!0,!0,e.value)}getReference(e){let t=this.references.get(e);if(t!==void 0)return t.addRef();t=new ei(e),this.references.set(e,t),this.rpc.invoke(RE,{id:this.rpcId,annotation:e}),t.registerDisposer(()=>{this.references.delete(e),this.rpc.invoke(kE,{id:this.rpcId,annotation:e})});const n=this.metadataChunkSource.chunks.get(e);return n!==void 0&&(t.value=n.annotation),t}forEachPossibleChunk(e,t){const{relatedSegments:n}=e;if(n!==void 0){const l=n.length,{segmentFilteredSources:c}=this;for(let d=0;d<l;++d){const u=n[d];if(u===void 0)return;const h=c[d];for(const f of u){const m=h.chunks.get(vn(f));m!==void 0&&t(m)}}}const{rank:s}=this,r=new Float32Array(s),o=new Float32Array(s),a=new Float32Array(s);for(const l of this.spatiallyIndexedSources){switch(e.type){case Je.POINT:we.vo(r,l.multiscaleToChunkTransform,s+1,e.point,s),o.set(r);break;case Je.LINE:case Je.AXIS_ALIGNED_BOUNDING_BOX:we.vo(r,l.multiscaleToChunkTransform,s+1,e.pointA,s),we.vo(o,l.multiscaleToChunkTransform,s+1,e.pointB,s);break;case Je.ELLIPSOID:we.vo(r,l.multiscaleToChunkTransform,s+1,e.center,s),we._U(o,l.multiscaleToChunkTransform,s+1,e.radii,s);for(let u=0;u<s;++u){const h=r[u],f=o[u];r[u]=h-f,o[u]=h+f}break}let c=1;for(let u=0;u<s;++u){const h=r[u],f=o[u],m=Math.min(h,f),g=Math.max(h,f);r[u]=Math.ceil(m-1),o[u]=Math.floor(g+1),c*=o[u]-r[u]}const{chunks:d}=l;for(let u=0;u<c;++u){let h=u;for(let m=0;m<s;++m){const g=r[m],y=o[m]-g,S=a[m]=h%y;h=(h-S)/y}const f=d.get(a.join());f!==void 0&&t(f)}}}static encodeOptions(e){return{}}handleSuccessfulUpdate(e,t){const n=this.localUpdates.get(e);if(n===void 0||n.commitInProgress===void 0)throw new Error("Received invalid successful update notification");if(this.updateCommitsInProgress(-1),t!==null&&n.reference.id!==t.id){if(n.commitInProgress===null)throw new Error("Received invalid successful update notification");n.reference.id=t.id,this.references.delete(e),this.references.set(t.id,n.reference),this.localUpdates.delete(e),this.localUpdates.set(t.id,n),n.reference.value!==null&&(n.reference.value.id=t.id,ea(this.temporary.data,n.type,e,this.annotationPropertySerializers),Zo(this.temporary.data,n.reference.value,this.annotationPropertySerializers)),n.reference.changed.dispatch()}n.existingAnnotation=t||void 0,n.commitInProgress=void 0;let{pendingCommit:s}=n;n.pendingCommit=void 0,t===null&&(s=void 0),s!==void 0?(s!==null&&(s.id=t.id),this.sendCommitRequest(n,s)):this.revertLocalUpdate(n)}disposed(){const{commitStatus:e}=this;e!==void 0&&e.dispose()}updateCommitsInProgress(e){this.numCommitsInProgress+=e,this.numCommitsInProgress===0?this.commitStatus!==void 0&&(this.commitStatus.dispose(),this.commitStatus=void 0):this.commitStatus===void 0&&(this.commitStatus=new Se(!0)).setText("Commiting annotations")}handleFailedUpdate(e,t){const n=this.localUpdates.get(e);if(n===void 0||n.commitInProgress===void 0)throw new Error("Received invalid update notification");new Se().setErrorMessage(`Error commiting annotation update: ${t}`),this.revertLocalUpdate(n),this.updateCommitsInProgress(-1)}revertLocalUpdate(e){ea(this.temporary.data,e.type,e.reference.id,this.annotationPropertySerializers);const{existingAnnotation:t}=e;t!==void 0&&this.forEachPossibleChunk(t,r=>{const{data:o}=r;o!==void 0&&Zo(o,t,this.annotationPropertySerializers)});const{reference:n}=e,{id:s}=n;n.value=t||null,n.changed.dispatch(),n.dispose(),this.localUpdates.delete(s)}*[Symbol.iterator](){}}dt(PE,function(i){const e=this.get(i.id),t=i.annotationId,n=i.error;if(n!==void 0)e.handleFailedUpdate(t,n);else{const s=Ch(i.newAnnotation);e.handleSuccessfulUpdate(t,s)}});var Dr=G(8795);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const lg={offset:0,completions:[]};function li(i,e){return e.offset+=i,e}function Oc(i,e){const t=[];for(const n of e)n.startsWith(i)&&t.push({value:n});return t.sort((n,s)=>(0,Dr.e)(n.value,s.value)),t}function Wt(i,e,t,n){const s=[];for(const r of e){const o=t(r);o.startsWith(i)&&s.push({value:o,description:n(r)})}return s.sort((r,o)=>(0,Dr.e)(r.value,o.value)),s}async function sT(i,e,t){if(i.startsWith("{"))return lg;const s=i.match(/^(?:(.*)[&;])?([^&;]*)$/)[2],r=i.length-s.length,o=s.indexOf("=");if(o===-1){const a=await e(s);return{offset:a.offset+r,completions:a.completions.map(l=>({...l,value:`${l.value}=`}))}}return li(r+o+1,await t(s.substring(0,o),s.substring(o+1)))}async function cg(i,e){return sT(i,async t=>{const n=[];for(const s of e){const r=s.key;r.value.startsWith(t)&&n.push(r)}return{offset:0,completions:n}},async(t,n)=>{for(const s of e)if(s.key.value===t)return{offset:0,completions:s.values.filter(r=>r.value.startsWith(n))};return lg})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Vc extends Error{constructor(e){super(`Redirected to: ${e}`),this.redirectTarget=e}}function dg(i,e){e===void 0&&(i.indexOf("/")===-1?e=":":e="/");const t=i.lastIndexOf(e);return t===-1?0:t+1}function rT(i,e){const t=dg(i,e);return i.substring(t)}var ks=(i=>(i[i.annotations=0]="annotations",i[i.equivalences=1]="equivalences",i))(ks||{});function ug(){return{url:"",transform:void 0,enableDefaultSubsources:!0,subsources:new Map}}class Ut extends D.O8{normalizeUrl(e){return e.url}convertLegacyUrl(e){return e.url}async completeUrl(e){throw null}}const hg="local://annotations",_c="local://equivalences";class oT extends Ut{get description(){return"Local in-memory"}async get(e){switch(e.url){case hg:{const{transform:t}=e;let n;if(t===void 0){const s=e.globalCoordinateSpace.value,{rank:r,names:o,scales:a,units:l}=s,c=ke({rank:r,scales:a,units:l,names:o.map((u,h)=>`${h}`)}),d=ke({rank:r,scales:a,units:l,names:o});n={rank:r,sourceRank:r,inputSpace:c,outputSpace:d,transform:(0,we.DA)(Float64Array,r+1)}}else n=yt(xi);return{modelTransform:n,canChangeModelSpaceRank:!0,subsources:[{id:"default",default:!0,subsource:{local:0}}]}}case _c:return{modelTransform:yt(xi),canChangeModelSpaceRank:!1,subsources:[{id:"default",default:!0,subsource:{local:1}}]}}throw new Error("Invalid local data source URL")}async completeUrl(e){return{offset:0,completions:Wt(e.providerUrl,[{value:"annotations",description:"Annotations stored in the JSON state"},{value:"equivalences",description:"Segmentation equivalence graph stored in the JSON state"}],t=>t.value,t=>t.description)}}}const pg=/^(?:([a-zA-Z][a-zA-Z0-9-+_]*):\/\/)?(.*)$/;class aT extends D.O8{constructor(e){super(),this.credentialsManager=e,this.dataSources=new Map([["local",new oT]])}register(e,t){this.dataSources.set(e,this.registerDisposer(t))}getProvider(e){const t=e.match(pg);if(t===null||t[1]===void 0)throw new Error('Data source URL must have the form "<protocol>://<path>".');const[,n,s]=t,r=this.dataSources.get(n);if(r===void 0)throw new Error(`Unsupported data source: ${JSON.stringify(n)}.`);return[r,s,n]}async get(e){const t=new Set,{cancellationToken:n=at.fx}=e;let s=e.url;for(;;){const[r,o,a]=this.getProvider(e.url);t.add(e.url);try{return r.get({...e,url:s,providerProtocol:a,providerUrl:o,registry:this,cancellationToken:n,credentialsManager:this.credentialsManager})}catch(l){if(l instanceof Vc){const c=l.redirectTarget;if(t.has(c))throw Error(`Layer source redirection contains loop: ${JSON.stringify(Array.from(t))}`);if(t.size>=10)throw Error(`Too many layer source redirections: ${JSON.stringify(Array.from(t))}`);s=c;continue}throw l}}}convertLegacyUrl(e){try{const[t,n,s]=this.getProvider(e.url);return t.convertLegacyUrl({...e,providerUrl:n,providerProtocol:s,registry:this})}catch{return e.url}}normalizeUrl(e){try{const[t,n,s]=this.getProvider(e.url);return t.normalizeUrl({...e,providerUrl:n,providerProtocol:s,registry:this})}catch{return e.url}}async completeUrl(e){const{url:t,cancellationToken:n=at.fx}=e,s=t.match(pg),r=s[1];if(r===void 0)return Promise.resolve({offset:0,completions:Wt(t,this.dataSources,([a])=>`${a}://`,([,a])=>a.description)});const o=this.dataSources.get(r);if(o!==void 0){const a=await o.completeUrl({registry:this,url:t,providerUrl:s[2],chunkManager:e.chunkManager,cancellationToken:n,credentialsManager:this.credentialsManager});return li(r.length+3,a)}throw null}suggestLayerName(e){let[t,n]=this.getProvider(e);n.endsWith("/")&&(n=n.substring(0,n.length-1));const s=t.suggestLayerName;return s!==void 0?s(n):rT(n)}findSourceGroup(e){const[t,n,s]=this.getProvider(e);return(t.findSourceGroup||dg)(n)+s.length+3}}var Ls=G(4022);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function lT(i){return typeof i=="boolean"?{enabled:i}:((0,p.Rf)(i),{enabled:(0,p.MM)(i,"enabled",p.aO)})}function Ir(i,e=void 0){return typeof i=="string"?{url:i,transform:e,enableDefaultSubsources:!0,subsources:new Map}:((0,p.Rf)(i),{url:(0,p.cQ)(i,"url",p.zr),transform:(0,p.cQ)(i,"transform",Uh)||e,enableDefaultSubsources:(0,p.MM)(i,"enableDefaultSubsources",p.aO,!0),subsources:(0,p.MM)(i,"subsources",t=>(0,p.vS)(t,lT),new Map),state:(0,p.MM)(i,"state",p.Rf)})}function cT(i){return i.enabled}function fg(i){const e=$h(i.transform),t={};let n=!0;for(const[s,r]of i.subsources){const o=cT(r);o!==void 0&&(t[s]=o,n=!1)}return e===void 0&&n&&i.enableDefaultSubsources===!0&&i.state===void 0?i.url:{url:i.url,transform:e,subsources:n?void 0:t,enableDefaultSubsources:i.enableDefaultSubsources===!0?void 0:!1,state:i.state}}class dT{constructor(e,t,n,s,r){this.loadedDataSource=e,this.subsourceEntry=t,this.subsourceSpec=n,this.subsourceIndex=s,this.activated=void 0,this.guardValues=[],this.messages=new Di,this.isActiveChanged=new j.IY;let o;n===void 0||n.enabled===void 0?o=t.default&&r:o=n.enabled;const a=e.dataSource.modelTransform.sourceRank;let{modelSubspaceDimensionIndices:l}=t;if(l===void 0){l=new Array(a);for(let d=0;d<a;++d)l[d]=d}const{subsourceToModelSubspaceTransform:c=we.DA(Float32Array,l.length+1)}=t;this.enabled=o,this.subsourceToModelSubspaceTransform=c,this.modelSubspaceDimensionIndices=l,this.isActiveChanged.add(e.activatedSubsourcesChanged.dispatch)}activate(e,...t){if(this.messages.clearMessages(),this.activated!==void 0){if((0,z.r1)(t,this.guardValues))return;this.activated.dispose()}this.guardValues=t;const n=this.activated=new D.O8;e(n),this.isActiveChanged.dispatch()}deactivate(e){this.messages.clearMessages(),this.messages.addMessage({severity:xn.error,message:e});const{activated:t}=this;t!==void 0&&(this.activated=void 0,t.dispose(),this.isActiveChanged.dispatch())}addRenderLayer(e){const t=this.activated;t.registerDisposer(this.loadedDataSource.layer.addRenderLayer(e)),t.registerDisposer(this.messages.addChild(e.messages))}getRenderLayerTransform(e){const t=this.activated,{layer:n,transform:s}=this.loadedDataSource;return t.registerDisposer(Hh(n.manager.root.coordinateSpace,n.localPosition.coordinateSpace,s,this,e))}}class Bc extends D.O8{constructor(e,t,n){super(),this.layerDataSource=e,this.dataSource=t,this.error=void 0,this.enabledSubsourcesChanged=new j.IY,this.activatedSubsourcesChanged=new j.IY,this.messages=new Di,t.canChangeModelSpaceRank?(this.transform=new Bh(yt(ke({rank:0,scales:new Float64Array(0),units:[],names:[]})),!0),this.transform.value=t.modelTransform):this.transform=new Bh(t.modelTransform),n.transform!==void 0&&(this.transform.spec=n.transform);const s=n.subsources;this.enableDefaultSubsources=n.enableDefaultSubsources,this.subsources=t.subsources.map((r,o)=>new dT(this,r,s.get(r.id),o,this.enableDefaultSubsources))}get enabledSubsources(){return this.subsources.filter(e=>e.enabled)}get layer(){return this.layerDataSource.layer}disposed(){for(const e of this.subsources){const{activated:t}=e;t!==void 0&&(e.activated=void 0,t.dispose())}}}class uT extends D.O8{constructor(e,t=void 0){super(),this.layer=e,this.changed=new j.IY,this.messages=new Di,this.loadState_=void 0,this.specGeneration=-1,this.refCounted_=void 0,this.registerDisposer(this.changed.add(e.dataSourcesChanged.dispatch)),this.registerDisposer(e.messages.addChild(this.messages)),t===void 0?this.spec_=ug():this.spec=t}get spec(){const{loadState:e}=this;if(e!==void 0&&e.error===void 0){const t=this.changed.count;t!==this.specGeneration&&(this.specGeneration=t,this.spec_={url:this.spec.url,transform:e.transform.spec,enableDefaultSubsources:e.enableDefaultSubsources,subsources:new Map(Array.from(e.subsources,n=>{const s=e.enableDefaultSubsources&&n.subsourceEntry.default;return[n.subsourceEntry.id,{enabled:n.enabled!==s?n.enabled:void 0}]})),state:this.spec.state})}return this.spec_}get loadState(){return this.loadState_}set spec(e){const{layer:t}=this;if(this.messages.clearMessages(),e.url.length===0){if(t.dataSources.length!==1){const l=t.dataSources.indexOf(this);if(l!==-1){t.dataSources.splice(l,1),t.dataSourcesChanged.dispatch(),this.dispose();return}}this.spec_=e,this.refCounted_!==void 0&&(this.refCounted_.dispose(),this.refCounted_=void 0,this.loadState_=void 0,this.changed.dispatch());return}const n=new D.O8,s=n.registerDisposer((0,D.K9)(t.markLoading()));this.refCounted_!==void 0&&(this.refCounted_.dispose(),this.loadState_=void 0),this.refCounted_=n,this.spec_=e;const r=t.manager.chunkManager,o=t.manager.dataSourceProviderRegistry,a=new at.Qi;this.messages.addMessage({severity:xn.info,message:"Loading data source"}),o.get({chunkManager:r,url:e.url,cancellationToken:a,globalCoordinateSpace:t.manager.root.coordinateSpace,transform:e.transform,state:e.state}).then(l=>{if(n.wasDisposed)return;this.messages.clearMessages();const c=n.registerDisposer(new Bc(this,l,e));c.registerDisposer(t.addCoordinateSpace(c.transform.outputSpace)),c.registerDisposer(c.transform.changed.add(this.changed.dispatch)),this.loadState_=c,c.registerDisposer(c.enabledSubsourcesChanged.add(this.changed.dispatch)),this.changed.dispatch(),l.state&&n.registerDisposer(l.state.changed.add(()=>{this.spec.state=l.state?.toJSON(),t.specificationChanged.dispatch()})),s()}).catch(l=>{this.wasDisposed||(this.loadState_={error:l},this.messages.clearMessages(),this.messages.addMessage({severity:xn.error,message:l.message}),this.changed.dispatch())}),n.registerDisposer(()=>{a.cancel()}),this.changed.dispatch()}disposed(){const e=this.refCounted_;e!==void 0&&e.dispose()}toJSON(){const{loadState:e}=this;return e===void 0||e.error!==void 0?fg(this.spec):fg({url:this.spec.url,transform:e.transform.spec,enableDefaultSubsources:e.enableDefaultSubsources,subsources:new Map(Array.from(e.subsources,t=>{const n=e.enableDefaultSubsources&&t.subsourceEntry.default;return[t.subsourceEntry.id,{enabled:t.enabled!==n?t.enabled:void 0}]})),state:this.spec.state})}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Fi={side:"right",col:0,row:1/0,flex:1,size:300,minSize:100,visible:!1};class ci{constructor(e=Fi,t=e){this.defaultValue=e,this.value=t,this.changed=new j.HN,this.locationChanged=new j.HN,this.locationChanged.add(this.changed.dispatch);const n=this;this.watchableVisible={get value(){return n.visible},set value(s){n.visible=s},changed:n.locationChanged}}toJSON(e=this.defaultValue){const t={},{value:n}=this;for(const s in n)n[s]!==e[s]&&(t[s]=n[s]);return t}get visible(){return this.value.visible}set visible(e){const{value:t}=this;t.visible!==e&&(this.value={...t,visible:e},this.locationChanged.dispatch())}reset(){this.value!==this.defaultValue&&(this.value=this.defaultValue,this.locationChanged.dispatch())}restoreState(e,t=this.defaultValue){if(e===void 0)return;(0,p.Rf)(e);const n={side:(0,p.MM)(e,"side",s=>{if(s!=="left"&&s!=="right"&&s!=="top"&&s!=="bottom")throw new Error(`Expected "left", "right", "top", or "bottom", but received: ${JSON.stringify(s)}`);return s},t.side),col:(0,p.MM)(e,"col",p.zo,t.col),row:(0,p.MM)(e,"row",p.zo,t.row),flex:(0,p.MM)(e,"flex",p.zo,t.flex),size:(0,p.MM)(e,"size",p.We,t.size),visible:(0,p.MM)(e,"visible",p.aO,t.visible),minSize:t.minSize};this.value=n,this.locationChanged.dispatch()}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ta="tab",gg="tabs",mg="panels",hT={...Fi,row:0},vg={...Fi,visible:!0,row:0};class Rr extends D.O8{constructor(e){super(),this.panels=e,this.layer=this.panels.layer,this.location=new ci(vg),this.tabsChanged=new j.HN,this.selectedTab=new A.B0(void 0),this.tabs=[]}initialize(){const{panels:e}=this;this.tabsChanged.add(e.specificationChanged.dispatch),this.selectedTab.changed.add(e.specificationChanged.dispatch),this.location.changed.add(()=>{e.specificationChanged.dispatch();const{layer:t}=this,{selectedLayer:n}=t.manager.root;if(n.layer?.layer!==t||this!==t.panels.panels[0])return;const s=this.location.value;n.location.value!==s&&(n.location.value=s,n.location.locationChanged.dispatch())}),this.location.locationChanged.add(()=>{this.location.visible||this!==this.panels.panels[0]&&this.panels.removePanel(this)});for(const t of this.tabs){const{hidden:n}=this.layer.tabs.options.get(t);n&&this.registerDisposer(n.changed.add(()=>{this.panels.updateTabs(),this.tabsChanged.dispatch()}))}}normalizeTabs(){const{tabs:e}=this;if(e.length===0){this.selectedTab.value=void 0;return}const t=this.layer.tabs.options,n=o=>t.get(o).order??0;e.sort((o,a)=>n(o)-n(a));const{selectedTab:s}=this,r=s.value;(r===void 0||!e.includes(r))&&(s.value=e[0])}pin(){const{layer:e}=this,{selectedLayer:t}=e.manager.root;if(t.layer?.layer!==e||this!==e.panels.panels[0]||this.tabs.length===0)return;const{panels:n}=this,s=e.registerDisposer(new Rr(n));n.panels.splice(0,1,s),n.panels.push(this),n.updateTabs(),s.initialize(),t.layerManager.layersChanged.dispatch(),this.panels.specificationChanged.dispatch()}unpin(){const{panels:e}=this,t=e.panels.indexOf(this);if(t===-1||t===0)return;const{layer:n}=this,{selectedLayer:s}=n.manager.root,r=s.layer?.layer;s.visible&&r!=null&&r!==n&&r.panels.panels[0].pin(),e.panels.splice(t,1);const[o]=e.panels.splice(0,1,this);if(this.explicitTabs===void 0)n.unregisterDisposer(o);else{e.panels.push(o);for(let a=1,l=e.panels.length;a<l;++a){const c=e.panels[a];c.explicitTabs===void 0&&(c.explicitTabs=new Set(c.tabs))}}this.explicitTabs=void 0,e.updateTabs(),s.layer=n.managedLayer,s.location.value=this.location.value,s.location.locationChanged.dispatch(),s.layerManager.layersChanged.dispatch(),this.panels.specificationChanged.dispatch()}splitOffTab(e,t){if(!this.tabs.includes(e))return;const{panels:n}=this;{const{explicitTabs:o}=this;o!==void 0&&o.delete(e)}const{layer:s}=this,r=s.registerDisposer(new Rr(n));r.location.value=t,r.explicitTabs=new Set([e]),n.panels.splice(1,0,r),n.updateTabs(),r.initialize(),s.manager.root.layerManager.layersChanged.dispatch(),n.specificationChanged.dispatch()}moveTabTo(e,t){if(!this.tabs.includes(e))return;{const{explicitTabs:s}=this;s!==void 0&&s.delete(e)}{const{explicitTabs:s}=t;s!==void 0&&s.add(e)}const{panels:n}=this;n.updateTabs(),t.selectedTab.value=e,n.specificationChanged.dispatch()}mergeInto(e){const{explicitTabs:t}=e;if(t!==void 0)for(const s of this.tabs)t.add(s);const{panels:n}=this;n.removePanel(this)}}class pT{constructor(e){this.layer=e,this.specificationChanged=new j.HN,this.updating=!1,this.panels=[e.registerDisposer(new Rr(this))]}restoreState(e){const{panels:t}=this;t[0].selectedTab.value=(0,p.MM)(e,ta,p.zr);const{layer:n}=this,{tabs:s}=n,r=new Set(s.options.keys());(0,p.MM)(e,mg,o=>(0,p.$v)(o,a=>{(0,p.Rf)(a);const l=new Rr(this);l.location.restoreState(a),l.location.visible&&(l.selectedTab.value=(0,p.MM)(a,ta,p.zr),l.explicitTabs=(0,p.MM)(a,gg,c=>{const d=new Set;for(const u of(0,p.si)(c))r.has(u)&&(r.delete(u),d.add(u));return d}),l.explicitTabs===void 0?(l.tabs=Array.from(r),r.clear()):l.tabs=Array.from(l.explicitTabs),l.tabs.length!==0&&(l.normalizeTabs(),n.registerDisposer(l),l.initialize(),t.push(l)))})),t[0].tabs=Array.from(r),t[0].normalizeTabs(),this.panels[0].initialize()}removePanel(e){if(this.updating)return;const t=this.panels.indexOf(e);this.panels.splice(t,1),this.layer.unregisterDisposer(e),this.updateTabs()}updateTabs(){const{layer:e}=this,{tabs:t}=e,n=new Set(t.options.keys()),{panels:s}=this;this.updating=!0;const r=o=>{const a=o.tabs;if(o.explicitTabs===void 0)o.tabs=Array.from(n),n.clear();else{o.tabs=Array.from(o.explicitTabs);for(const l of o.tabs)n.delete(l)}(0,z.r1)(a,o.tabs)||(o.normalizeTabs(),o.tabsChanged.dispatch())};for(let o=1;o<s.length;){const a=s[o];if(a.location.visible&&(r(a),a.tabs.length!==0)){++o;continue}s.splice(o,1),e.unregisterDisposer(a)}if(r(s[0]),s[0].tabs.length===0){const{selectedLayer:o}=this.layer.manager.root;o.layer?.layer===this.layer&&(o.location.visible=!1)}this.updating=!1}toJSON(){const{panels:e}=this,t={};if(t[ta]=e[0].selectedTab.value,e.length>1){const n=[];for(let s=1,r=e.length;s<r;++s){const o=e[s],a=o.location.toJSON()??{};a[ta]=o.selectedTab.value;const{explicitTabs:l}=o;l!==void 0&&(a[gg]=Array.from(l)),n.push(a)}t[mg]=n}return t}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function fT(i,e){i.remove(e)}function gT(i,e){i.add(e)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const yg="tool",Sg="toolBindings",Fc="localPosition",bg="localVelocity",wg="localDimensions",Cg="source",mT="transform",xg="pick";class vT{constructor(){this.callbacks=[]}defer(e){this.callbacks.push(e)}}const Eg=[];class Ln extends D.O8{constructor(e){super(),this.managedLayer=e,this.pick=new rt(!0,!0),this.messages=new Di,this.layersChanged=new j.IY,this.readyStateChanged=new j.IY,this.specificationChanged=new j.IY,this.renderLayers=new Array,this.loadingCounter=1,this.tabs=this.registerDisposer(new ex),this.panels=new pT(this),this.tool=this.registerDisposer(new px(this)),this.toolBinder=this.registerDisposer(new gc(this,this.manager.root.toolBinder)),this.dataSourcesChanged=new j.IY,this.dataSources=[],this.localCoordinateSpaceCombiner.includeDimensionPredicate=Oh,this.tabs.changed.add(this.specificationChanged.dispatch),this.panels.specificationChanged.add(this.specificationChanged.dispatch),this.tool.changed.add(this.specificationChanged.dispatch),this.toolBinder.changed.add(this.specificationChanged.dispatch),this.localPosition.changed.add(this.specificationChanged.dispatch),this.pick.changed.add(this.specificationChanged.dispatch),this.pick.changed.add(this.layersChanged.dispatch),this.dataSourcesChanged.add(this.specificationChanged.dispatch),this.dataSourcesChanged.add(()=>this.updateDataSubsourceActivations()),this.messages.changed.add(this.layersChanged.dispatch);for(const t of Eg)this.tabs.add(t.id,{label:t.label,order:t.order,getter:()=>t.getter(this)})}get localPosition(){return this.managedLayer.localPosition}get localVelocity(){return this.managedLayer.localVelocity}get localCoordinateSpaceCombiner(){return this.managedLayer.localCoordinateSpaceCombiner}get localCoordinateSpace(){return this.managedLayer.localCoordinateSpace}get type(){return this.constructor.type}initializeSelectionState(e){e.generation=-1,e.localPositionValid=!1,e.localPosition=rs,e.localCoordinateSpace=void 0,e.annotationId=void 0,e.annotationType=void 0,e.annotationBuffer=void 0,e.annotationIndex=void 0,e.annotationCount=void 0,e.annotationSourceIndex=void 0,e.annotationSubsource=void 0,e.annotationPartIndex=void 0,e.value=void 0}resetSelectionState(e){e.localPositionValid=!1,e.annotationId=void 0,e.value=void 0}selectionStateFromJson(e,t){const n=e.localCoordinateSpace=this.localCoordinateSpace.value,{rank:s}=n;if(s!==0){const o=(0,p.MM)(t,Fc,a=>(0,p.Xu)(new Float32Array(s),a,p.zo));o===void 0?e.localPositionValid=!1:(e.localPositionValid=!0,e.localPosition=o)}(e.annotationId=(0,p.MM)(t,"annotationId",p.zr))!==void 0&&(e.annotationSourceIndex=(0,p.MM)(t,"annotationSource",p.bX,0),e.annotationPartIndex=(0,p.MM)(t,"annotationPart",p.bX),e.annotationSubsource=(0,p.MM)(t,"annotationSubsource",p.zr)),e.value=t.value}displaySelectionState(e,t,n){return!1}selectionStateToJson(e,t){const n={};if(e.localPositionValid){const{localPosition:s}=e;s.length>0&&(n.localPosition=Array.from(s))}return e.annotationId!==void 0&&(n.annotationId=e.annotationId,n.annotationPart=e.annotationPartIndex,n.annotationSource=e.annotationSourceIndex,n.annotationSubsource=e.annotationSubsource),e.value!=null&&(n.value=e.value),n}captureSelectionState(e,t){e.localCoordinateSpace=this.localCoordinateSpace.value;const n=this.localPosition.value,{localPosition:s}=e;s.length!==n.length?e.localPosition=n.slice():s.set(n),e.localPositionValid=!0,e.value=this.getValueAt(t.position,t)}copySelectionState(e,t){e.generation=t.generation,e.localPositionValid=t.localPositionValid,e.localCoordinateSpace=t.localCoordinateSpace;const n=t.localPosition,{localPosition:s}=e;s.length!==n.length?e.localPosition=n.slice():e.localPosition.set(n),e.annotationId=t.annotationId,e.annotationType=t.annotationType,e.annotationBuffer=t.annotationBuffer,e.annotationIndex=t.annotationIndex,e.annotationCount=t.annotationCount,e.annotationSourceIndex=t.annotationSourceIndex,e.annotationSubsource=t.annotationSubsource,e.annotationPartIndex=t.annotationPartIndex,e.value=t.value}get isReady(){return this.loadingCounter===0}get manager(){return this.managedLayer.manager}canAddDataSource(){return!0}addDataSource(e){const t=new uT(this,e);return this.dataSources.push(t),this.dataSourcesChanged.dispatch(),t}activateDataSubsources(e){}updateDataSubsourceActivations(){function*e(){for(const t of this.dataSources){const{loadState:n}=t;if(!(n===void 0||n.error!==void 0))for(const s of n.subsources)if(s.enabled)yield s;else{const{activated:r}=s;s.messages.clearMessages(),r!==void 0&&(r.dispose(),s.activated=void 0,n.activatedSubsourcesChanged.dispatch())}}}this.activateDataSubsources(e.call(this))}decrementLoadingCounter(){--this.loadingCounter===0&&this.readyStateChanged.dispatch()}markLoading(){const e=this.localCoordinateSpaceCombiner.retain(),t=this.manager.root.coordinateSpaceCombiner.retain();return++this.loadingCounter===1&&this.readyStateChanged.dispatch(),()=>{e(),t(),this.decrementLoadingCounter()}}addCoordinateSpace(e){const t=this.manager.root.coordinateSpaceCombiner.bind(e),n=this.localCoordinateSpaceCombiner.bind(e);return()=>{t(),n()}}initializationDone(){const e=this.selectionState={};this.initializeSelectionState(e),this.decrementLoadingCounter()}getLegacyDataSourceSpecifications(e,t,n,s){return e===void 0?[]:[Ir(e,n)]}getDataSourceSpecifications(e){let t,n=(0,p.cQ)(e,Cg,r=>Array.isArray(r)?r.map(o=>Ir(o)):typeof r=="object"?[Ir(r)]:(t=r,[]));const s=(0,p.cQ)(e,mT,yw);return n.push(...this.getLegacyDataSourceSpecifications(t,e,s,n)),n=n.filter(r=>r.url),n.length===0&&n.push(ug()),n}restoreState(e){this.tool.restoreState(e[yg]),this.panels.restoreState(e),this.localCoordinateSpace.restoreState(e[wg]),this.localPosition.restoreState(e[Fc]),this.localVelocity.restoreState(e[bg]),this.toolBinder.restoreState(e[Sg]),this.constructor.supportsPickOption&&this.pick.restoreState(e[xg]);for(const t of this.getDataSourceSpecifications(e))this.addDataSource(t)}addRenderLayer(e){this.renderLayers.push(e);const{layersChanged:t}=this;return e.layerChanged.add(t.dispatch),e.userLayer=this,t.dispatch(),()=>this.removeRenderLayer(e)}removeRenderLayer(e){const{renderLayers:t,layersChanged:n}=this,s=t.indexOf(e);if(s===-1)throw new Error("Attempted to remove invalid RenderLayer");t.splice(s,1),e.layerChanged.remove(n.dispatch),e.userLayer=void 0,e.dispose(),n.dispatch()}disposed(){const{layersChanged:e}=this;(0,D.$F)(this.dataSources);for(const t of this.renderLayers)t.layerChanged.remove(e.dispatch),t.dispose();this.renderLayers.length=0,super.disposed()}getValueAt(e,t){let n;const{renderLayers:s}=this,{pickedRenderLayer:r}=t;if(r!==null&&s.indexOf(r)!==-1&&(n=r.transformPickedValue(t),n=this.transformPickedValue(n),n!=null))return n;for(const o of s)if(n=o.getValueAt(e),n!=null)break;return this.transformPickedValue(n)}transformPickedValue(e){return e}toJSON(){return{type:this.type,[Cg]:yT(this.dataSources),[yg]:this.tool.toJSON(),[Sg]:this.toolBinder.toJSON(),[wg]:this.localCoordinateSpace.toJSON(),[Fc]:this.localPosition.toJSON(),[bg]:this.localVelocity.toJSON(),[xg]:this.pick.toJSON(),...this.panels.toJSON()}}handleAction(e,t){}selectedValueToJson(e){return e}selectedValueFromJson(e){return e}setLayerPosition(e,t){const{globalPosition:n}=this.manager.root,{localPosition:s}=this;(0,z.b8)(n.value,t,e.globalToRenderLayerDimensions),(0,z.b8)(s.value,t,e.localToRenderLayerDimensions),s.changed.dispatch(),n.changed.dispatch()}}Ln.supportsPickOption=!1;function yT(i){if(i.length!==0)return i.length===1?i[0].toJSON():i.map(e=>e.toJSON())}class Uc extends D.O8{constructor(e,t){super(),this.manager=t,this.localCoordinateSpace=new Ml,this.localCoordinateSpaceCombiner=new Fl(this.localCoordinateSpace,tr),this.localPosition=this.registerDisposer(new oi(this.localCoordinateSpace)),this.localVelocity=this.registerDisposer(new sc(this.localCoordinateSpace)),this.nonArchivedLayerIndex=-1,this.readyStateChanged=new j.IY,this.layerChanged=new j.IY,this.specificationChanged=new j.IY,this.containers=new Set,this.layer_=null,this.visible=!0,this.archived=!1,this.name_=e,this.registerDisposer(new rc(this.manager.root.display,this.localPosition,this.localVelocity))}get layer(){return this.layer_}set layer(e){const t=this.layer_;if(t!=null&&(this.unregisterUserLayer(),t.dispose()),this.layer_=e,e!=null){const n=[e.layersChanged.add(this.layerChanged.dispatch),e.readyStateChanged.add(this.readyStateChanged.dispatch),e.specificationChanged.add(this.specificationChanged.dispatch)];this.unregisterUserLayer=()=>{n.forEach(s=>s())},this.readyStateChanged.dispatch(),this.layerChanged.dispatch()}}isReady(){const{layer:e}=this;return e?.isReady}get name(){return this.name_}set name(e){e!==this.name_&&(this.name_=e,this.layerChanged.dispatch())}get supportsPickOption(){const e=this.layer;return e!==null&&e.constructor.supportsPickOption}get pickEnabled(){const e=this.layer;return e!==null&&e.constructor.supportsPickOption&&e.pick.value}set pickEnabled(e){const t=this.layer;t!==null&&t.constructor.supportsPickOption&&(t.pick.value=e)}toJSON(){const e=this.layer;if(e===null)return;const t=e.toJSON();return t.name=this.name,this.visible||(this.archived?t.archived=!0:t.visible=!1),t}setVisible(e){if(e!==this.visible){if(e&&this.archived){this.visible=!0,this.setArchived(!1);return}this.visible=e,this.layerChanged.dispatch()}}setArchived(e){if(this.archived!==e){if(e===!0){this.visible=!1,this.archived=!0;for(const{layerManager:t}of this.manager.root.subsets)t.has(this)&&t.removeManagedLayer(this)}else{for(const{layerManager:t}of this.manager.root.subsets)t.has(this)||t.addManagedLayer(this.addRef());this.archived=!1}this.layerChanged.dispatch()}}disposed(){this.layer=null,super.disposed()}}class Tg extends D.O8{constructor(){super(),this.managedLayers=new Array,this.layerSet=new Set,this.layersChanged=new j.IY,this.readyStateChanged=new j.IY,this.specificationChanged=new j.IY,this.boundPositions=new WeakSet,this.numDirectUsers=0,this.nonArchivedLayerIndexGeneration=-1,this.renderLayerToManagedLayerMapGeneration=-1,this.renderLayerToManagedLayerMap_=new Map,this.scheduleRemoveLayersWithSingleRef=this.registerCancellable((0,xe.A)(()=>this.removeLayersWithSingleRef(),0)),this.layersChanged.add(this.scheduleRemoveLayersWithSingleRef)}updateNonArchivedLayerIndices(){const e=this.layersChanged.count;if(e===this.nonArchivedLayerIndexGeneration)return;this.nonArchivedLayerIndexGeneration=e;let t=0;for(const n of this.managedLayers)n.archived||(n.nonArchivedLayerIndex=t++);for(const n of this.managedLayers)n.archived&&(n.nonArchivedLayerIndex=t++)}getLayerByNonArchivedIndex(e){let t=0;for(const n of this.managedLayers)if(!n.archived){if(t===e)return n;++t}}get renderLayerToManagedLayerMap(){const e=this.layersChanged.count,t=this.renderLayerToManagedLayerMap_;if(this.renderLayerToManagedLayerMapGeneration!==e){this.renderLayerToManagedLayerMapGeneration=e,t.clear();for(const n of this.managedLayers){const s=n.layer;if(s!==null)for(const r of s.renderLayers)t.set(r,n)}}return t}filter(e){let t=!1;this.managedLayers=this.managedLayers.filter(n=>e(n)?!0:(this.unbindManagedLayer(n),this.layerSet.delete(n),t=!0,!1)),t&&this.layersChanged.dispatch()}removeLayersWithSingleRef(){this.numDirectUsers>0||this.filter(e=>e.refCount!==1||e.archived)}updateSignalBindings(e,t){t(e.layerChanged,this.layersChanged.dispatch),t(e.readyStateChanged,this.readyStateChanged.dispatch),t(e.specificationChanged,this.specificationChanged.dispatch)}useDirectly(){return++this.numDirectUsers===1&&this.layersChanged.remove(this.scheduleRemoveLayersWithSingleRef),()=>{--this.numDirectUsers===0&&(this.layersChanged.add(this.scheduleRemoveLayersWithSingleRef),this.scheduleRemoveLayersWithSingleRef())}}addManagedLayer(e,t){return this.updateSignalBindings(e,gT),this.layerSet.add(e),e.containers.add(this),t===void 0&&(t=this.managedLayers.length),this.managedLayers.splice(t,0,e),this.layersChanged.dispatch(),this.readyStateChanged.dispatch(),e}*readyRenderLayers(){for(const e of this.managedLayers)!e.visible||!e.layer||(yield*e.layer.renderLayers)}unbindManagedLayer(e){this.updateSignalBindings(e,fT),e.containers.delete(this),e.manager.rootLayers.layersChanged.dispatch(),e.dispose()}clear(){for(const e of this.managedLayers)this.unbindManagedLayer(e);this.managedLayers.length=0,this.layerSet.clear(),this.layersChanged.dispatch()}remove(e){const t=this.managedLayers[e];this.unbindManagedLayer(t),this.managedLayers.splice(e,1),this.layerSet.delete(t),this.layersChanged.dispatch()}removeManagedLayer(e){const t=this.managedLayers.indexOf(e);if(t===-1)throw new Error("Internal error: invalid managed layer.");this.remove(t)}reorderManagedLayer(e,t){const n=this.managedLayers.length;if(e===t||e<0||e>=n||t<0||t>=n)return;const[s]=this.managedLayers.splice(e,1);this.managedLayers.splice(t,0,s),this.layersChanged.dispatch()}disposed(){this.clear(),super.disposed()}getLayerByName(e){return this.managedLayers.find(t=>t.name===e)}getUniqueLayerName(e){let t=e,n=0;for(;this.getLayerByName(t)!==void 0;)t=e+ ++n;return t}has(e){return this.layerSet.has(e)}get renderLayers(){const e=this;return{*[Symbol.iterator](){for(const t of e.managedLayers)if(t.layer!==null)for(const n of t.layer.renderLayers)yield n}}}get visibleRenderLayers(){const e=this;return{*[Symbol.iterator](){for(const t of e.managedLayers)if(!(t.layer===null||!t.visible))for(const n of t.layer.renderLayers)yield n}}}invokeAction(e){const t=new vT;for(const n of this.managedLayers){if(n.layer===null||!n.visible)continue;const s=n.layer;s.handleAction(e,t);for(const r of s.renderLayers)r.handleAction(e)}for(const n of t.callbacks)n()}}class ST{constructor(){this.changed=new j.IY,this.coordinateSpace=Bn,this.position=rs,this.unsnappedPosition=rs,this.active=!1,this.displayDimensions=void 0,this.pickedRenderLayer=null,this.pickedValue=new M.R(0,0),this.pickedOffset=0,this.pickedAnnotationLayer=void 0,this.pickedAnnotationId=void 0,this.pickedAnnotationBuffer=void 0,this.pickedAnnotationBufferBaseOffset=void 0,this.pickedAnnotationIndex=void 0,this.pickedAnnotationCount=void 0,this.pickedAnnotationType=void 0,this.forcerFunction=void 0}removeForcer(e){e===this.forcerFunction&&(this.forcerFunction=void 0,this.setActive(!1))}setForcer(e){this.forcerFunction=e,e===void 0&&this.setActive(!1)}updateUnconditionally(){const{forcerFunction:e}=this;return e===void 0?!1:(e(),this.active)}setActive(e){(this.active!==e||e===!0)&&(this.active=e,this.changed.dispatch())}}class bT extends D.O8{constructor(e,t){super(),this.layerManager=e,this.mouseState=t,this.changed=new j.IY,this.needsUpdate=!0,this.registerDisposer(t.changed.add(()=>{this.handleChange()})),this.registerDisposer(e.layersChanged.add(()=>{this.handleLayerChange()}))}handleLayerChange(){this.mouseState.active&&this.handleChange()}handleChange(){this.needsUpdate=!0,this.changed.dispatch()}update(){if(!this.needsUpdate)return;this.needsUpdate=!1;const e=this.mouseState,t=this.changed.count;if(e.active)for(const n of this.layerManager.managedLayers){const s=n.layer;if(n.visible&&s!==null){const{selectionState:r}=s;s.resetSelectionState(r),r.generation=t,s.captureSelectionState(r,e)}}}get(e){this.update();const{selectionState:t}=e;if(t.generation===this.changed.count)return t}toJSON(){this.update();const e={};for(const t of this.layerManager.managedLayers){const n=t.layer;if(n){const s=this.get(n);s!==void 0&&(e[t.name]=n.selectionStateToJson(s,!0))}}return e}}const Dg=10,$c={...Fi,minSize:150,row:1},Ig={...$c,visible:!0};class wT extends D.O8{constructor(e,t){super(),this.coordinateSpace=e,this.layerSelectedValues=t,this.changed=new j.IY,this.history=[],this.historyIndex=0,this.location=new ci($c),this.pin=new A.B0(!0),this.registerDisposer((0,A.no)((n,s)=>{s||(this.capture(!0),n.registerDisposer(t.changed.add(n.registerCancellable((0,Ls.A)(()=>this.capture(!0),100,{leading:!0,trailing:!0})))))},this.pin)),this.pin.changed.add(this.changed.dispatch),this.location.changed.add(this.changed.dispatch)}get value(){return this.value_}goBack(){const e=this.pin.value?this.historyIndex:this.history.length;e>0&&(this.historyIndex=e-1,this.value_=this.history[e-1],this.pin.value=!0,this.changed.dispatch())}canGoBack(){return(this.pin.value?this.historyIndex:this.history.length)>0}canGoForward(){return this.pin.value?this.historyIndex+1<this.history.length:!1}goForward(){if(!this.pin.value)return;const e=this.historyIndex;e+1<this.history.length&&(this.historyIndex=e+1,this.value_=this.history[e+1],this.changed.dispatch())}set value(e){if(e!==this.value_){if(this.value_=e,e!==void 0&&this.pin.value){const{history:t}=this;t.length=Math.min(t.length,this.historyIndex+1),t.push(e),t.length>Dg&&t.splice(0,t.length-Dg),this.historyIndex=t.length-1}this.changed.dispatch()}}captureSingleLayerState(e,t,n=!0){if(n===!1&&(!this.location.visible||this.pin.value))return;const s={};e.initializeSelectionState(s),t(s)&&(this.location.visible=!0,n===!0?this.pin.value=!0:n==="toggle"&&(this.pin.value=!this.pin.value),this.value={layers:[{layer:e,state:s}],coordinateSpace:this.coordinateSpace.value,position:void 0})}reset(){this.location.reset(),this.pin.value=!1,this.value=void 0}toJSON(){const{value:e}=this;let t;if(this.location.visible){if(t=this.location.toJSON(Ig),this.pin.value&&e!==void 0){const n={};for(const s of e.layers){const{layer:r}=s;let o=r.selectionStateToJson(s.state,!1);Object.keys(o).length===0&&(o=void 0),n[s.layer.managedLayer.name]=o}e.position!==void 0&&(t.position=Array.from(e.position)),t.layers=n}}else t=this.location.toJSON($c),t=(0,p.Zu)(t),t!==void 0&&(t.visible=!1);return t}select(){const{pin:e}=this;this.location.visible=!0,e.value=!e.value,e.value&&this.capture()}capture(e=!1){const t=CT(this.layerSelectedValues);e&&t===void 0||(this.value=t)}restoreState(e){if(e===void 0){this.pin.value=!0,this.value=void 0;return}if(e===null){this.pin.value=!1,this.location.visible=!0,this.value=void 0;return}(0,p.Rf)(e),this.location.restoreState(e,Ig);const t=this.coordinateSpace.value,n=(0,p.MM)(e,"position",r=>(0,p.Xu)(new Float32Array(t.rank),r,p.zo)),s=[];(0,p.MM)(e,"layers",r=>{(0,p.Rf)(r);const{layerManager:o}=this.layerSelectedValues;for(const[a,l]of Object.entries(r)){const c=o.getLayerByName(a);if(c===void 0)return;const d=c.layer;if(d===null)return;(0,p.Rf)(l);const u={};d.initializeSelectionState(u),d.selectionStateFromJson(u,l),s.push({layer:d,state:u})}}),this.pin.value=s.length>0||n!==void 0,this.value={position:n,coordinateSpace:t,layers:s}}}function CT(i){const{mouseState:e}=i;if(!e.active)return;const t=[];for(const n of i.layerManager.managedLayers){const s=n.layer;if(s===null)continue;const r=i.get(s);if(r===void 0)continue;const o={};s.initializeSelectionState(o),s.copySelectionState(o,r),t.push({layer:s,state:o})}return{position:e.position.slice(),coordinateSpace:e.coordinateSpace,layers:t}}class xT extends D.O8{constructor(e){super(),this.view=e,this.messages=new Di,this.seenGeneration=-1,this.state=void 0}}let ET=0;class TT extends D.O8{constructor(e,t,n,s,r,o){super(),this.layerManager=e,this.renderLayerType=t,this.view=n,this.roles=s,this.layerAdded=r,this.visibility=o,this.visibleLayers_=new Map,this.debouncedUpdateVisibleLayers=this.registerCancellable((0,xe.A)(()=>this.updateVisibleLayers(),0)),this.registerDisposer(e.layersChanged.add(this.debouncedUpdateVisibleLayers)),this.registerDisposer(s.changed.add(this.debouncedUpdateVisibleLayers)),this.updateVisibleLayers()}disposed(){this.visibleLayers.forEach(e=>e.dispose()),this.visibleLayers.clear(),super.disposed()}updateVisibleLayers(){const e=++ET,{visibleLayers_:t,renderLayerType:n,layerAdded:s,roles:r}=this;for(const o of this.layerManager.readyRenderLayers())if(o instanceof n&&r.has(o.role)){const a=o;let l=t.get(a);l===void 0&&(l=new xT(this.view),l.registerDisposer(a.messages.addChild(l.messages)),l.registerDisposer(a.addRef()),l.registerDisposer(a.visibility.add(this.visibility)),t.set(a,l),s(a,l),a.attach(l)),l.seenGeneration=e}for(const[o,a]of t)a.seenGeneration!==e&&(t.delete(o),a.dispose())}get visibleLayers(){return this.debouncedUpdateVisibleLayers.flush(),this.visibleLayers_}}function Rg(i,e,t,n,s){return n.registerDisposer(new TT(i,e,n,t,(r,o)=>{o.registerDisposer(r.redrawNeeded.add(()=>n.scheduleRedraw()));const{backend:a}=r;a&&(a.rpc.invoke(co.sC,{layer:a.rpcId,view:n.rpcId}),o.registerDisposer(()=>a.rpc.invoke(co.lG,{layer:a.rpcId,view:n.rpcId}))),s!==void 0&&s(r,o),n.scheduleRedraw(),o.registerDisposer(()=>n.scheduleRedraw())},n.visibility))}class DT extends D.O8{constructor(e){super(),this.layerManager=e,this.changed=new j.IY,this.location=new ci(hT),this.registerDisposer(e),this.location.changed.add(()=>{this.changed.dispatch();const t=this.layer?.layer??void 0;if(t!==void 0){const n=this.location.value;if(n.visible){const s=t.panels.panels[0];s.location.value!==n&&(s.location.value=n,s.location.locationChanged.dispatch())}}})}get layer(){return this.layer_}get visible(){return this.location.visible}toggle(e){this.layer===e&&this.visible?this.visible=!1:(this.layer=e,this.visible=!0)}set visible(e){let t=this.layer_;if(e===!0&&t===void 0){const{managedLayers:n}=this.layerManager;n.length>0?t=this.layer=n[0]:e=!1}if(e===!0&&t!==void 0){const n=t.layer;(n===null||n.panels.panels[0].tabs.length===0)&&(e=!1)}this.visible!==e&&(this.location.visible=e,!e&&t!==void 0&&this.maybeDeleteNewLayer(t),this.changed.dispatch())}maybeDeleteNewLayer(e){if(e.wasDisposed)return;const t=e.layer;t!==null&&t instanceof Hn&&(t.dataSources.some(n=>n.spec.url.length!==0)||Ps(e))}set layer(e){if(e===this.layer_)return;const t=this.layer_;if(t!==void 0&&(this.existingLayerDisposer(),this.existingLayerDisposer=void 0,this.maybeDeleteNewLayer(t)),this.layer_=e,e!==void 0){const n=()=>{this.layer_=void 0,this.visible=!1,this.existingLayerDisposer=void 0,this.changed.dispatch()};e.registerDisposer(n);const s=e.specificationChanged.add(()=>{this.changed.dispatch()});this.existingLayerDisposer=()=>{const r=e.layer;if(r!==null){const o=r.tool.value;o!==void 0&&o.deactivate()}e.unregisterDisposer(n),s()}}else this.location.visible=!1;this.changed.dispatch()}toJSON(){const e=this.location.toJSON();return this.layer!==void 0&&(e.layer=this.layer.name),(0,p.Zu)(e)}restoreState(e){if(e===void 0){this.reset();return}(0,p.Rf)(e),this.location.restoreState(e);const t=(0,p.cQ)(e,"layer",p.z$),n=t!==void 0?this.layerManager.getLayerByName(t):void 0;n===void 0&&(this.visible=!1),this.layer=n}reset(){this.location.reset(),this.layer=void 0}}class IT extends D.O8{constructor(e,t){super(),this.layerManager=e,this.filter=t,this.changed=new j.IY,this.validate=(0,xe.A)(()=>{const{layerName_:n}=this;if(n!==void 0){const s=this.layerManager.getLayerByName(n);s!==void 0&&this.filter(s)?(this.layer_=s,this.changed.dispatch()):(this.layer_=void 0,this.layerName_=void 0,this.changed.dispatch())}},0),this.registerDisposer(e),this.registerDisposer(e.specificationChanged.add(()=>{const{layer_:n}=this;if(n!==void 0)if(!this.layerManager.layerSet.has(n)||!this.filter(n))this.layer_=void 0,this.layerName_=void 0,this.changed.dispatch();else{const{name:s}=n;s!==this.layerName_&&(this.layerName_=s,this.changed.dispatch())}}))}get layer(){return this.layer_}get layerName(){return this.layerName_}set layer(e){this.layer_!==e&&(e!==void 0&&this.layerManager.layerSet.has(e)&&this.filter(e)?(this.layer_=e,this.layerName_=e.name):(this.layer_=void 0,this.layerName_=void 0),this.changed.dispatch())}set layerName(e){e!==this.layerName_&&(this.layer_=void 0,this.layerName_=e,this.changed.dispatch(),this.validate())}restoreState(e){const t=(0,p.z$)(e);this.layerName=t}toJSON(){const{layer_:e}=this;return e!==void 0?e.name:this.layerName_}reset(){this.layerName_=void 0,this.layer_=void 0,this.changed.dispatch()}}class kg extends D.O8{constructor(e,t,n,s){super(),this.layerManager=e,this.layer=t,this.predicate=n,this.getGroup=s,this.linkedLayers_=new Set,this.changed=new j.IY,this.linkedLayersChanged=new j.IY,this.root_=t;const r=this;this.root={get value(){return r.root_},changed:r.changed}}get linkedLayers(){return this.linkedLayers_}get rootGroup(){return this.getGroup(this.root.value)}reset(){this.isolate()}restoreState(e){if(e===void 0)return;const t=(0,p.zr)(e);this.linkByName(t)}toJSON(){const{root:{value:e}}=this;if(e!==this.layer)return e.managedLayer.name}isolate(e=!0){const{getGroup:t,layer:n,root_:s}=this;if(s===n){const{linkedLayers_:o}=this;if(o.size!==0){for(const a of o){const l=t(a);l.root_=a,l.changed.dispatch()}o.clear(),this.linkedLayersChanged.dispatch()}return}const r=t(s);r.linkedLayers_.delete(n),r.linkedLayersChanged.dispatch(),this.root_=n,e&&this.changed.dispatch()}linkByName(e){const{layer:t}=this,{managedLayer:n}=t,{layerManager:s}=this,r=s.getLayerByName(e);if(r===void 0||r===n)return;const o=r.layer;o!==null&&this.predicate(o)&&this.linkToLayer(o)}linkToLayer(e){if(e===this.layer||this.root_===e)return;this.root_!==this.layer&&this.isolate(!1);const{getGroup:t}=this,n=t(e).root_;if(n===this.layer)return;const s=t(n);s.linkedLayers_.add(this.layer),s.linkedLayersChanged.dispatch(),this.root_=n,this.changed.dispatch()}disposed(){this.isolate(!1)}}function Lg(i,e){const t=(0,p.MM)(e,"type",p.zr,"auto");i.archived=(0,p.MM)(e,"archived",p.aO,!1),i.archived?i.visible=!1:i.visible=(0,p.MM)(e,"visible",p.aO,!0);const n=na.get(t)||Hn;return i.layer=new n(i),e}function Pg(i,e){try{const t=i.layer;if(t===null)return;t.restoreState(e),t.initializationDone()}catch(t){throw Ps(i),t}}function Ag(i,e){try{(0,p.Rf)(e),Lg(i,e),Pg(i,e)}catch(t){throw Ps(i),t}}function RT(i,e){try{Ag(i,e)}catch(t){new Se().setErrorMessage(t instanceof Error?t.message:""+t)}}function Mg(i,e,t){const n=new Uc(e,i);return Ag(n,t),n}class Ng extends D.O8{constructor(){super(...arguments),this.changed=new j.IY}}class kT extends Ng{constructor(e,t,n,s,r,o,a,l,c){super(),this.display=e,this.dataSourceProviderRegistry=t,this.layerManager=n,this.chunkManager=s,this.selectionState=r,this.selectedLayer=o,this.coordinateSpace=a,this.globalPosition=l,this.toolBinder=c,this.coordinateSpaceCombiner=new Fl(this.coordinateSpace,pw),this.subsets=new Set,this.layerSelectedValues=this.selectionState.layerSelectedValues,this.registerDisposer(n.layersChanged.add(this.changed.dispatch)),this.registerDisposer(n.specificationChanged.add(this.changed.dispatch))}get rpc(){return this.chunkManager.rpc}get root(){return this}reset(){this.layerManager.clear()}restoreState(e){this.layerManager.clear();let t;Array.isArray(e)?t=e:((0,p.Rf)(e),t=Object.entries(e).map(([s,r])=>typeof r=="string"?{name:s,source:r}:((0,p.Rf)(r),{...r,name:s})));const n=[];for(const s of t){(0,p.Rf)(s);const r=this.layerManager.getUniqueLayerName((0,p.cQ)(s,"name",p.zr)),o=new Uc(r,this);try{Lg(o,s),this.layerManager.addManagedLayer(o),n.push({managedLayer:o,spec:s})}catch(a){o.dispose(),new Se().setErrorMessage(`Error creating layer ${JSON.stringify(r)}: `+(a instanceof Error)?a.message:""+a)}}for(const{managedLayer:s,spec:r}of n)try{Pg(s,r)}catch(o){new Se().setErrorMessage(`Error creating layer ${JSON.stringify(name)}: `+(o instanceof Error)?o.message:""+o)}}add(e,t){this.layerManager.managedLayers.indexOf(e)===-1&&(e.name=this.layerManager.getUniqueLayerName(e.name)),this.layerManager.addManagedLayer(e,t)}toJSON(){const e=[];let t=0;for(const n of this.layerManager.managedLayers){const s=n.toJSON();s!=null&&(e.push(s),++t)}if(t!==0)return e}get rootLayers(){return this.layerManager}}class Og extends Ng{constructor(e){super(),this.master=e,this.changed=new j.IY,this.layerManager=this.registerDisposer(new Tg),this.registerDisposer(e);const{layerManager:t}=this;this.registerDisposer(t.layersChanged.add(this.changed.dispatch)),this.registerDisposer(t.specificationChanged.add(this.changed.dispatch)),e.subsets.add(this)}get rpc(){return this.master.rpc}get dataSourceProviderRegistry(){return this.master.dataSourceProviderRegistry}get chunkManager(){return this.master.chunkManager}get layerSelectedValues(){return this.master.layerSelectedValues}get root(){return this.master}disposed(){super.disposed(),this.master.subsets.delete(this)}reset(){this.layerManager.clear()}restoreState(e){const t=this.master.layerManager,n=[];for(const s of new Set((0,p.$v)(e,p.zr))){const r=t.getLayerByName(s);if(r===void 0)throw new Error(`Undefined layer referenced in subset specification: ${JSON.stringify(s)}`);r.archived||n.push(r)}this.layerManager.clear();for(const s of n)this.layerManager.addManagedLayer(s.addRef())}toJSON(){return this.layerManager.managedLayers.map(e=>e.name)}add(e,t){this.master.layerManager.managedLayers.indexOf(e)===-1&&(e.name=this.master.layerManager.getUniqueLayerName(e.name),this.master.layerManager.addManagedLayer(e.addRef())),this.layerManager.addManagedLayer(e,t)}get rootLayers(){return this.master.rootLayers}}const na=new Map,Gc=new Map,Vg=[i=>{const{volume:e}=i;if(e===void 0)return;const t=Gc.get(e.volumeType);if(t!==void 0)return{layerConstructor:t,priority:0}}];function Ui(i,e=i.type){na.set(e,i)}function ia(i){Vg.push(i)}function _g(i,e){Gc.set(i,e)}function zc(i,e){const t=i.layer;if(t===null)return;const n=t.toJSON(),s=new e(i);s.restoreState(n),s.initializationDone(),i.layer=s}function Bg(i,e){return e!==i.name?(e=i.manager.root.layerManager.getUniqueLayerName(e),i.name=e,i.layerChanged.dispatch(),!0):!1}function Ps(i){if(!i.wasDisposed)for(const e of i.containers)e.removeManagedLayer(i)}function sa(i,e){return i===void 0?e:e===void 0?i:i.priority<e.priority?e:i}function Fg(i){let e;for(const n of Vg)e=sa(e,n(i));const{volume:t}=i;if(t!==void 0){const n=Gc.get(t.volumeType);n!==void 0&&(e=sa(e,{layerConstructor:n,priority:0}))}return e}function D_(i){let e;for(const t of i.dataSources){const{loadState:n}=t;if(!(n===void 0||n.error!==void 0))for(const s of n.subsources){const{subsourceEntry:r}=s,{subsource:o}=r;s.enabled&&(e=sa(e,Fg(o)))}}return e?.layerConstructor}function Ug(i){let e;for(const t of i){const{subsourceEntry:n}=t,{subsource:s}=n;e=sa(e,Fg(s))}return e}class Hn extends Ln{activateDataSubsources(e){this.detectedLayerConstructor=Ug(e)?.layerConstructor}}Hn.type="new",Hn.typeAbbreviation="new";class Wc extends Ln{activateDataSubsources(e){const t=Ug(e)?.layerConstructor;t!==void 0&&zc(this.managedLayer,t)}}Wc.type="auto",Wc.typeAbbreviation="auto";function $g(i,e){const t=Mg(i,"new layer",{type:"new"});i.add(t),e.layer=t,e.visible=!0}Ui(Hn),Ui(Wc);const Hc="selectedAlpha",Jc="notSelectedAlpha",jc="objectAlpha",Yc="saturation",Qc="hoverHighlight",qc="hideSegmentZero",Kc="baseSegmentColoring",Xc="ignoreNullVisibleSet",LT="mesh",PT="skeletons",Zc="segments",ra="equivalences",ed="colorSeed",Gg="segmentColors",td="meshRenderScale",nd="crossSectionRenderScale",oa="skeletonRendering",AT="skeletonShader",zg="segmentQuery",id="meshSilhouetteRendering",Wg="linkedSegmentationGroup",Hg="linkedSegmentationColorGroup",sd="segmentDefaultColor",Jg="anchorSegment",jg="skeletonShaderControl";/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Yg(i,e,t,n){const s=document.createElement("label");s.classList.add("neuroglancer-layer-control-container");const r=document.createElement("div");r.classList.add("neuroglancer-layer-control-label-container");const o=document.createElement("div");o.classList.add("neuroglancer-layer-control-label"),r.appendChild(o);const a=document.createElement("div");a.classList.add("neuroglancer-layer-control-label-text-container"),a.appendChild(document.createTextNode(t.label)),o.appendChild(a),t.title&&(o.title=t.title),s.appendChild(r);const{control:l,controlElement:c}=t.makeControl(e,i,{labelContainer:r,labelTextContainer:a,display:e.manager.root.display,visibility:n});return c.classList.add("neuroglancer-layer-control-control"),s.appendChild(c),{controlContainer:s,label:o,labelContainer:r,labelTextContainer:a,control:l}}class Qg extends vs{constructor(e,t){super(e),this.options=t}activate(e){const{options:t}=this,{layer:n}=this,{isValid:s}=t;if(s!==void 0&&!s(n).value)return;const{header:r,body:o}=Ss(e),{controlContainer:a,control:l,labelContainer:c}=Yg(e,n,t,new ht(ht.VISIBLE));r.appendChild(c),o.appendChild(a),t.activateTool(e,l)}get description(){const{options:e}=this;return e.toolDescription??e.label}toJSON(){return this.options.toolJson}}function qg(i,e,t,n){const{controlContainer:s,label:r}=Yg(i,e,t,n);return s.classList.add("neuroglancer-layer-options-control-container"),r.prepend(i.registerDisposer(new Cf(e.toolBinder,t.toolJson)).element),s}function rd(i,e,t,n){const{isValid:s}=n;return s===void 0?qg(i,e,n,t):i.registerDisposer(new zt(s(e),(r,o,a)=>{r&&o.appendChild(qg(a,e,n,t))},t)).element}function Kg(i,e){const{toolJson:t}=e,n=typeof t=="string"?t:t.type;Rn(i,n,s=>new Qg(s,e))}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function kr(i){return{makeControl:(e,t)=>{const n=i(e),s=t.registerDisposer(new Un(n));return{control:s,controlElement:s.element}},activateTool:(e,t)=>{t.model.value=!t.model.value}}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const MT=Pe.fromObject({"at:shift+wheel":{action:"adjust-via-wheel"}});function od(i){return{makeControl:(e,t)=>{const n=i(e),s=t.registerDisposer(new Po(n));return{control:s,controlElement:s.element}},activateTool:(e,t)=>{e.bindInputEventMap(MT),e.bindAction("adjust-via-wheel",n=>{n.stopPropagation(),n.preventDefault(),t.adjustViaWheel(n.detail)})}}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class NT extends D.O8{constructor(e,{min:t=0,max:n=1,step:s=.01}={}){super(),this.value=e,this.element=document.createElement("label"),this.inputElement=document.createElement("input"),this.numericInputElement=document.createElement("input");const{element:r,inputElement:o,numericInputElement:a}=this;r.className="range-slider";const l=d=>{d.min=""+t,d.max=""+n,d.step=""+s,d.valueAsNumber=this.value.value,this.registerEventListener(d,"change",()=>this.inputValueChanged(d)),this.registerEventListener(d,"input",()=>this.inputValueChanged(d)),this.registerEventListener(d,"wheel",u=>{this.adjustViaWheel(d,u)})};o.type="range",l(o),a.type="number";const c=Math.max(t.toString().length,n.toString().length,Math.min(n,t+s).toString().length,Math.max(t,n-s).toString().length);a.style.width=c+2+"ch",l(a),r.appendChild(o),r.appendChild(a),e.changed.add(()=>{this.inputElement.valueAsNumber=this.value.value,this.numericInputElement.valueAsNumber=this.value.value})}inputValueChanged(e){this.value.value=e.valueAsNumber}adjustViaWheel(e,t){const n=this.inputElement,{deltaY:s}=t;s>0?(n.stepUp(),this.inputValueChanged(e)):s<0&&(n.stepDown(),this.inputValueChanged(e))}disposed(){lt(this.element),super.disposed()}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const OT=Pe.fromObject({"at:shift+wheel":{action:"adjust-via-wheel"}});function Jn(i){return{makeControl:(e,t)=>{const{value:n,options:s}=i(e),r=t.registerDisposer(new NT(n,s));return{control:r,controlElement:r.element}},activateTool:(e,t)=>{e.bindInputEventMap(OT),e.bindAction("adjust-via-wheel",n=>{n.stopPropagation(),n.preventDefault(),t.adjustViaWheel(t.inputElement,n.detail)})}}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Xg(i,e){let t="";for(let n=0;n<=e&&(t=i.toFixed(n),parseFloat(t)!==i);++n);return t}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const VT=200,Zg=Pe.fromObject({mousedown0:{action:"set"},wheel:{action:"adjust-via-wheel"},dblclick0:{action:"reset"}});function _T(i){if(i<1||i>1024){const e=Math.log2(i)|0,t=i/2**e;return`${Xg(t,1)}p${e}`}return Math.round(i)+""}class aa extends D.O8{constructor(e,t){super(),this.histogram=e,this.target=t,this.label=document.createElement("div"),this.element=document.createElement("div"),this.canvas=document.createElement("canvas"),this.legend=document.createElement("div"),this.legendRenderScale=document.createElement("div"),this.legendSpatialScale=document.createElement("div"),this.legendChunks=document.createElement("div"),this.logScaleOrigin=Is,this.unitOfTarget="px",this.ctx=this.canvas.getContext("2d"),this.hoverTarget=new A.B0(void 0),this.throttledUpdateView=this.registerCancellable((0,Ls.A)(()=>this.debouncedUpdateView(),VT,{leading:!0,trailing:!0})),this.debouncedUpdateView=this.registerCancellable((0,xe.A)(()=>this.updateView(),0));const{canvas:n,label:s,element:r,legend:o,legendRenderScale:a,legendSpatialScale:l,legendChunks:c}=this;s.className="neuroglancer-render-scale-widget-prompt",r.className="neuroglancer-render-scale-widget",r.title=Zg.describe(),o.className="neuroglancer-render-scale-widget-legend",r.appendChild(s),r.appendChild(n),r.appendChild(o),a.title="Target resolution of data in screen pixels",c.title="Number of chunks rendered",o.appendChild(a),o.appendChild(c),o.appendChild(l),this.registerDisposer(e.changed.add(this.throttledUpdateView)),this.registerDisposer(e.visibility.changed.add(this.debouncedUpdateView)),this.registerDisposer(t.changed.add(this.debouncedUpdateView)),this.registerDisposer(new fn(n,Zg)),this.registerDisposer(t.changed.add(this.debouncedUpdateView)),this.registerDisposer(this.hoverTarget.changed.add(this.debouncedUpdateView));const d=h=>{const f=h.offsetX/n.width*ft;return HE(f,this.logScaleOrigin)};this.registerEventListener(n,"pointermove",h=>{this.hoverTarget.value=[d(h),h.offsetY]}),this.registerEventListener(n,"pointerleave",()=>{this.hoverTarget.value=void 0}),this.registerDisposer(X(n,"set",h=>{this.target.value=d(h.detail)})),this.registerDisposer(X(n,"adjust-via-wheel",h=>{this.adjustViaWheel(h.detail)})),this.registerDisposer(X(n,"reset",h=>{this.reset(),h.preventDefault()}));const u=new ResizeObserver(()=>this.debouncedUpdateView());u.observe(n),this.registerDisposer(()=>u.disconnect()),this.updateView()}adjustViaWheel(e){const t=this.getWheelMoveValue(e);if(t===0)return;this.hoverTarget.value=void 0;const n=Math.round(this.logScaleOrigin+ft*xr),s=Le([2**this.logScaleOrigin,2**(n-1)],this.target.value*2**Math.sign(t));this.target.value=s,e.preventDefault()}getWheelMoveValue(e){return e.deltaY}reset(){this.hoverTarget.value=void 0,this.target.reset()}updateView(){const{ctx:e}=this,{canvas:t}=this,n=t.width=t.offsetWidth,s=t.height=t.offsetHeight,r=this.target.value,o=this.hoverTarget.value;{const{legendRenderScale:C}=this,k=o===void 0?r:o[0],T=_T(k);C.textContent=T+" "+this.unitOfTarget}function a(C){return C*n/ft}e.clearRect(0,0,n,s);const{histogram:l}=this,{value:c,spatialScales:d}=l;l.visibility.visible||c.fill(0);const u=Array.from(d.keys());u.sort();const h=w.eR.create();let f=1;const m=d.size;let g=0,v=0;for(let C=0;C<ft;++C){let k=0;for(let T=0;T<m;++T){const L=T*ft*2+C,_=c[L],R=c[L+ft];g+=_,v+=R,k+=_+R}f=Math.max(k,f)}v-=l.fakeChunkCount;const S=s/Math.log(1+f);function x(C){return s-Math.log(1+C)*S}let b;if(o!==void 0){const C=Math.floor(jo(o[0],this.logScaleOrigin));if(C>=0&&C<ft){let k=0;const T=o[1];for(let L=m-1;L>=0;--L){const _=u[L],P=2*d.get(_)*ft+C,V=c[P]+c[P+ft];if(V===0)continue;const $=Math.round(x(k));if(k+=V,Math.round(x(k))<=T&&T<=$){b=_;break}}}}if(b!==void 0){g=0,v=0;const k=2*d.get(b)*ft;for(let T=0;T<ft;++T){const L=k+T;g+=c[L],v+=c[L+ft]}Number.isFinite(b)?this.legendSpatialScale.textContent=Ci(b,"m",{precision:2,elide1:!1}):this.legendSpatialScale.textContent="unknown"}else this.legendSpatialScale.textContent="";this.legendChunks.textContent=`${g}/${g+v}`;const E=u.map(C=>{const k=C===b?.5:1;let T;Number.isFinite(C)?T=(Math.log2(C)*.1%1+1)%1:T=0,Io(h,T,k,1);const L=ze(h);Io(h,T,k,.5);const _=ze(h);return[L,_]});for(let C=0;C<ft;++C){let k=0;for(let T=m-1;T>=0;--T){const L=u[T],R=d.get(L)*ft*2+C,P=c[R],V=c[R+ft],$=P+V;if($===0)continue;const Q=Math.round(a(C)),K=Math.round(a(C+1)),ee=Math.round(x(k));k+=$;const ce=Math.round(x(k)),fe=(P*ce+V*ee)/$;e.fillStyle=E[T][1],e.fillRect(Q,ce,K-Q,fe-ce),e.fillStyle=E[T][0],e.fillRect(Q,fe,K-Q,ee-fe)}}{const C=r;e.fillStyle="#fff";const k=a(jo(C,this.logScaleOrigin));e.fillRect(Math.floor(k),0,1,s)}if(o!==void 0){const C=o[0];e.fillStyle="#888";const k=a(jo(C,this.logScaleOrigin));e.fillRect(Math.floor(k),0,1,s)}}}class BT extends aa{constructor(){super(...arguments),this.unitOfTarget="samples",this.logScaleOrigin=1}getWheelMoveValue(e){return-e.deltaY}}const FT=Pe.fromObject({"at:shift+wheel":{action:"adjust-via-wheel"},"at:shift+dblclick0":{action:"reset"}});function la(i,e=aa){return{makeControl:(t,n)=>{const{histogram:s,target:r}=i(t),o=n.registerDisposer(new e(s,r));return{control:o,controlElement:o.element}},activateTool:(t,n)=>{t.bindInputEventMap(FT),t.bindAction("adjust-via-wheel",s=>{s.stopPropagation(),s.preventDefault(),n.adjustViaWheel(s.detail)}),t.bindAction("reset",s=>{s.stopPropagation(),s.preventDefault(),n.reset()})}}}var UT=G(8682);/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const $T=Pe.fromObject({"at:shift+wheel":{action:"adjust-hue-via-wheel"}});function em(i){return{makeControl:(e,t)=>{const n=i(e),s=t.registerDisposer(new Ro(n));return{control:s,controlElement:s.element}},activateTool:(e,t)=>{e.bindInputEventMap($T),e.bindAction("adjust-via-wheel",n=>{n.stopPropagation(),n.preventDefault(),t.adjustHueViaWheel(n.detail)})}}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tm extends D.O8{constructor(e){super(),this.model=e,this.element=document.createElement("input"),this.registerDisposer(e.changed.add(()=>this.updateView()));const{element:t}=this;t.type="text",this.registerEventListener(t,"change",()=>this.updateModel()),this.updateView()}disposed(){lt(this.element)}updateView(){this.element.value=(this.model.value??"")+""}updateModel(){try{this.model.restoreState(this.element.value)}catch{}this.updateView()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ca(i,e){e?i.displayState.segmentDefaultColor.value=w.eR.fromValues(1,0,0):i.displayState.segmentDefaultColor.value=void 0}function GT(){const i=e=>{e.displayState.segmentationColorGroupState.value.segmentColorHash.randomize()};return{makeControl:(e,t,{labelTextContainer:n})=>{const s=document.createElement("input");s.type="radio",s.addEventListener("change",()=>{ca(e,!s.checked)}),n.prepend(s);const r=document.createElement("div");r.classList.add("neuroglancer-segmentation-color-seed-control");const o=t.registerDisposer(new tm(e.displayState.segmentColorHash));r.appendChild(o.element);const a=_e({svg:UT,title:"Randomize",onClick:()=>i(e)});return r.appendChild(a),t.registerDisposer((0,A.W1)(l=>{const c=l===void 0;r.style.visibility=c?"":"hidden",s.checked=c},e.displayState.segmentDefaultColor)),{controlElement:r,control:o}},activateTool:e=>{const{layer:t}=e.tool;ca(t,!1),i(t)}}}function zT(){const i=em(e=>e.displayState.segmentDefaultColor);return{...i,makeControl:(e,t,n)=>{const s=i.makeControl(e,t,n),{controlElement:r}=s,o=document.createElement("input");return o.type="radio",o.addEventListener("change",()=>{ca(e,o.checked),o.checked&&r.click()}),n.labelTextContainer.prepend(o),t.registerDisposer((0,A.W1)(a=>{const l=a!==void 0;r.style.visibility=l?"":"hidden",o.checked=l},e.displayState.segmentDefaultColor)),s},activateTool:(e,t)=>{ca(e.tool.layer,!0),i.activateTool(e,t)}}}const nm=[{label:"Color seed",title:"Color segments based on a hash of their id",toolJson:ed,...GT()},{label:"Fixed color",title:"Use a fixed color for all segments without an explicitly-specified color",toolJson:sd,...zT()},{label:"Saturation",toolJson:Yc,title:"Saturation of segment colors",...Jn(i=>({value:i.displayState.saturation}))},{label:"Opacity (on)",toolJson:Hc,isValid:i=>i.has2dLayer,title:"Opacity in cross-section views of segments that are selected",...Jn(i=>({value:i.displayState.selectedAlpha}))},{label:"Opacity (off)",toolJson:Jc,isValid:i=>i.has2dLayer,title:"Opacity in cross-section views of segments that are not selected",...Jn(i=>({value:i.displayState.notSelectedAlpha}))},{label:"Resolution (slice)",toolJson:nd,isValid:i=>i.has2dLayer,...la(i=>({histogram:i.sliceViewRenderScaleHistogram,target:i.sliceViewRenderScaleTarget}))},{label:"Resolution (mesh)",toolJson:td,isValid:i=>i.has3dLayer,...la(i=>({histogram:i.displayState.renderScaleHistogram,target:i.displayState.renderScaleTarget}))},{label:"Opacity (3d)",toolJson:jc,isValid:i=>i.has3dLayer,title:"Opacity of meshes and skeletons",...Jn(i=>({value:i.displayState.objectAlpha}))},{label:"Silhouette (3d)",toolJson:id,isValid:i=>i.has3dLayer,title:"Set to a non-zero value to increase transparency of object faces perpendicular to view direction",...Jn(i=>({value:i.displayState.silhouetteRendering,options:{min:0,max:WT,step:.1}}))},{label:"Hide segment ID 0",toolJson:qc,title:"Disallow selection and display of segment id 0",...kr(i=>i.displayState.hideSegmentZero)},{label:"Base segment coloring",toolJson:Kc,title:"Color base segments individually",...kr(i=>i.displayState.baseSegmentColoring)},{label:"Show all by default",title:"Show all segments if none are selected",toolJson:Xc,...kr(i=>i.displayState.ignoreNullVisibleSet)},{label:"Highlight on hover",toolJson:Qc,title:"Highlight the segment under the mouse pointer",...kr(i=>i.displayState.hoverHighlight)},...im("2d"),...im("3d")],WT=10;function im(i){return[{label:`Skeleton mode (${i})`,toolJson:`${oa}.mode${i}`,isValid:e=>e.hasSkeletonsLayer,...od(e=>e.displayState.skeletonRenderingOptions[`params${i}`].mode)},{label:`Line width (${i})`,toolJson:`${oa}.lineWidth${i}`,isValid:e=>e.hasSkeletonsLayer,toolDescription:`Skeleton line width (${i})`,title:`Skeleton line width (${i})`,...Jn(e=>({value:e.displayState.skeletonRenderingOptions[`params${i}`].lineWidth,options:{min:1,max:40,step:1}}))}]}function HT(i){for(const e of nm)Kg(i,e)}var yn=G(3708);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function JT(i,e,t){return i&1|e<<1&2|t<<2&4}function I_(i,e,t,n){const s=Math.max(e,t,n);let r=0,o=i.low,a=0,l=0,c=0;for(let d=0;d<s;++d){if(d<e){const u=o>>>r&1;a|=u<<d,r===31?(r=0,o=i.high):++r}if(d<t){const u=o>>>r&1;l|=u<<d,r===31?(r=0,o=i.high):++r}if(d<n){const u=o>>>r&1;c|=u<<d,r===31?(r=0,o=i.high):++r}}return Uint32Array.of(a,l,c)}function R_(i,e,t,n,s,r,o){const a=Math.max(e,t,n);let l=0,c=0,d=!1;function u(h){c|=(h&1)<<l,++l===32&&(i.low=c>>>0,c=0,l=0,d=!0)}for(let h=0;h<a;++h)h<e&&u(s>>h&1),h<t&&u(r>>h&1),h<n&&u(o>>h&1);return d?i.high=c>>>0:(i.high=0,i.low=c>>>0),i}function k_(i,e,t){let n=0;const s=e.length;let r=0,o=!1;function a(l){r|=(l&1)<<n,++n===32&&(i.low=r>>>0,r=0,n=0,o=!0)}for(let l=0;l<32;++l)for(let c=0;c<s;++c)t[c]-1>>>l&&a(e[c]>>>l);return o?i.high=r>>>0:(i.high=0,i.low=r>>>0),i}function sm(i,e){return i<e&&i<(i^e)}function L_(i,e,t,n,s,r){let o=t,a=r;return sm(o^a,e^s)&&(o=e,a=s),sm(o^a,i^n)&&(o=i,a=n),o<a}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const da=!1;function jT(i,e,t,n,s,r,o){const{octree:a,lodScales:l,chunkGridSpatialOrigin:c,chunkShape:d}=i,u=l.length-1,h=e[0],f=e[4],m=e[8],g=e[1],v=e[5],y=e[9],S=e[3],x=e[7],b=e[11],E=e[15],C=S>0?0:1,k=x>0?0:1,T=b>0?0:1,L=t[4*4],_=t[4*4+1],R=t[4*4+2],P=t[4*4+3];function V(kt,Ue,et){return S*kt+x*Ue+b*et+E}function $(kt,Ue,et,Lt,Xn,Zr){return V(kt+C*(Lt-kt),Ue+k*(Xn-Ue),et+T*(Zr-et))}const Q=V(-P*L,-P*_,-P*R),K=i.clipLowerBound[0],ee=i.clipLowerBound[1],ce=i.clipLowerBound[2],fe=i.clipUpperBound[0],le=i.clipUpperBound[1],ve=i.clipUpperBound[2],Ie=Math.sqrt((h*s)**2+(g*r)**2),mt=Math.sqrt((f*s)**2+(v*r)**2),Fe=Math.sqrt((m*s)**2+(y*r)**2),Ct=Math.max(Ie,mt,Fe);function ln(kt,Ue,et){const Lt=1<<kt,Xn=Ue*5,Zr=a[Xn],eo=a[Xn+1],QV=a[Xn+2],qV=a[Xn+3],Ab=a[Xn+4];let to=Zr*Lt*d[0]+c[0],no=eo*Lt*d[1]+c[1],io=QV*Lt*d[2]+c[2],vl=to+Lt*d[0],yl=no+Lt*d[1],Sl=io+Lt*d[2];if(to=Math.max(to,K),no=Math.max(no,ee),io=Math.max(io,ce),vl=Math.min(vl,fe),yl=Math.min(yl,le),Sl=Math.min(Sl,ve),(0,w.T_)(to,no,io,vl,yl,Sl,t)){const gh=Math.max(Q,$(to,no,io,vl,yl,Sl))/Ct;if(et===0||gh*n<et){const Ks=l[kt];if(Ks!==0&&o(kt,Ue,Ks/gh,Ab>>>31),kt>0&&(Ks===0||gh*n<Ks)){const KV=Ks===0?et:Ks,XV=(Ab&2147483647)>>>0;for(let mh=qV;mh<XV;++mh)ln(kt-1,mh,KV)}}}}ln(u,a.length/5-1,0)}function rm(i,e,t,n,s,r,o,a){const{lodScales:l}=i;let c=0;for(;c+1<l.length&&l[c+1]!==0;)++c;const d=3,u=[];let h=0,f=0;function m(y,S){for(da&&console.log(`emitChunksUpTo: stackDepth=${h}, targetStackIndex=${y}, subChunkIndex=${S}, priorSubChunkIndex=${f}`);;){if(h===0)return;const x=h-1,b=c-x,E=u[x*d],C=b===0?1:8,k=u[x*d+1],T=u[x*d+2];if(y===h){const L=S&C-1;f!==L&&E!==-1&&(da&&console.log(`  drawing chunk because priorSubChunkIndex (${f}) != endSubChunk (${L})`),a(b,E,f,L,T)),f=L+1;return}f!==C&&E!==-1&&a(b,E,f,C,T),f=k+1,--h}}let g=0;da&&(console.log(""),console.log("Starting to draw"));const{octree:v}=i;jT(i,e,t,n,s,r,(y,S,x,b)=>{if(!b&&!o(y,S,x)){g=Math.max(y,g);return}if(y<g)return;g=0;const E=S*5,C=v[E],k=v[E+1],T=v[E+2],L=JT(C,k,T),_=c-y;m(_,L);const R=_*d;u[R]=b?-1:S,u[R+1]=L,u[R+2]=x,da&&console.log(`Adding to stack: lod=${y}, row=${u[R]}, subChunkIndex=${L}`),f=0,h=_+1}),m(0,0)}function YT(i){if(i.length%5!==0)throw new Error("Invalid length");const e=i.length/5,t=new Set;function n(s){if(t.has(s))throw new Error("Previously seen node");if(t.add(s),s<0||s>=e)throw new Error("Invalid node reference");const r=i[s*5],o=i[s*5+1],a=i[s*5+2],l=i[s*5+3],c=i[s*5+4];if(l<0||c<0||c<l||c>e||l+8<c)throw new Error("Invalid child references");for(let d=l;d<c;++d){const u=i[d*5],h=i[d*5+1],f=i[d*5+2];if(u>>>1!==r||h>>>1!==o||f>>>1!==a)throw new Error("invalid child");n(d)}}if(e!==0&&(n(e-1),t.size!==e))throw new Error("Orphan nodes in octree")}function om(i,e,t){return`${i}/${e}:${t}`}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class $i extends up{draw(e,t){}isReady(e,t){return!0}get transparentPickEnabled(){return!0}}var ua=G(9254);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ad=3,QT=.8,di=!1;let Pn=0,An=0,am=0,lm=0;class Lr{constructor(e=Lr.generateHashSeeds(ad)){this.hashSeeds=e,this.loadFactor=QT,this.size=0,this.emptyLow=4294967295,this.emptyHigh=4294967295,this.maxRehashAttempts=5,this.maxAttempts=5,this.generation=0,this.mungedEmptyKey=-1;let t=8;for(;t<2*e.length;)t*=2;this.allocate(t)}updateHashFunctions(e){this.hashSeeds=Lr.generateHashSeeds(e),this.mungedEmptyKey=-1}tableWithMungedEmptyKey(e){const t=this.hashSeeds.length,n=new Array(t);for(let l=0;l<t;++l)n[l]=this.getHash(l,this.emptyLow,this.emptyHigh);let{mungedEmptyKey:s}=this;if(s===-1)e:for(;;){s=Math.random()*16777216>>>0;for(let l=0;l<t;++l){const c=this.getHash(l,s,s);for(let d=0;d<t;++d)if(n[d]===c)continue e}this.mungedEmptyKey=s;break}const{table:r,emptyLow:o,emptyHigh:a}=this;for(let l=0;l<t;++l){const c=n[l];r[c]===o&&r[c+1]===a&&(r[c]=s,r[c+1]=s)}try{e(r)}finally{for(let l=0;l<t;++l){const c=n[l];r[c]===s&&r[c+1]===s&&(r[c]=o,r[c+1]=a)}}}static generateHashSeeds(e=ad){return ot(new Uint32Array(e))}getHash(e,t,n){let s=this.hashSeeds[e];return s=(0,ua._)(s,t),s=(0,ua._)(s,n),this.entryStride*(s&this.tableSize-1)}*keys(){const{emptyLow:e,emptyHigh:t,entryStride:n}=this,{table:s}=this;for(let r=0,o=s.length;r<o;r+=n){const a=s[r],l=s[r+1];(a!==e||l!==t)&&(yield new M.R(a,l))}}*unsafeKeys(e=new M.R){const{emptyLow:t,emptyHigh:n,entryStride:s}=this,{table:r}=this;for(let o=0,a=r.length;o<a;o+=s){const l=r[o],c=r[o+1];(l!==t||c!==n)&&(e.low=l,e.high=c,yield e)}}indexOfPair(e,t){const{table:n,emptyLow:s,emptyHigh:r}=this;if(e===s&&t===r)return-1;for(let o=0,a=this.hashSeeds.length;o<a;++o){const l=this.getHash(o,e,t);if(n[l]===e&&n[l+1]===t)return l}return-1}indexOf(e){return this.indexOfPair(e.low,e.high)}chooseAnotherEmptyKey(){const{emptyLow:e,emptyHigh:t,table:n,entryStride:s}=this;let r,o;for(;r=Math.random()*4294967296>>>0,o=Math.random()*4294967296>>>0,!(!(r===e&&o===t)&&!this.hasPair(r,o)););this.emptyLow=r,this.emptyHigh=o;for(let a=0,l=n.length;a<l;a+=s)n[a]===e&&n[a+1]===t&&(n[a]=r,n[a+1]=o)}has(e){return this.indexOf(e)!==-1}hasPair(e,t){return this.indexOfPair(e,t)!==-1}delete(e){const t=this.indexOf(e);if(t!==-1){const{table:n}=this;return n[t]=this.emptyLow,n[t+1]=this.emptyHigh,++this.generation,this.size--,!0}return!1}clearTable(){const{table:e,entryStride:t,emptyLow:n,emptyHigh:s}=this,r=e.length;for(let o=0;o<r;o+=t)e[o]=n,e[o+1]=s}clear(){return this.size===0?!1:(this.size=0,++this.generation,this.clearTable(),!0)}reserve(e){return e>this.capacity?(this.backupPending(),this.grow(e),this.restorePending(),!0):!1}swapPending(e,t){const n=Pn,s=An;this.storePending(e,t),e[t]=n,e[t+1]=s}storePending(e,t){Pn=e[t],An=e[t+1]}backupPending(){am=Pn,lm=An}restorePending(){Pn=am,An=lm}tryToInsert(){di&&console.log(`tryToInsert: ${Pn}, ${An}`);let e=0;const{emptyLow:t,emptyHigh:n,maxAttempts:s,table:r}=this,o=this.hashSeeds.length;let a=Math.floor(Math.random()*o);for(;;){const l=this.getHash(a,Pn,An);if(this.swapPending(r,l),Pn===t&&An===n)return!0;if(++e===s)break;a=(a+Math.floor(Math.random()*(o-1))+1)%o}return!1}allocate(e){this.tableSize=e;const{entryStride:t}=this;this.table=new Uint32Array(e*t),this.maxAttempts=e,this.clearTable(),this.capacity=e*this.loadFactor,this.mungedEmptyKey=-1}rehash(e,t){di&&console.log("rehash begin"),this.allocate(t),this.updateHashFunctions(this.hashSeeds.length);const{emptyLow:n,emptyHigh:s,entryStride:r}=this;for(let o=0,a=e.length;o<a;o+=r){const l=e[o],c=e[o+1];if((l!==n||c!==s)&&(this.storePending(e,o),!this.tryToInsert()))return di&&console.log("rehash failed"),!1}return di&&console.log("rehash end"),!0}grow(e){di&&console.log(`grow: ${e}`);const t=this.table;let{tableSize:n}=this;for(;n<e;)n*=2;for(;;){for(let s=0;s<this.maxRehashAttempts;++s)if(this.rehash(t,n)){di&&console.log("grow end");return}n*=2}}insertInternal(){for(++this.generation,Pn===this.emptyLow&&An===this.emptyHigh&&this.chooseAnotherEmptyKey(),++this.size>this.capacity&&(this.backupPending(),this.grow(this.tableSize*2),this.restorePending());!this.tryToInsert();)this.backupPending(),this.grow(this.tableSize),this.restorePending()}}class cm extends Lr{add(e){const{low:t,high:n}=e;return this.hasPair(t,n)?!1:(di&&console.log(`add: ${t},${n}`),Pn=t,An=n,this.insertInternal(),!0)}[Symbol.iterator](){return this.unsafeKeys()}}cm.prototype.entryStride=2;let Pr=0,Ar=0,dm=0,um=0;class ld extends Lr{set(e,t){const{low:n,high:s}=e;return this.hasPair(n,s)?!1:(di&&console.log(`add: ${n},${s} -> ${t.low},${t.high}`),Pn=n,An=s,Pr=t.low,Ar=t.high,this.insertInternal(),!0)}get(e,t){const n=this.indexOf(e);if(n===-1)return!1;const{table:s}=this;return t.low=s[n+2],t.high=s[n+3],!0}swapPending(e,t){const n=Pr,s=Ar;super.swapPending(e,t),e[t+2]=n,e[t+3]=s}storePending(e,t){super.storePending(e,t),Pr=e[t+2],Ar=e[t+3]}backupPending(){super.backupPending(),dm=Pr,um=Ar}restorePending(){super.restorePending(),Pr=dm,Ar=um}[Symbol.iterator](){return this.unsafeEntries()}*entries(){const{emptyLow:e,emptyHigh:t,entryStride:n}=this,{table:s}=this;for(let r=0,o=s.length;r<o;r+=n){const a=s[r],l=s[r+1];if(a!==e||l!==t){const c=new M.R(a,l),d=new M.R(s[r+2],s[r+3]);yield[c,d]}}}*unsafeEntries(e=[new M.R,new M.R]){const{emptyLow:t,emptyHigh:n,entryStride:s}=this,{table:r}=this,[o,a]=e;for(let l=0,c=r.length;l<c;l+=s){const d=r[l],u=r[l+1];(d!==t||u!==n)&&(o.low=d,o.high=u,a.low=r[l+2],a.high=r[l+3],yield e)}}}ld.prototype.entryStride=4;/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class As{}const Gi=[-1,WebGL2RenderingContext.RED_INTEGER,WebGL2RenderingContext.RG_INTEGER,WebGL2RenderingContext.RGB_INTEGER,WebGL2RenderingContext.RGBA_INTEGER],qT=[-1,WebGL2RenderingContext.RED,WebGL2RenderingContext.RG,WebGL2RenderingContext.RGB,WebGL2RenderingContext.RGBA],ha=["","r","rg","rgb","rgba"],KT=[-1,WebGL2RenderingContext.R8UI,WebGL2RenderingContext.RG8UI,WebGL2RenderingContext.RGB8UI,WebGL2RenderingContext.RGBA8UI],XT=[-1,WebGL2RenderingContext.R8I,WebGL2RenderingContext.RG8I,WebGL2RenderingContext.RGB8I,WebGL2RenderingContext.RGBA8I],ZT=[-1,WebGL2RenderingContext.R16UI,WebGL2RenderingContext.RG16UI,WebGL2RenderingContext.RGB16UI,WebGL2RenderingContext.RGBA16UI],eD=[-1,WebGL2RenderingContext.R16I,WebGL2RenderingContext.RG16I,WebGL2RenderingContext.RGB16I,WebGL2RenderingContext.RGBA16I],hm=[-1,WebGL2RenderingContext.R32UI,WebGL2RenderingContext.RG32UI,WebGL2RenderingContext.RGB32UI,WebGL2RenderingContext.RGBA32UI],tD=[-1,WebGL2RenderingContext.R32I,WebGL2RenderingContext.RG32I,WebGL2RenderingContext.RGB32I,WebGL2RenderingContext.RGBA32I],nD=[-1,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RG32F,WebGL2RenderingContext.RGB32F,WebGL2RenderingContext.RGBA32F];function pa(i){return i===I.FLOAT32?"":re[i]?"i":"u"}function zi(i,e,t=1){switch(e){case I.UINT8:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=KT[t],i.textureFormat=Gi[t],i.texelType=WebGL2RenderingContext.UNSIGNED_BYTE,i.arrayElementsPerTexel=t,i.arrayConstructor=Uint8Array,i.samplerPrefix="u",i;case I.INT8:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=XT[t],i.textureFormat=Gi[t],i.texelType=WebGL2RenderingContext.BYTE,i.arrayElementsPerTexel=t,i.arrayConstructor=Int8Array,i.samplerPrefix="i",i;case I.UINT16:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=ZT[t],i.textureFormat=Gi[t],i.texelType=WebGL2RenderingContext.UNSIGNED_SHORT,i.arrayElementsPerTexel=t,i.arrayConstructor=Uint16Array,i.samplerPrefix="u",i;case I.INT16:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=eD[t],i.textureFormat=Gi[t],i.texelType=WebGL2RenderingContext.SHORT,i.arrayElementsPerTexel=t,i.arrayConstructor=Int16Array,i.samplerPrefix="i",i;case I.UINT32:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=hm[t],i.textureFormat=Gi[t],i.texelType=WebGL2RenderingContext.UNSIGNED_INT,i.arrayElementsPerTexel=1,i.arrayConstructor=Uint32Array,i.samplerPrefix="u",i;case I.INT32:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=tD[t],i.textureFormat=Gi[t],i.texelType=WebGL2RenderingContext.INT,i.arrayElementsPerTexel=1,i.arrayConstructor=Int32Array,i.samplerPrefix="i",i;case I.UINT64:if(t<1||t>2)break;return i.texelsPerElement=1,i.textureInternalFormat=hm[t*2],i.textureFormat=Gi[t*2],i.texelType=WebGL2RenderingContext.UNSIGNED_INT,i.arrayElementsPerTexel=2*t,i.arrayConstructor=Uint32Array,i.samplerPrefix="u",i;case I.FLOAT32:if(t<1||t>4)break;return i.texelsPerElement=1,i.textureInternalFormat=nD[t],i.textureFormat=qT[t],i.texelType=WebGL2RenderingContext.FLOAT,i.arrayElementsPerTexel=t,i.arrayConstructor=Float32Array,i.samplerPrefix="",i}throw new Error(`No supported texture format for ${I[e]}[${t}].`)}function fa(i,e,t){const{arrayConstructor:n,arrayElementsPerTexel:s,textureInternalFormat:r,textureFormat:o,texelsPerElement:a}=e,{maxTextureSize:l}=i,c=t.length/s;if(c*a>l*l)throw new Error("Number of elements exceeds maximum texture size: "+a+" * "+c);const d=Math.ceil(c/l),u=Math.ceil(Math.log2(d)),h=(1<<u)*a,f=Math.ceil(c/(1<<u)),m=h*f*s;t.constructor!==n&&(t=new n(t.buffer,t.byteOffset,t.byteLength/n.BYTES_PER_ELEMENT));const g=(0,z.jx)(t,m);i.pixelStorei(WebGL2RenderingContext.UNPACK_ALIGNMENT,1),ki(i),i.texImage2D(WebGL2RenderingContext.TEXTURE_2D,0,r,h,f,0,o,e.texelType,g)}function iD(i,e,t,n,s){const{arrayConstructor:r,textureInternalFormat:o,textureFormat:a,texelsPerElement:l}=e;t.constructor!==r&&(t=new r(t.buffer,t.byteOffset,t.byteLength/r.BYTES_PER_ELEMENT)),i.pixelStorei(WebGL2RenderingContext.UNPACK_ALIGNMENT,1),ki(i),i.texImage2D(WebGL2RenderingContext.TEXTURE_2D,0,o,n*l,s,0,a,e.texelType,t)}function sD(i,e,t,n,s,r){const{arrayConstructor:o,textureInternalFormat:a,textureFormat:l,texelsPerElement:c}=e;t.constructor!==o&&(t=new o(t.buffer,t.byteOffset,t.byteLength/o.BYTES_PER_ELEMENT)),i.pixelStorei(WebGL2RenderingContext.UNPACK_ALIGNMENT,1),iC(i),i.texImage3D(WebGL2RenderingContext.TEXTURE_3D,0,a,n*c,s,r,0,l,e.texelType,t)}function rD(i){switch(i){case I.UINT8:return Cp;case I.INT8:return xp;case I.UINT16:return Ep;case I.INT16:return Tp;case I.UINT32:return bo;case I.INT32:return Dp;case I.UINT64:return pt;case I.FLOAT32:return Xl}}function pm(i,e,t,n,s,r){const o=vt(s,r),a=[rD(s)];let l=`
${o} ${i}(${n} index) {
`;switch(s){case I.UINT8:case I.UINT16:case I.UINT32:l+=`
  ${o} result;
  highp uvec4 temp;
  ${e}(${t}, index, temp);
  result.value = temp.${ha[r]};
  return result;
`;break;case I.INT8:case I.INT16:case I.INT32:l+=`
  ${o} result;
  highp ivec4 temp;
  ${e}(${t}, index, temp);
  result.value = temp.${ha[r]};
  return result;
`;break;case I.UINT64:a.push(pC),l+=`
  highp uvec4 temp;
  ${e}(${t}, index, temp);
  return unpackUint64leFromUint32(temp.${ha[r*2]});
`;break;case I.FLOAT32:a.push(Xl),l+=`
  highp vec4 temp;
  ${e}(${t}, index, temp);
  return temp.${ha[r]};
`;break}return l+=`
}
`,a.push(l),a}class ga{constructor(e){this.key=e,this.readTextureValue=`readTextureValue_${this.key}`}defineShader(e){}getReadTextureValueCode(e,t){let n=`
void ${this.readTextureValue}(highp ${t}sampler2D sampler, highp uint index`;for(let s=0;s<e;++s)n+=`, out ${t}vec4 output${s}`;n+=`) {
  highp int width = textureSize(sampler, 0).x / ${e};
  highp uint log2width = log2Exact(uint(width));
  highp int y = int(index >> log2width);
  highp int x = int((index - (uint(y) << log2width)) * ${e}u);
`;for(let s=0;s<e;++s)n+=`
  output${s} = texelFetch(sampler, ivec2(x + ${s}, y), 0);
`;return n+=`
}
`,[yC,n]}getAccessor(e,t,n,s=1){const r=pa(n);return[this.getReadTextureValueCode(1,r),...pm(e,this.readTextureValue,t,"highp uint",n,s)]}}class oD{constructor(e,t){this.key=e,this.textureDims=t,this.readTextureValue=`readTextureValue_${this.key}`}getReadTextureValueCode(e,t){const{textureDims:n}=this;let s=`
void ${this.readTextureValue}(highp ${t}sampler${this.textureDims}D sampler, highp ivec${n} p`;for(let r=0;r<e;++r)s+=`, out ${t}vec4 output${r}`;s+=`) {
`;for(let r=0;r<e;++r)s+=`
  output${r} = texelFetch(sampler, ivec${n}(p.x * ${e} + ${r}, p.y
                                         ${n===3?", p.z":""}), 0);
`;return s+=`
}
`,s}getAccessor(e,t,n,s=1){const r=pa(n);return[this.getReadTextureValueCode(1,r),...pm(e,this.readTextureValue,t,`highp ivec${this.textureDims}`,n,s)]}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const fm=[pt,`
highp uint hashCombine(highp uint state, highp uint value) {
  value *= 0xcc9e2d51u;
  value = (value << 15u) | (value >> 17u);
  value *= 0x1b873593u;
  state ^= value;
  state = (state << 13u) | (state >> 19u);
  state = (state * 5u) + 0xe6546b64u;
  return state;
}
highp uint hashCombine(highp uint state, uint64_t x) {
  state = hashCombine(state, x.value[0]);
  return hashCombine(state, x.value[1]);
}
`],aD=zi(new As,I.UINT64,1);class Wi extends D.O8{constructor(e,t){super(),this.gl=e,this.hashTable=t,this.generation=-1,this.texture=null,this.texture=e.createTexture()}copyToGPU(){const{hashTable:e}=this,{generation:t}=e;if(this.generation===t)return;const{gl:n,texture:s}=this;this.generation=t,n.activeTexture(WebGL2RenderingContext.TEXTURE0+n.tempTextureUnit),n.bindTexture(WebGL2RenderingContext.TEXTURE_2D,s),e.tableWithMungedEmptyKey(r=>{fa(this.gl,aD,r)}),n.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}disposed(){const{gl:e}=this;e.deleteTexture(this.texture),this.texture=null,this.gl=void 0,this.hashTable=void 0,super.disposed()}static get(e,t){return e.memoize.get(t,()=>new Wi(e,t))}}class gm{constructor(e,t=ad){this.prefix=e,this.numAlternatives=t,this.textureUnitSymbol=Symbol.for(`gpuhashtable:${this.prefix}`),this.accessHelper=new ga(`gpuhashtable_${this.prefix}`),this.samplerName=this.prefix+"_sampler",this.hashSeedsName=this.prefix+"_seeds",this.hashKeyMask=this.prefix+"_keyMask",this.readTable=this.prefix+"_readTable"}defineShader(e){const{hashSeedsName:t,samplerName:n,numAlternatives:s,hashKeyMask:r}=this;e.addUniform("highp uint",t,s),e.addUniform("highp uint",r),e.addTextureSampler("usampler2D",n,this.textureUnitSymbol),e.addFragmentCode(fm),e.addFragmentCode(pt),e.addFragmentCode(Sp),this.accessHelper.defineShader(e),e.addFragmentCode(this.accessHelper.getAccessor(this.readTable,this.samplerName,I.UINT64,1));let o="";o+=`
bool ${this.hasFunctionName}(uint64_t x) {
`;for(let a=0;a<s;++a)o+=`
  {
    uint h = hashCombine(${t}[${a}], x) & ${r};
    uint64_t key = ${this.readTable}(h);
    if (equals(key, x)) {
      return true;
    }
  }
`;o+=`
  return false;
}
`,e.addFragmentCode(o)}get hasFunctionName(){return`${this.prefix}_has`}enable(e,t,n){n.copyToGPU();const s=t.textureUnit(this.textureUnitSymbol);e.activeTexture(WebGL2RenderingContext.TEXTURE0+s),e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,n.texture),e.uniform1ui(t.uniform(this.hashKeyMask),n.hashTable.tableSize-1),e.uniform1uiv(t.uniform(this.hashSeedsName),n.hashTable.hashSeeds)}disable(e,t){const n=t.textureUnit(this.textureUnitSymbol);e.activeTexture(WebGL2RenderingContext.TEXTURE0+n),e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}}class mm extends gm{defineShader(e){super.defineShader(e);const{numAlternatives:t,hashSeedsName:n,hashKeyMask:s}=this;let r=`
bool ${this.getFunctionName}(uint64_t x, out uint64_t value) {
`;for(let o=0;o<t;++o)r+=`
  {
    uint h = hashCombine(${n}[${o}], x) & ${s};
    uint64_t key = ${this.readTable}(h * 2u);
    if (equals(key, x)) {
      value = ${this.readTable}(h * 2u + 1u);
      return true;
    }
  }
`;r+=`
  return false;
}
`,e.addFragmentCode(r)}get getFunctionName(){return`${this.prefix}_get`}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const vm=2;class lD{constructor(e){this.prefix=e,this.seedName=this.prefix+"_seed"}defineShader(e){const{seedName:t}=this;e.addUniform("highp uint",t),e.addFragmentCode(pt),e.addFragmentCode(fm),e.addFragmentCode(hC);let n=`
vec3 ${this.prefix}(uint64_t x) {
  uint h = hashCombine(${t}, x);
  vec${vm} v;
`;for(let s=0;s<vm;++s)n+=`
  v[${s}] = float(h & 0xFFu) / 255.0;
  h >>= 8u;
`;n+=`
  vec3 hsv = vec3(v.x, 0.5 + v.y * 0.5, 1.0);
  return hsvToRgb(hsv);
}
`,e.addFragmentCode(n)}enable(e,t,n){e.uniform1ui(t.uniform(this.seedName),n)}}const ym=new Float32Array(3);function Sm(i){return`rgb(${i[0]*100}%,${i[1]*100}%,${i[2]*100}%)`}class cd{constructor(e=_t()){this.hashSeed=e,this.changed=new j.IY}static getDefault(){return new cd(0)}get value(){return this.hashSeed}set value(e){e!==this.hashSeed&&(this.hashSeed=e,this.changed.dispatch())}compute(e,t){let n=(0,ua._)(this.hashSeed,t.low);n=(0,ua._)(n,t.high);const s=(n&255)/255,r=(n>>8&255)/255;return Io(e,s,.5+.5*r,1),e}computeCssColor(e){return this.compute(ym,e),Sm(ym)}randomize(){this.hashSeed=_t(),this.changed.dispatch()}toString(){return`new SegmentColorHash(${this.hashSeed})`}toJSON(){return this.hashSeed===0?void 0:this.hashSeed}reset(){this.restoreState(0)}restoreState(e){const t=e>>>0;t!==this.hashSeed&&(this.hashSeed=t,this.changed.dispatch())}}class cD{constructor(e){this.prefix=e,this.hashMapShaderManager=new mm("segmentStatedColorHash")}defineShader(e){this.hashMapShaderManager.defineShader(e);const t=`
bool ${this.getFunctionName}(uint64_t x, out vec4 value) {
  uint64_t uint64Value;
  if (${this.hashMapShaderManager.getFunctionName}(x, uint64Value)) {
    uint uintValue = uint64Value.value[0];
    value.r = float((uintValue & 0x0000ffu))       / 255.0;
    value.g = float((uintValue & 0x00ff00u) >>  8) / 255.0;
    value.b = float((uintValue & 0xff0000u) >> 16) / 255.0;
    value.a = float((uintValue & 0xff000000u) >> 24) / 255.0;
    return true;
  }
  return false;
}
`;e.addFragmentCode(t)}get getFunctionName(){return`${this.prefix}_get`}enable(e,t,n){this.hashMapShaderManager.enable(e,t,n)}disable(e,t){this.hashMapShaderManager.disable(e,t)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let dd;function dD(){if(dd===void 0){const i=new Pe;i.set("keyl","recolor"),i.set("keyx","clear-segments"),i.set("keys","toggle-show-slices"),i.set("keyb","toggle-scale-bar"),i.set("keyv","toggle-default-annotations"),i.set("keya","toggle-axis-lines"),i.set("keyo","toggle-orthographic-projection");for(let e=1;e<=9;++e)i.set("digit"+e,"toggle-layer-"+e),i.set("control+digit"+e,"select-layer-"+e),i.set("alt+digit"+e,"toggle-pick-layer-"+e);for(let e=0;e<26;++e){const t=String.fromCharCode(97+e),n=String.fromCharCode(65+e);i.set(`alt?+control?+shift+key${t}`,`tool-${n}`)}i.set("keyn","add-layer"),i.set("keyh","help"),i.set("space","toggle-layout"),i.set("shift+space","toggle-layout-alternative"),i.set("backslash","toggle-show-statistics"),dd=i}return dd}let ud;function Mr(){return ud===void 0&&(ud=Pe.fromObject({"control+mousedown2":"select-position"})),ud}let hd;function uD(){return hd===void 0&&(hd=Pe.fromObject({click0:"pin-annotation",mousedown2:"move-to-annotation"},{parents:[[Mr(),0]]})),hd}let pd;function bm(){return pd===void 0&&(pd=Pe.fromObject({arrowleft:"x-",arrowright:"x+",arrowup:"y-",arrowdown:"y+",comma:"z-",period:"z+",bracketleft:"t-",bracketright:"t+",keyz:"snap","control+equal":"zoom-in","alt+equal":"depth-range-decrease","control+shift+equal":"zoom-in","alt+shift+equal":"depth-range-decrease","control+minus":"zoom-out","alt+minus":"depth-range-increase",keyr:"rotate-relative-z-",keye:"rotate-relative-z+","shift+arrowdown":"rotate-relative-x-","shift+arrowup":"rotate-relative-x+","shift+arrowleft":"rotate-relative-y-","shift+arrowright":"rotate-relative-y+","control+wheel":{action:"zoom-via-wheel",preventDefault:!0},"alt+wheel":{action:"adjust-depth-range-via-wheel",preventDefault:!0},"at:wheel":{action:"z+1-via-wheel",preventDefault:!0},"at:shift+wheel":{action:"z+10-via-wheel",preventDefault:!0},"at:dblclick0":"select","at:shift+dblclick0":"star","at:control+mousedown0":"annotate","at:mousedown2":"move-to-mouse-position","at:alt+mousedown0":"move-annotation","at:control+alt+mousedown2":"delete-annotation","at:touchpinch":"zoom-via-touchpinch","at:touchrotate":"rotate-in-plane-via-touchrotate","at:touchtranslate2":"translate-in-plane-via-touchtranslate","at:touchhold1":"move-to-mouse-position","at:touchtap1x2":"select","at:touchtap2x3":"snap"},{label:"All Data Panels",parents:[[Mr(),0]]})),pd}let fd;function hD(){return fd===void 0&&(fd=Pe.fromObject({"at:mousedown0":{action:"rotate-via-mouse-drag",stopPropagation:!0},"at:shift+mousedown0":{action:"translate-via-mouse-drag",stopPropagation:!0},"at:touchtranslate1":"rotate-out-of-plane-via-touchtranslate"},{parents:[[bm(),Number.NEGATIVE_INFINITY]]})),fd}let gd;function pD(){return gd===void 0&&(gd=Pe.fromObject({"at:mousedown0":{action:"translate-via-mouse-drag",stopPropagation:!0},"at:shift+mousedown0":{action:"rotate-via-mouse-drag",stopPropagation:!0},"at:touchtranslate1":"translate-z-via-touchtranslate"},{parents:[[bm(),Number.NEGATIVE_INFINITY]]})),gd}function fD(i){i.global.addParent(dD(),Number.NEGATIVE_INFINITY),i.sliceView.addParent(pD(),Number.NEGATIVE_INFINITY),i.perspectiveView.addParent(hD(),Number.NEGATIVE_INFINITY)}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Ms;const Nr=[];function gD(){if(Ms===void 0){const i=Ms=document.createElement("div");i.classList.add("neuroglancer-drag-status"),document.body.appendChild(i)}return Ms}function mD(){Ms!==void 0&&(Ae(Ms),Ms.style.display="none")}function wm(i){const e=gD();Ae(e),typeof i=="string"?e.appendChild(document.createTextNode(i)):e.appendChild(i()),e.style.display=""}function Cm(i,e){(0,z.U8)(Nr,t=>!(t.target===i&&t.operation===e))}function Sn(i,e,t){Cm(i,e),Nr.push({target:i,operation:e,status:t}),wm(t)}function Dt(i,e){Cm(i,e);const t=Nr.length===0?void 0:Nr[Nr.length-1];t===void 0?mD():wm(t.status)}var vD=G(9575);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function md(i={}){return _e({svg:vD,...i})}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Ns="neuroglancer-drag-over",xm={row:"row",column:"col"},yD={left:"right",right:"left",top:"bottom",bottom:"top"},ui={left:"column",right:"column",top:"row",bottom:"row"},ma={left:"row",right:"row",top:"column",bottom:"column"},Hi={row:"width",column:"height"},Em={row:"left",column:"top"},SD={row:"right",column:"bottom"},Tm={left:"marginLeft",right:"marginRight",top:"marginTop",bottom:"marginBottom"},va={left:-1,right:1,top:-1,bottom:1};class Ji extends D.O8{constructor(e,t=new ci){super(),this.sidePanelManager=e,this.location=t,this.element=document.createElement("div"),this.visibility=new ht(ht.VISIBLE);const{element:n}=this;n.classList.add("neuroglancer-side-panel"),n.draggable=!0,n.addEventListener("dragstart",s=>{this.sidePanelManager.startDrag(this.makeDragSource(),s),n.style.backgroundColor="black",setTimeout(()=>{n.style.backgroundColor=""},0),Sn(n,"drag",()=>document.createTextNode("Drag side panel to move it to the left/right/top/bottom of another panel"))}),n.addEventListener("dragend",s=>{this.sidePanelManager.endDrag(),Dt(n,"drag")})}makeDragSource(){return{dropAsNewPanel:e=>{const t=this.location.value;this.location.value={...t,...e},this.location.locationChanged.dispatch()}}}close(){this.location.visible=!1}addTitleBar(e){const t=document.createElement("div");t.classList.add("neuroglancer-side-panel-titlebar");const{title:n}=e;let s;n!==void 0&&(s=document.createElement("div"),s.classList.add("neuroglancer-side-panel-title"),s.textContent=n,t.appendChild(s));const r=md({title:"Close panel",onClick:()=>{this.close()}});return r.style.order="100",t.appendChild(r),this.element.appendChild(t),{titleBar:t,titleElement:s,closeButton:r}}addBody(e){e.draggable=!0,e.addEventListener("dragstart",t=>{t.preventDefault(),t.stopPropagation()}),this.element.appendChild(e)}}class bD extends D.O8{constructor(e,t,n=new ht(ht.VISIBLE)){super(),this.display=e,this.center=t,this.visibility=n,this.element=document.createElement("div"),this.centerColumn=document.createElement("div"),this.beforeRender=new j.HN,this.sides={left:this.makeSidePanelSideState("left"),right:this.makeSidePanelSideState("right"),top:this.makeSidePanelSideState("top"),bottom:this.makeSidePanelSideState("bottom")},this.registeredPanels=new Set,this.layoutNeedsUpdate=!1,this.invalidateLayout=()=>{this.layoutNeedsUpdate=!0,this.display.scheduleRedraw()};const{element:s,centerColumn:r}=this;s.style.display="flex",s.style.flex="1",s.style.flexDirection="row",r.style.display="flex",r.style.flex="1",r.style.flexDirection="column",r.style.flexBasis="0px",r.style.minWidth="0px",this.render(),this.registerDisposer(e.updateStarted.add(()=>{this.beforeRender.dispatch(),this.layoutNeedsUpdate&&(this.render(),++e.resizeGeneration)})),this.registerDisposer(this.visibility.changed.add(this.invalidateLayout))}get visible(){return this.visibility.visible}makeSidePanelSideState(e){return{flexGroups:[],outerDropZoneElement:this.makeDropZone(e,va[e]*(1/0),0,e,!1)}}hasDroppablePanel(){return this.dragSource!==void 0}startDrag(e,t){setTimeout(()=>{this.dragSource===e&&(this.element.dataset.neuroglancerSidePanelDrag="true")},0),this.dragSource=e,t.stopPropagation(),t.dataTransfer.setData("neuroglancer-side-panel","")}endDrag(){delete this.element.dataset.neuroglancerSidePanelDrag,this.dragSource=void 0}makeDropZone(e,t,n,s,r=!1){const o=document.createElement("div");o.className="neuroglancer-side-panel-drop-zone";const a=10,l=ui[s],c=ma[s];return o.style[Hi[c]]=`${a}px`,o.style[Hi[l]]="100%",r?(o.style.position="absolute",o.style[s]="50%",o.style[Tm[s]]="-${size/2}px"):(o.style.position="relative",o.style[Tm[yD[s]]]=`-${a}px`),o.addEventListener("dragenter",d=>{this.hasDroppablePanel()&&(o.classList.add(Ns),d.preventDefault(),Sn(o,"drop",()=>document.createTextNode(`Drop side panel as new ${l}`)))}),o.addEventListener("dragleave",()=>{Dt(o,"drop"),o.classList.remove(Ns)}),o.addEventListener("dragover",d=>{this.hasDroppablePanel()&&d.preventDefault()}),o.addEventListener("drop",d=>{const{dragSource:u}=this;if(u===void 0)return;Dt(o,"drop"),o.classList.remove(Ns);const h=ui[e];u.dropAsNewPanel({side:e,row:h==="column"?n:t,col:h==="row"?n:t}),this.dragSource=void 0,d.preventDefault(),d.stopPropagation()}),o}registerPanel(e){return this.registeredPanels.add(e),this.invalidateLayout(),e.location.locationChanged.add(this.invalidateLayout),()=>{this.unregisterPanel(e)}}unregisterPanel(e){this.registeredPanels.delete(e),e.location.locationChanged.remove(this.invalidateLayout),e.panel?.dispose(),this.invalidateLayout()}disposed(){for(const{panel:e}of this.registeredPanels)e?.dispose();super.disposed()}render(){this.layoutNeedsUpdate=!1;const e={left:[],right:[],top:[],bottom:[]};for(const o of this.registeredPanels)e[o.location.value.side].push(o);const t=o=>this.renderSide(o,this.sides[o].flexGroups,e[o]),n=this;function*s(){yield n.sides.left.outerDropZoneElement,yield*t("left"),yield n.centerColumn,yield*t("right"),yield n.sides.right.outerDropZoneElement}Zt(this.element,s());function*r(){yield n.sides.top.outerDropZoneElement,yield*t("top"),yield n.center,yield*t("bottom"),yield n.sides.bottom.outerDropZoneElement}Zt(this.centerColumn,r())}makeCrossGutter(e,t){const n=document.createElement("div");n.style.position="relative";const s=ma[e];n.className=`neuroglancer-resize-gutter-${s==="row"?"horizontal":"vertical"}`,n.addEventListener("pointerdown",o=>{if("button"in o&&o.button!==0)return;o.preventDefault();const a=this.sides[e].flexGroups[t];if(a===void 0||!a.visible)return;let c=a.element.getBoundingClientRect()[Hi[s]];const d=a.minSize,u=()=>{Sn(n,"drag",`Drag to resize, current ${Hi[s]} is ${a.crossSize}px`)};u(),$t(o,(h,f,m)=>{const g=s==="row"?f:m;c-=va[e]*g,a.crossSize=Math.max(d,Math.round(c)),u(),this.invalidateLayout()},()=>{Dt(n,"drag")})});const r=this.makeDropZone(e,t-va[e]*.5,0,e,!0);return n.appendChild(r),n}makeFlexGutter(e,t,n){const s=document.createElement("div");s.style.position="relative";const r=ui[e];s.className=`neuroglancer-resize-gutter-${r==="row"?"horizontal":"vertical"}`,s.addEventListener("pointerdown",a=>{if("button"in a&&a.button!==0)return;a.preventDefault();const l=this.sides[e].flexGroups[t];if(l===void 0||!l.visible)return;const{cells:c}=l,d=c[n];if(d===void 0||!d.registeredPanel.location.visible)return;let u=n+1;for(;u<c.length&&!c[u].registeredPanel.location.visible;)++u;if(u===c.length)return;const h=c[u],f=()=>{Sn(s,"drag",`Drag to resize, current ${Hi[r]} ratio is ${d.registeredPanel.location.value.flex} : ${h.registeredPanel.location.value.flex}`)};f(),$t(a,m=>{const g=d.registeredPanel.panel,v=h.registeredPanel.panel;if(g===void 0||v===void 0)return;const y=g.element.getBoundingClientRect(),S=v.element.getBoundingClientRect(),x=Math.max(.1,Math.min(.9,r==="column"?(m.clientY-y.top)/(S.bottom-y.top):(m.clientX-y.left)/(S.right-y.left))),b=d.registeredPanel.location.value,E=h.registeredPanel.location.value,C=b.flex+E.flex;d.registeredPanel.location.value={...b,flex:Math.round(x*C*100)/100},h.registeredPanel.location.value={...E,flex:Math.round((1-x)*C*100)/100},f(),d.registeredPanel.location.locationChanged.dispatch(),h.registeredPanel.location.locationChanged.dispatch(),this.invalidateLayout()},()=>{Dt(s,"drag")})});const o=this.makeDropZone(e,t,n+.5,Em[ui[e]],!0);return s.appendChild(o),s}renderSide(e,t,n){const s=xm[ma[e]],r=xm[ui[e]];n.sort((l,c)=>{const d=l.location.value,u=c.location.value,h=d[r]-u[r];return h!==0?h:d[s]-u[s]});const o=this;function*a(){let l=0;const c=n.length;let d=0;for(;l<c;){const u=n[l].location.value[r];let h=l,f=0,m=0;do{const S=n[h].location.value;if(S[r]!==u)break;S.visible&&(++f,m=Math.max(m,S.minSize)),++h}while(h<c);const g=f>0;let v=t[d];if(v===void 0){const S=o.makeCrossGutter(e,d),x=document.createElement("div");x.className=`neuroglancer-side-panel-${ui[e]}`,v=t[d]={element:x,gutterElement:S,cells:[],crossSize:-1,minSize:m,visible:g,beginDropZone:o.makeDropZone(e,d,-1/0,Em[ui[e]]),endDropZone:o.makeDropZone(e,d,1/0,SD[ui[e]])}}else v.visible=g,v.minSize=m,v.crossSize=Math.max(v.crossSize,m);function*y(){yield v.beginDropZone;let S=0;for(let x=l,b=0;x<h;++x,++b){const E=n[x];let C=v.cells[b];C===void 0?C=v.cells[b]={registeredPanel:E,gutterElement:void 0}:C.registeredPanel=E;const k=C.registeredPanel.location.value;v.crossSize===-1&&(v.crossSize=Math.max(m,k.size)),(k[r]!==d||k[s]!==b||k.visible&&k.size!==v.crossSize)&&(C.registeredPanel.location.value={...k,[r]:d,[s]:b,size:k.visible?v.crossSize:k.size},C.registeredPanel.location.changed.dispatch());const T=k.visible&&o.visibility.visible;let{panel:L}=E;if(!T){L!==void 0&&(L.dispose(),E.panel=void 0);continue}++S,L===void 0&&(L=E.panel=E.makePanel()),L.element.style.flex=f>1?`${k.flex}`:"1",yield L.element,S===f?C.gutterElement=void 0:(C.gutterElement===void 0&&(C.gutterElement=o.makeFlexGutter(e,d,b)),yield C.gutterElement)}yield v.endDropZone}Zt(v.element,y()),v.cells.length=h-l,g&&(v.element.style[Hi[ma[e]]]=`${v.crossSize}px`,va[e]>0?(yield v.gutterElement,yield v.element):(yield v.element,yield v.gutterElement)),l=h,++d}t.length=d}return a()}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Dm(i={}){return _e({text:"\u2197",...i})}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Im(i){return i.closest(".neuroglancer-selection-details")}class wD extends Ji{constructor(e,t,n,s){super(e,t.location),this.sidePanelManager=e,this.state=t,this.manager=n,this.selectedLayer=s,this.body=document.createElement("div");const{element:r,body:o}=this;r.classList.add("neuroglancer-selection-details"),this.registerDisposer(new fn(this.element,Mr()));const{titleBar:a}=this.addTitleBar({title:"Selection"}),l=_e({svg:rf,title:"Previous selection",onClick:()=>{this.state.goBack()}}),c=_e({svg:of,title:"Next selection",onClick:()=>{this.state.goForward()}});a.appendChild(l),a.appendChild(c),a.appendChild(this.registerDisposer(new en(t.pin,{text:"\u{1F4CC}\uFE0E",enableTitle:"Pin selection",disableTitle:"Unpin selection"})).element),o.classList.add("neuroglancer-selection-details-body"),this.addBody(o),o.appendChild(this.registerDisposer(new zt(t,(d,u,h)=>{if(!t.location.visible||(l.style.visibility=t.canGoBack()?"visible":"hidden",c.style.visibility=t.canGoForward()?"visible":"hidden",d===void 0))return;const{position:f}=d;if(f!==void 0){const m=document.createElement("div");m.classList.add("neuroglancer-selection-details-position");const g=zn({title:"Copy position",onClick:()=>{ai(S.map(b=>Math.floor(b)).join(", "))}});m.appendChild(g);const{coordinateSpace:{rank:v,names:y},position:S}=d;for(let b=0;b<v;++b){const E=document.createElement("span");E.classList.add("neuroglancer-selection-details-position-dimension");const C=document.createElement("span");C.classList.add("neuroglancer-selection-details-position-dimension-name"),C.textContent=y[b];const k=document.createElement("span");k.classList.add("neuroglancer-selection-details-position-dimension-coordinate"),k.textContent=Math.floor(S[b]).toString(),E.appendChild(C),E.appendChild(k),m.appendChild(E)}const x=Dm({title:"Move to position",onClick:()=>{this.manager.globalPosition.value=S}});m.appendChild(x),u.appendChild(m)}for(const m of d.layers){const{layer:g}=m;u.appendChild(h.registerDisposer(new zt({value:void 0,changed:g.managedLayer.layerChanged},(v,y,S)=>{if(g.wasDisposed||!g.isReady)return;const x=document.createElement("div");if(x.classList.add("neuroglancer-selection-details-layer-body"),!g.displaySelectionState(m.state,x,S))return;const b=document.createElement("div");y.appendChild(b),b.classList.add("neuroglancer-selection-details-layer");const E=document.createElement("div");E.classList.add("neuroglancer-selection-details-layer-title"),E.textContent=g.managedLayer.name,E.addEventListener("click",()=>{this.selectedLayer.layer=g.managedLayer,this.selectedLayer.visible=!0}),E.title="Click to show layer side panel",b.appendChild(E),b.appendChild(x)})).element)}})).element)}close(){super.close(),this.state.value=void 0,this.state.pin.value=!0}}var Rm=G(9564);/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function km(i={}){const e=_e({svg:Rm,...i});return e.classList.add("neuroglancer-eye-icon"),e}var CD=G(7237);/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function xD(i={}){return _e({svg:CD,...i})}var ED=G(9187);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Lm(i={}){const e=_e({svg:ED,...i});return e.classList.add("neuroglancer-star-icon"),e}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hi{constructor(e,t,n){this.key=e,this.value=t,this.label=n}toString(){const{key:e,value:t,label:n}=this;let s;return t===void 0?s=`${e}`:s=`${e}\u2192${t}`,n===void 0?s:`${s} ${n}`}}class TD extends D.O8{constructor(){super(...arguments),this.selectedSegment=new M.R,this.baseSelectedSegment=new M.R,this.hasSelectedSegment=!1,this.changed=new j.IY}get value(){return this.hasSelectedSegment?this.selectedSegment:void 0}get baseValue(){return this.hasSelectedSegment?this.baseSelectedSegment:void 0}set(e,t=!1){const{selectedSegment:n,baseSelectedSegment:s}=this;let r=0,o=0,a=0,l=0,c;if(e==null)c=!1;else if(typeof e=="number")r=a=e>>>0,o=l=e<0?4294967295:0,c=!0;else if(e instanceof hi){const d=e.value||e.key;r=d.low,o=d.high,a=e.key.low,l=e.key.high,c=!0}else e instanceof M.R?(r=a=e.low,o=l=e.high,c=!0):c=!1;t&&r===0&&o===0&&(c=!1),c?c&&(!this.hasSelectedSegment||n.low!==r||n.high!==o||s.low!==a||s.high!==l)&&(n.low=r,n.high=o,s.low=a,s.high=l,this.hasSelectedSegment=!0,this.changed.dispatch()):this.hasSelectedSegment&&(this.hasSelectedSegment=!1,this.changed.dispatch())}isSelected(e){return this.hasSelectedSegment&&M.R.equal(e,this.selectedSegment)}bindTo(e,t){this.registerDisposer(e.changed.add(()=>{const n=e.get(t);let s;n!==void 0&&(s=n.value),this.set(s,t.displayState.segmentationGroupState.value.hideSegmentZero.value)}))}}function Or(i){i.useTemporarySegmentEquivalences.value=!1,i.useTemporaryVisibleSegments.value=!1,i.temporaryVisibleSegments.clear(),i.temporarySegmentEquivalences.clear()}function Pm(i,e,t=!1){let n,s,r;if(typeof e=="number"?n=new M.R(e>>>0,e<0?4294967295:0):typeof e=="string"?n=M.R.parseString(e):n=t?e.clone():e,i==null)return n;const{segmentEquivalences:o,segmentPropertyMap:{value:a}}=i.segmentationGroupState.value;o.size!==0?(s=o.get(n),M.R.equal(s,n)?r=void 0:r=s):s=n;const l=a?.getSegmentLabel(s);return l===void 0&&r===void 0?n:new hi(n,r,l)}function ji(i,e){if(e instanceof hi)return e;const t=Pm(i,e);return t instanceof M.R?new hi(t):t}function Am(i,e){const{length:t}=e;i.value<t&&(i.value=t)}function Vr(i,e){return(0,A.W1)(t=>e.style.setProperty("--neuroglancer-segment-list-width",`${t}ch`),i.segmentationGroupState.value.maxIdLength)}const vd=(()=>{const i=document.createElement("div");i.classList.add("neuroglancer-segment-list-entry");const e=document.createElement("div");e.classList.add("neuroglancer-segment-list-entry-sticky"),i.appendChild(e);const t=zn({title:"Copy segment ID"});t.classList.add("neuroglancer-segment-list-entry-copy");const n=document.createElement("div");n.classList.add("neuroglancer-segment-list-entry-copy-container");const s=n.childElementCount;n.appendChild(t);const r=e.childElementCount;e.appendChild(n);const o=e.childElementCount,a=km({title:"Toggle segment visibility"});a.classList.add("neuroglancer-segment-list-entry-visible-checkbox"),e.appendChild(a);const l=document.createElement("div");l.classList.add("neuroglancer-segment-list-entry-id-container");const c=e.childElementCount;e.appendChild(l);const d=document.createElement("div");d.classList.add("neuroglancer-segment-list-entry-id");const u=l.childElementCount;l.appendChild(d);const h=Lm({title:"Star segment"});h.classList.add("neuroglancer-segment-list-entry-star");const f=e.childElementCount;e.appendChild(h);const m=document.createElement("span");m.classList.add("neuroglancer-segment-list-entry-name");const g=i.childElementCount;i.appendChild(m);const v=xD({title:"Filter by label"});v.classList.add("neuroglancer-segment-list-entry-filter");const y=i.childElementCount;return i.appendChild(v),{template:i,copyContainerIndex:r,copyIndex:s,visibleIndex:o,idContainerIndex:c,idIndex:u,labelIndex:g,filterIndex:y,starIndex:f,unmappedIdIndex:-1,unmappedCopyIndex:-1}})(),DD=(()=>{const i=vd,e=i.template.cloneNode(!0),t=e.children[0],n=t.children[i.idContainerIndex],s=n.childElementCount,r=n.children[i.idIndex].cloneNode(!0);r.classList.add("neuroglancer-segment-list-entry-unmapped-id"),n.appendChild(r);const o=t.children[i.copyContainerIndex],a=o.childElementCount;return o.appendChild(o.children[i.copyIndex].cloneNode(!0)),{...i,template:e,unmappedIdIndex:s,unmappedCopyIndex:a}})();function ID(i){const e=vd,t=e.template.cloneNode(!0),n=[];for(let s=0;s<i;++s){n.push(t.childElementCount);const r=document.createElement("div");r.classList.add("neuroglancer-segment-list-entry-extra-property"),r.style.width=`max(var(--neuroglancer-column-${s}-width), var(--neuroglancer-column-${s}-label-width))`,t.appendChild(r)}return{...e,template:t,numericalPropertyIndices:n}}const Mm=new WeakMap;function RD(i){const e=d=>{const u=d.currentTarget,h=u.dataset.id,f=nn;f.tryParseString(h),i.segmentSelectionState.set(f),Im(u)||i.selectSegment(f,!1)},t=d=>{const u=d.currentTarget,h=u.dataset.id,f=nn;f.tryParseString(h),i.selectSegment(f,Im(u)?"toggle":!0)},n=()=>{i.segmentSelectionState.set(null)},s=d=>d.currentTarget.closest(".neuroglancer-segment-list-entry"),r=d=>{const u=s(d);ai(u.dataset.id),d.stopPropagation()},o=d=>{const u=s(d);ai(u.dataset.unmappedId),d.stopPropagation()},a=d=>{const h=s(d).dataset.id,f=nn;f.tryParseString(h);const{selectedSegments:m,visibleSegments:g}=i.segmentationGroupState.value,v=!g.has(f);v&&m.add(f),g.set(f,v),d.stopPropagation(),d.preventDefault()},l=d=>{const h=s(d).dataset.id,f=nn;f.tryParseString(h),i.filterBySegmentLabel(f),d.stopPropagation()},c=d=>{if(d.button!==2||d.ctrlKey||d.altKey||d.metaKey||d.shiftKey)return;const h=d.currentTarget.dataset.id,f=nn;f.tryParseString(h),i.moveToSegment(f)};return(d,u)=>{const{children:h}=d,f=h[0].children;d.addEventListener("mousedown",c);const m=f[u.copyContainerIndex];u.unmappedCopyIndex!==-1&&m.children[u.unmappedCopyIndex].addEventListener("click",o),m.children[u.copyIndex].addEventListener("click",r),d.addEventListener("mouseenter",e),d.addEventListener("mouseleave",n),f[u.visibleIndex].addEventListener("click",a),h[u.filterIndex].addEventListener("click",l),d.addEventListener("action:select-position",t),f[u.starIndex].addEventListener("click",v=>{const S=s(v).dataset.id,x=nn;x.tryParseString(S);const{selectedSegments:b}=i.segmentationGroupState.value;b.set(x,!b.has(x))})}}class Os{constructor(e,t){if(this.displayState=e,this.template=t,e!==void 0){let n=Mm.get(e);n===void 0&&(n=RD(e),Mm.set(e,n)),this.registerEventHandlers=n}}static make(e,t){return new Os(e,t?DD:vd)}get(e){const{displayState:t}=this;return this.getWithNormalizedId(ji(t,e))}getWithNormalizedId(e){const{displayState:t}=this,{template:n}=this,s=n.template.cloneNode(!0),r=e.key,o=e.value??r,a=o.toString();s.dataset.id=a;const{children:l}=s,c=l[0].children,d=c[n.idContainerIndex];d.children[n.idIndex].textContent=a;const{unmappedIdIndex:u}=n;if(t!==void 0?this.registerEventHandlers(s,n):c[n.visibleIndex].style.display="none",u!==-1){const h=d.children[u];if(M.R.equal(r,o)){h.style.display="none";const f=c[n.copyContainerIndex];f.children[n.unmappedCopyIndex].style.display="none"}else{const f=r.toString();s.dataset.unmappedId=f,h.textContent=f,t!==void 0&&Am(t.segmentationGroupState.value.maxIdLength,f)}}return l[n.labelIndex].textContent=e.label??"",t!==void 0&&(this.updateWithId(s,o),Am(t.segmentationGroupState.value.maxIdLength,a)),s}update(e){const t=nn,n=e.dataset.id;n!==void 0&&(t.parseString(n),this.updateWithId(e,t))}updateWithId(e,t){const{children:n}=e,s=n[0].children,{template:r}=this,{displayState:o}=this,{segmentSelectionState:a}=o,{visibleSegments:l}=o.segmentationGroupState.value;s[r.visibleIndex].classList.toggle("neuroglancer-visible",l.has(t)),e.dataset.selected=(a.hasSelectedSegment&&M.R.equal(a.selectedSegment,t)).toString();const{selectedSegments:c}=o.segmentationGroupState.value;s[r.starIndex].classList.toggle("neuroglancer-starred",c.has(t));const d=s[r.idContainerIndex];Nm(d.children[r.idIndex],bd(this.displayState,t));const{unmappedIdIndex:u}=r;if(u!==-1){let h,f;if(o.baseSegmentColoring.value&&(h=e.dataset.unmappedId)!==void 0){const m=nn;m.parseString(h),f=bd(this.displayState,m)}else f=w.Oi;Nm(d.children[u],f)}}}function Nm(i,e){i.style.backgroundColor=Sm(e),i.style.color=Ve(e)?"white":"black"}class Om extends Os{constructor(e,t,n){const s=e.segmentationGroupState.value.segmentPropertyMap.value,r=(s?.numericalProperties??[]).filter(n),o=ID(r.length);super(e,o),this.parentElement=t,this.segmentPropertyMap=s,this.numericalProperties=r,(this.numericalPropertyWidths=new Array(this.numericalProperties.length)).fill(0)}getWithNormalizedId(e){const t=super.getWithNormalizedId(e),{numericalProperties:n}=this,{numericalPropertyIndices:s}=this.template;if(s.length>0){const r=this.segmentPropertyMap?.getSegmentInlineIndex(e.value??e.key)??-1;if(r!==-1){const{numericalPropertyWidths:o}=this;for(let a=0,l=s.length;a<l;++a){const c=n[a].values[r];if(!Number.isNaN(c)){const d=c.toString(),u=d.length;u>o[a]&&(o[a]=u,this.parentElement.style.setProperty(`--neuroglancer-column-${a}-width`,`${u}ch`)),t.children[s[a]].textContent=d}}}}return t}makeHeaderLabel(e,t,n){const s=document.createElement("span");s.textContent=e,s.classList.add("neuroglancer-segment-list-header-label"),s.classList.add("neuroglancer-segment-list-header-label"),e==="label"&&(n.style.textAlign="left");const r=document.createElement("span");r.classList.add("neuroglancer-segment-list-header-label-sort"),s.appendChild(r),r.textContent="\u25B2";const o=YC(s).width;return this.parentElement.style.setProperty(t,`${o}px`),n.appendChild(s),{id:e,label:s,sortIcon:r}}getHeader(){const{template:e}=this,t=e.template.cloneNode(!0),{children:n}=t,s=n[0].children,r=s[e.copyContainerIndex];r.style.visibility="hidden",s[e.visibleIndex].style.visibility="hidden",n[e.filterIndex].style.visibility="hidden";const o=s[e.idContainerIndex],a=[this.makeHeaderLabel("id","--neuroglancer-id-column-label-width",o.children[e.idIndex]),this.makeHeaderLabel("label","--neuroglancer-label-column-label-width",n[e.labelIndex])],{numericalProperties:l}=this,{numericalPropertyIndices:c}=this.template;for(let d=0,u=c.length;d<u;++d){const h=l[d],f=this.makeHeaderLabel(h.id,`--neuroglancer-column-${d}-label-width`,t.children[c[d]]),{description:m}=h;m&&(f.label.title=m),a.push(f)}return{container:t,propertyLabels:a}}}function yd(i,e){return Os.make(i??void 0,!0).getWithNormalizedId(e)}function Vs(i,e,t){e.registerDisposer((0,A.aM)((n,s)=>{$E(n,s,t)},i.segmentationGroupState)),e.registerDisposer((0,A.aM)((n,s)=>{n.registerDisposer(s.segmentColorHash.changed.add(t)),n.registerDisposer(s.segmentDefaultColor.changed.add(t))},i.segmentationColorGroupState)),e.registerDisposer(i.saturation.changed.add(t)),e.registerDisposer(i.segmentSelectionState.changed.add(t)),e.registerDisposer(i.baseSegmentColoring.changed.add(t)),e.registerDisposer(i.hoverHighlight.changed.add(t))}function Vm(i,e){const t=e.redrawNeeded.dispatch;Vs(i,e,t),e.registerDisposer((0,A.aM)((n,s)=>{GE(n,s,t)},i.segmentationGroupState))}function kD(i,e){Vm(i,e),e.registerDisposer(i.objectAlpha.changed.add(e.redrawNeeded.dispatch))}function Sd(i,e){kD(i,e),e.registerDisposer(i.transform.changed.add(e.redrawNeeded.dispatch)),e.registerDisposer(i.renderScaleTarget.changed.add(e.redrawNeeded.dispatch)),e.registerDisposer(i.transparentPickEnabled.changed.add(e.redrawNeeded.dispatch))}const _m=w.ln.create(),nn=new M.R;function bd(i,e,t=_m){if(i==null)return t.fill(1),t;const n=i.segmentationColorGroupState.value,{segmentStatedColors:s}=n;if(s.size!==0&&n.segmentStatedColors.get(e,nn))return t[0]=(nn.low&255)/255,t[1]=((nn.low&65280)>>>8)/255,t[2]=((nn.low&16711680)>>>16)/255,t;const r=n.segmentDefaultColor.value;return r!==void 0?(t[0]=r[0],t[1]=r[1],t[2]=r[2],t):(n.segmentColorHash.compute(t,e),t)}function LD(i,e,t=1){const n=_m;n[3]=t,bd(i,e,n);let s=i.saturation.value;i.hoverHighlight.value&&i.segmentSelectionState.isSelected(e)&&(s>.5?s=s-=.5:s+=.5);for(let r=0;r<3;++r)n[r]=n[r]*s+(1-s);return n[0]*=t,n[1]*=t,n[2]*=t,n}function Bm(i,e={}){for(const t of tg)e[t]=i[t].rpcId;return e}const PD=ir(Cr);class ya extends PD{constructor(e,t,n){super(n),this.chunkManager=e,this.displayState=t;const s=t.segmentationGroupState.value;for(const r of tg)this.registerDisposer(s[r].addRef())}initializeCounterpartWithChunkManager(e){const{displayState:t}=this;e.chunkManager=this.chunkManager.rpcId,Bm(t.segmentationGroupState.value,e),e.transform=this.registerDisposer(ut.makeFromExisting(this.chunkManager.rpc,this.displayState.transform)).rpcId,e.renderScaleTarget=this.registerDisposer(ut.makeFromExisting(this.chunkManager.rpc,this.displayState.renderScaleTarget)).rpcId,super.initializeCounterpart(this.chunkManager.rpc,e)}}function wd(i,e,t,n,s){const r=Math.min(1,i.objectAlpha.value),o=i.baseSegmentColoring.value;Ds(i.segmentationGroupState.value,(a,l)=>{const c=n?.registerUint64(e,a),d=t?LD(i,o?a:l,r):void 0;s(a,d,c,l)})}var AD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,Fm=(i,e,t,n)=>{for(var s=n>1?void 0:n?MD(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&AD(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ND=w.pB.create(),sn=w.w0.create(),Um=!1;function $m(i,e){e.vertexBuffer=At.fromData(i,e.meshData.vertexPositions,i.ARRAY_BUFFER,i.STATIC_DRAW),e.indexBuffer=At.fromData(i,e.meshData.indices,i.ELEMENT_ARRAY_BUFFER,i.STATIC_DRAW),e.normalBuffer=At.fromData(i,e.meshData.vertexNormals,i.ARRAY_BUFFER,i.STATIC_DRAW)}function Gm(i){i.vertexBuffer.dispose(),i.indexBuffer.dispose(),i.normalBuffer.dispose()}const OD=`
highp vec3 decodeNormalOctahedronSnorm8(highp vec2 e) {
  vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));
  if (v.z < 0.0) v.xy = (1.0 - abs(v.yx)) * vec2(v.x > 0.0 ? 1.0 : -1.0, v.y > 0.0 ? 1.0 : -1.0);
  return normalize(v);
}
`;function zm(i){return i>=128&&(i=i-256),Math.max(-1,i/127)}function P_(i){let e=i.length;e-=1;const t=new Float32Array(Math.floor(i.length/2)*3);let n=0;for(let s=0;s<e;s+=2){const r=zm(i[s]),o=zm(i[s+1]);let a=r,l=o;const c=1-Math.abs(r)-Math.abs(o);c<0&&(a=(1-Math.abs(l))*(a>0?1:-1),l=(1-Math.abs(a))*(l>0?1:-1));const d=Math.sqrt(a**2+l**2+c**2);t[n]=a/d,t[n+1]=l/d,t[n+2]=c/d,n+=3}return t}function Wm(i){return{defineShader:e=>{e.addAttribute("highp vec3","aVertexPosition"),e.addVertexCode("highp vec3 getVertexPosition() { return aVertexPosition; }")},bind(e,t,n){n.vertexBuffer.bindToVertexAttrib(t.attribute("aVertexPosition"),3,i,!0)},endLayer:(e,t)=>{e.disableVertexAttribArray(t.attribute("aVertexPosition"))}}}const VD={[yn.Pc.float32]:Wm(WebGL2RenderingContext.FLOAT),[yn.Pc.uint16]:Wm(WebGL2RenderingContext.UNSIGNED_SHORT),[yn.Pc.uint10]:{defineShader:i=>{i.addAttribute("highp uint","aVertexPosition"),i.addVertexCode(`
highp vec3 getVertexPosition() {
  return vec3(float(aVertexPosition & 1023u),
              float((aVertexPosition >> 10) & 1023u),
              float((aVertexPosition >> 20) & 1023u)) / 1023.0;
}
`)},bind(i,e,t){t.vertexBuffer.bindToVertexAttribI(e.attribute("aVertexPosition"),1,WebGL2RenderingContext.UNSIGNED_INT)},endLayer:(i,e)=>{i.disableVertexAttribArray(e.attribute("aVertexPosition"))}}};class Hm{constructor(e,t){this.fragmentRelativeVertices=e,this.vertexPositionFormat=t,this.tempLightVec=new Float32Array(4),this.vertexPositionHandler=VD[this.vertexPositionFormat]}beginLayer(e,t,n,s){const{lightDirection:r,ambientLighting:o,directionalLighting:a}=n,l=this.tempLightVec;w.eR.scale(l,r,a),l[3]=o,e.uniform4fv(t.uniform("uLightDirection"),l);const c=s.silhouetteRendering.value;c>0&&e.uniform1f(t.uniform("uSilhouettePower"),c)}setColor(e,t,n){e.uniform4fv(t.uniform("uColor"),n)}setPickID(e,t,n){e.uniform1ui(t.uniform("uPickID"),n)}beginModel(e,t,n,s){const{projectionParameters:r}=n;e.uniformMatrix4fv(t.uniform("uModelViewProjection"),!1,w.pB.multiply(ND,r.viewProjectionMat,s)),(0,w._A)(sn,s),(0,w.Jh)(sn,sn,r.displayDimensionRenderInfo.canonicalVoxelFactors),w.w0.invert(sn,sn),w.w0.transpose(sn,sn),e.uniformMatrix3fv(t.uniform("uNormalMatrix"),!1,sn)}drawFragmentHelper(e,t,n,s,r){this.vertexPositionHandler.bind(e,t,n);const{meshData:o}=n;n.normalBuffer.bindToVertexAttrib(t.attribute("aVertexNormal"),2,WebGL2RenderingContext.BYTE,!0),n.indexBuffer.bind();const{indices:a}=o;e.drawElements(o.strips?WebGL2RenderingContext.TRIANGLE_STRIP:WebGL2RenderingContext.TRIANGLES,r-s,a.BYTES_PER_ELEMENT===2?WebGL2RenderingContext.UNSIGNED_SHORT:WebGL2RenderingContext.UNSIGNED_INT,s*a.BYTES_PER_ELEMENT)}drawFragment(e,t,n){const{meshData:s}=n,{indices:r}=s;this.drawFragmentHelper(e,t,n,0,r.length)}drawMultiscaleFragment(e,t,n,s,r){const o=n.meshData.subChunkOffsets[s],a=n.meshData.subChunkOffsets[r];this.drawFragmentHelper(e,t,n,o,a)}endLayer(e,t){this.vertexPositionHandler.endLayer(e,t),e.disableVertexAttribArray(t.attribute("aVertexNormal"))}makeGetter(e){const t=e.registerDisposer((0,A.Uq)(n=>n>0,[e.displayState.silhouetteRendering]));return Ii(e,e.gl,{memoizeKey:`mesh/MeshShaderManager/${this.fragmentRelativeVertices}/${this.vertexPositionFormat}`,parameters:t,defineShader:(n,s)=>{this.vertexPositionHandler.defineShader(n),n.addAttribute("highp vec2","aVertexNormal"),n.addVarying("highp vec4","vColor"),n.addUniform("highp vec4","uLightDirection"),n.addUniform("highp vec4","uColor"),n.addUniform("highp mat3","uNormalMatrix"),n.addUniform("highp mat4","uModelViewProjection"),n.addUniform("highp uint","uPickID"),s&&n.addUniform("highp float","uSilhouettePower"),this.fragmentRelativeVertices&&(n.addUniform("highp vec3","uFragmentOrigin"),n.addUniform("highp vec3","uFragmentShape")),n.addVertexCode(OD);let r="";this.fragmentRelativeVertices?r+=`
highp vec3 vertexPosition = uFragmentOrigin + uFragmentShape * getVertexPosition();
highp vec3 normalMultiplier = 1.0 / uFragmentShape;
`:r+=`
highp vec3 vertexPosition = getVertexPosition();
highp vec3 normalMultiplier = vec3(1.0, 1.0, 1.0);
`,r+=`
gl_Position = uModelViewProjection * vec4(vertexPosition, 1.0);
vec3 origNormal = decodeNormalOctahedronSnorm8(aVertexNormal);
vec3 normal = normalize(uNormalMatrix * (normalMultiplier * origNormal));
float absCosAngle = abs(dot(normal, uLightDirection.xyz));
float lightingFactor = absCosAngle + uLightDirection.w;
vColor = vec4(lightingFactor * uColor.rgb, uColor.a);
`,s&&(r+=`
vColor *= pow(1.0 - absCosAngle, uSilhouettePower);
`),n.setVertexMain(r),n.setFragmentMain("emit(vColor, uPickID);")}})}}class Sa extends $i{constructor(e,t,n){super(),this.chunkManager=e,this.source=t,this.displayState=n,this.meshShaderManager=new Hm(!1,yn.Pc.float32),this.getShader=this.meshShaderManager.makeGetter(this),Sd(n,this),this.registerDisposer(n.silhouetteRendering.changed.add(this.redrawNeeded.dispatch));const s=this.backend=this.registerDisposer(new ya(e,n,this.layerChunkProgressInfo));s.RPC_TYPE_ID=yn.Of,s.initializeCounterpartWithChunkManager({source:t.addCounterpartRef()}),s.visibility.add(this.visibility),this.registerDisposer(n.renderScaleHistogram.visibility.add(this.visibility))}get isTransparent(){const{displayState:e}=this;return e.objectAlpha.value<1||e.silhouetteRendering.value>0}get transparentPickEnabled(){return this.displayState.transparentPickEnabled.value}get gl(){return this.chunkManager.chunkQueueManager.gl}draw(e,t){if(!e.emitColor&&e.alreadyEmittedPickID)return;const{gl:n,displayState:s,meshShaderManager:r}=this;if(s.objectAlpha.value<=0)return;const o=sr(s.transform.value,e.projectionParameters.displayDimensionRenderInfo,t);if(o===void 0)return;const{shader:a}=this.getShader(e.emitter);if(a===null)return;a.bind(),r.beginLayer(n,a,e,this.displayState),r.beginModel(n,a,e,o);const l=this.source.chunks;let c=0,d=0;const{renderScaleHistogram:u}=this.displayState,h=this.source.fragmentSource.chunks;wd(s,this,e.emitColor,e.emitPickID?e.pickIDs:void 0,(f,m,g)=>{const v=vn(f),y=l.get(v);if(++c,y!==void 0){++d,e.emitColor&&r.setColor(n,a,m),e.emitPickID&&r.setPickID(n,a,g),c+=y.fragmentIds.length;for(const S of y.fragmentIds){const{key:x}=this.source.getFragmentKey(v,S),b=h.get(x);b!==void 0&&b.state===Be.GPU_MEMORY&&(r.drawFragment(n,a,b),++d)}}}),e.emitColor&&(u.begin(this.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber),u.add(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,d,c-d)),r.endLayer(n,a)}isReady(){const{displayState:e,source:t}=this;let n=!0;const s=t.fragmentSource.chunks;return Ds(e.segmentationGroupState.value,r=>{const o=vn(r),a=t.chunks.get(o);if(a===void 0){n=!1;return}for(const l of a.fragmentIds){const{key:c}=this.source.getFragmentKey(o,l),d=s.get(c);if(d===void 0||d.state!==Be.GPU_MEMORY){n=!1;return}}}),n}getObjectPosition(e,t){const n=this.displayState.transform.value;if(n.error!==void 0)return;const s=vn(e),r=this.source.chunks.get(s);if(r===void 0)return;const{rank:o}=n,a=new Float32Array(n.modelToRenderLayerTransform.length);we.DI(a,o+1,n.modelToRenderLayerTransform,o+1,o+1);const l=new Float32Array(o);we.vo(l,a,o+1,t,o);const{fragmentIds:c}=r;let d=0;const u=[];for(const S of c){const{key:x}=this.source.getFragmentKey(s,S),b=this.source.fragmentSource.chunks.get(x);if(b===void 0)continue;const{state:E,meshData:C}=b;E!==Be.SYSTEM_MEMORY&&E!==Be.GPU_MEMORY||(d+=C.vertexPositions.length/o,u.push(b))}const f=100*1e3/d,m=Math.max(1,Math.floor(1/f)),g=new Float32Array(o);let v=Number.POSITIVE_INFINITY;for(const S of u){const{meshData:x}=S,{vertexPositions:b}=x;if(!(b.length<o))for(let E=0;E<b.length;E+=o*m){let C=0;for(let k=0;k<o;k++)C+=(b[E+k]-l[k])**2;if(C<v){v=C;for(let k=0;k<o;k++)g[k]=b[E+k]}}}if(v===Number.POSITIVE_INFINITY)return;const y=new Float32Array(o);return we.vo(y,n.modelToRenderLayerTransform,o+1,g,o),y}}class _D extends Wn{constructor(e,t){super(e),this.fragmentIds=t.fragmentIds}}class BD extends Wn{constructor(e,t){super(e),this.meshData=t}copyToGPU(e){super.copyToGPU(e),$m(e,this)}freeGPUMemory(e){super.freeGPUMemory(e),Gm(this)}}class pi extends tn{constructor(){super(...arguments),this.fragmentSource=this.registerDisposer(new Cd(this.chunkManager,this))}initializeCounterpart(e,t){this.fragmentSource.initializeCounterpart(this.chunkManager.rpc,{}),t.fragmentSource=this.fragmentSource.addCounterpartRef(),super.initializeCounterpart(e,t)}getChunk(e){return new _D(this,e)}getFragmentKey(e,t){return{key:`${e}/${t}`,fragmentId:t}}}let Cd=class extends tn{constructor(i,e){super(i),this.meshSource=e}get key(){return this.meshSource.key}getChunk(i){return new BD(this,i)}};Cd=Fm([Kt(yn.dI)],Cd);function Jm(i,e,t,n){const s=i.get(om(e,t,n));return s!==void 0&&s.state===Be.GPU_MEMORY}class xd extends $i{constructor(e,t,n){super(),this.chunkManager=e,this.source=t,this.displayState=n,this.meshShaderManager=new Hm(this.source.format.fragmentRelativeVertices,this.source.format.vertexPositionFormat),this.getShader=this.meshShaderManager.makeGetter(this),Sd(n,this),this.registerDisposer(n.silhouetteRendering.changed.add(this.redrawNeeded.dispatch));const s=this.backend=this.registerDisposer(new ya(e,n,this.layerChunkProgressInfo));s.RPC_TYPE_ID=yn.Yo,s.initializeCounterpartWithChunkManager({source:t.addCounterpartRef()}),s.visibility.add(this.visibility),this.registerDisposer(n.renderScaleHistogram.visibility.add(this.visibility))}get isTransparent(){const{displayState:e}=this;return e.objectAlpha.value<1||e.silhouetteRendering.value>0}get transparentPickEnabled(){return this.displayState.transparentPickEnabled.value}get gl(){return this.chunkManager.chunkQueueManager.gl}draw(e,t){if(!e.emitColor&&e.alreadyEmittedPickID)return;const{gl:n,displayState:s,meshShaderManager:r}=this;if(s.objectAlpha.value<=0)return;const o=sr(s.transform.value,e.projectionParameters.displayDimensionRenderInfo,t);if(o===void 0)return;const{shader:a}=this.getShader(e.emitter);if(a===null)return;a.bind(),r.beginLayer(n,a,e,this.displayState);const{renderScaleHistogram:l}=this.displayState;e.emitColor&&l.begin(this.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber),(0,w._A)(sn,o),(0,w.Jh)(sn,sn,e.projectionParameters.displayDimensionRenderInfo.voxelPhysicalScales);const c=Math.abs(w.w0.determinant(sn))**(1/3),{chunks:d}=this.source,u=this.source.fragmentSource.chunks,{projectionParameters:h}=e,f=w.pB.multiply(w.pB.create(),h.viewProjectionMat,o),m=(0,w._S)(new Float32Array(24),f),g=this.displayState.renderScaleTarget.value,{fragmentRelativeVertices:v}=this.source.format;r.beginModel(n,a,e,o);let y=0,S=0;wd(s,this,e.emitColor,e.emitPickID?e.pickIDs:void 0,(x,b,E)=>{const C=vn(x),k=d.get(C);if(++y,k===void 0)return;++S;const{manifest:T}=k,{octree:L,chunkShape:_,chunkGridSpatialOrigin:R,vertexOffsets:P}=T;if(Um)try{YT(L)}catch(V){console.log(`invalid octree for object=${x}: ${V.message}`)}e.emitColor&&r.setColor(n,a,b),e.emitPickID&&r.setPickID(n,a,E),rm(T,f,m,g,h.width,h.height,(V,$,Q)=>{const K=Jm(u,C,V,$);return e.emitColor&&l.add(T.lodScales[V]*c,Q,K?1:0,K?0:1),K},(V,$,Q,K)=>{const ee=om(C,V,$),ce=u.get(ee),fe=L[5*$],le=L[5*$+1],ve=L[5*$+2],Ie=1<<V;if(v&&(n.uniform3f(a.uniform("uFragmentOrigin"),R[0]+fe*_[0]*Ie+P[V*3+0],R[1]+le*_[1]*Ie+P[V*3+1],R[2]+ve*_[2]*Ie+P[V*3+2]),n.uniform3f(a.uniform("uFragmentShape"),_[0]*Ie,_[1]*Ie,_[2]*Ie)),Um){const mt=`lod=${V}, chunkIndex=${$}, subChunkBegin=${Q}, subChunkEnd=${K}, uFragmentOrigin=${[R[0]+fe*_[0]*Ie+P[V*3+0],R[1]+le*_[1]*Ie+P[V*3+1],R[2]+ve*_[2]*Ie+P[V*3+2]]}, uFragmentShape=${[_[0]*Ie,_[1]*Ie,_[2]*Ie]}`,Fe=e.pickIDs.registerUint64(this,x,1,mt);e.emitPickID&&r.setPickID(n,a,Fe)}r.drawMultiscaleFragment(n,a,ce,Q,K)})}),l.add(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,S,y-S),r.endLayer(n,a)}isReady(e,t){const{displayState:n}=this;if(n.objectAlpha.value<=0)return!0;const s=sr(n.transform.value,e.projectionParameters.displayDimensionRenderInfo,t);if(s===void 0)return!1;const{chunks:r}=this.source,o=this.source.fragmentSource.chunks,{projectionParameters:a}=e,l=w.pB.multiply(w.pB.create(),a.viewProjectionMat,s),c=(0,w._S)(new Float32Array(24),l),d=this.displayState.renderScaleTarget.value;let u=!0;return Ds(n.segmentationGroupState.value,h=>{if(!u)return;const f=vn(h),m=r.get(f);if(m===void 0){u=!1;return}const{manifest:g}=m;rm(g,l,c,d,a.width,a.height,(v,y)=>(u=u&&Jm(o,f,v,y),u),()=>{})}),u}getObjectPosition(e){const t=this.displayState.transform.value;if(t.error!==void 0)return;const n=this.source.chunks.get(vn(e));if(n===void 0)return;const{manifest:s}=n,{clipLowerBound:r,clipUpperBound:o}=s,{rank:a}=t,l=new Float32Array(a);for(let d=0;d<3;++d)l[d]=(r[d]+o[d])/2;const c=new Float32Array(a);return we.vo(c,t.modelToRenderLayerTransform,a+1,l,a),c}}class FD extends Wn{constructor(e,t){super(e),this.manifest=t.manifest}}class UD extends Wn{constructor(e,t){super(e),this.meshData=t}copyToGPU(e){super.copyToGPU(e),$m(e,this)}freeGPUMemory(e){super.freeGPUMemory(e),Gm(this)}}class ba extends tn{constructor(e,t){super(e,t),this.fragmentSource=this.registerDisposer(new Ed(this.chunkManager,this)),this.format=t.format}static encodeOptions(e){return{format:e.format,...tn.encodeOptions(e)}}initializeCounterpart(e,t){this.fragmentSource.initializeCounterpart(this.chunkManager.rpc,{}),t.fragmentSource=this.fragmentSource.addCounterpartRef(),t.format=this.format,super.initializeCounterpart(e,t)}getChunk(e){return new FD(this,e)}}let Ed=class extends tn{constructor(i,e){super(i),this.meshSource=e}get key(){return this.meshSource.key}getChunk(i){return new UD(this,i)}};Ed=Fm([Kt(yn.pi)],Ed);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function A_(i){let e=0;const t=i.length;for(let n=0;n<t;++n)e=e*31+i.charCodeAt(n)|0;return e}function jm(i,e){return e=Math.imul(e,3432918353)>>>0,e=(e<<15|e>>>17)>>>0,e=Math.imul(e,461845907)>>>0,i^=e,i=(i<<13|i>>>19)>>>0,i=Math.imul(i,5)+3864292196>>>0,i}function $D(i,e){return i^=e,i^=i>>>16,i=Math.imul(i,2246822507)>>>0,i^=i>>>13,i*=3266489909,i^=i>>>16,i>>>0}function Ym(i,e,t){let n=i;return n=jm(n,e),n=jm(n,t),$D(n,8)}function wa(i){return i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i}function Qm(i,e){return i<<e|i>>>32-e}function M_(i,e,t,n){let s=e,r=e,o=e,a=e;const l=597399067,c=2869860233,d=951274213;let u=Math.imul(n,c);u=Qm(u,16),u=Math.imul(u,d),r^=u;let h=Math.imul(t,l);h=Qm(h,15),h=Math.imul(h,c),s^=h;const f=8;return s^=f,r^=f,o^=f,a^=f,s=s+r>>>0,s=s+o>>>0,s=s+a>>>0,r=r+s>>>0,o=o+s>>>0,a=a+s>>>0,s=wa(s),r=wa(r),o=wa(o),a=wa(a),s=s+r>>>0,s=s+o>>>0,s=s+a>>>0,r=r+s>>>0,i.low=s,i.high=r,i}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class GD extends tn{constructor(e,t){super(e,t),this.properties=t.properties}static encodeOptions(e){return{properties:e.properties}}}function zD(i,e,t){const n=i.length-1;for(;;){if(e=e&n,i[e]===0){i[e]=t;return}++e}}function _s(i,e){return e<=255?new Uint8Array(i):e<=65535?new Uint16Array(i):new Uint32Array(i)}function WD(i){const e=i.length/2,n=2**(Math.ceil(Math.log2(e))+1),s=_s(n,e+1);for(let r=0;r<e;++r){const o=i[2*r],a=i[2*r+1];zD(s,Ym(0,o,a),r+1)}return s}function HD(i,e,t,n){let s=Ym(0,t,n);const r=i.length-1;for(;;){s=s&r;let o=i[s];if(o===0)return-1;if(--o,e[2*o]===t&&e[2*o+1]===n)return o;++s}}class qm{constructor(e){this.inlineProperties=e.inlineProperties}}class JD{constructor(e){this.segmentPropertyMap=e;const{inlineProperties:t}=e;t!==void 0&&(this.inlineIdToIndex=WD(t.ids)),this.tags=t?.properties.find(n=>n.type==="tags"),this.labels=t?.properties.find(n=>n.type==="label"),this.numericalProperties=t?.properties.filter(n=>n.type==="number")??[]}getSegmentInlineIndex(e){const{inlineIdToIndex:t}=this;return t===void 0?-1:HD(t,this.segmentPropertyMap.inlineProperties.ids,e.low,e.high)}getSegmentLabel(e){const t=this.getSegmentInlineIndex(e);if(t===-1)return;const{labels:n,tags:s}=this;let r="";if(n!==void 0&&(r=n.values[t]),s!==void 0){const{tags:o,values:a}=s,l=a[t];for(let c=0,d=l.length;c<d;++c){const u=o[l.charCodeAt(c)];r.length>0&&(r+=" "),r+="#",r+=u}}if(r.length!==0)return r}}function Km(i,e,t){for(let n=0,s=t.length;n<s;++n)e[t[n]]=i[n]}function jD(i){const e=i.length;if(e===0)return!0;let t=i[0],n=i[1];for(let s=0;s<e;s+=2){const r=i[s],o=i[s+1];if((o-n||r-t)<=0)return!1;t=r,n=o}return!0}function YD(i){const{ids:e}=i;if(jD(e))return i;const t=e.length/2,n=_s(t,t-1);for(let o=0;o<t;++o)n[o]=o;n.sort((o,a)=>{const l=e[o*2],c=e[o*2+1],d=e[a*2],u=e[a*2+1];return c-u||l-d});const s=new Uint32Array(t*2);for(let o=0;o<t;++o){const a=n[o];s[o*2]=e[a*2],s[o*2+1]=e[a*2+1]}const r=i.properties.map(o=>{const{values:a}=o,l=new a.constructor(t);for(let c=0;c<t;++c)l[c]=a[n[c]];return{...o,values:l}});return{ids:s,properties:r}}function QD(i,e,t){const n=new Array(e);return n.fill(""),Km(i.values,n,t),{...i,values:n}}function qD(i,e,t){const n=new Float32Array(e);return n.fill(Number.NaN),Km(i.values,n,t),{...i,values:n}}function Xm(i,e,t){const{type:n}=i;return n==="label"||n==="description"||n==="string"||n==="tags"?QD(i,e,t):qD(i,e,t)}function KD(i,e){if(i===void 0)return e;if(e===void 0)return i;let t=0;const n=i.ids.length/2,s=e.ids.length/2,r=new Uint32Array(n),o=new Uint32Array(s),a=i.ids,l=e.ids;(0,z.NT)(n,s,(u,h)=>{const f=a[2*u+1],m=a[2*u],g=l[2*h+1],v=l[2*h];return f-g||m-v},u=>{r[u]=t,++t},u=>{o[u]=t,++t},(u,h)=>{r[u]=t,o[h]=t,++t});let c;if(t===n)c=a;else if(t===s)c=l;else{c=new Uint32Array(t*2);for(let u=0;u<n;++u){const h=r[u];c[2*h]=a[2*u],c[2*h+1]=a[2*u+1]}for(let u=0;u<s;++u){const h=o[u];c[2*h]=l[2*u],c[2*h+1]=l[2*u+1]}}const d=[];if(t===n)d.push(...i.properties);else for(const u of i.properties)d.push(Xm(u,t,r));if(t===s)d.push(...e.properties);else for(const u of e.properties)d.push(Xm(u,t,o));return{ids:c,properties:d}}function XD(i,e){return new qm({inlineProperties:KD(i.inlineProperties,e.inlineProperties)})}function ZD(i){for(;;){if(i.length===0)return;if(i.length===1)return i[0];const e=[];for(let t=0,n=i.length;t<n;t+=2)t+1===n?e.push(i[t]):e.push(XD(i[t],i[t+1]));i=e}}function eI(i,e){return i.memoize.getUncounted({id:"getPreprocessedSegmentPropertyMap",maps:e.map(t=>St(t))},()=>{const t=ZD(e);if(t!==void 0)return new JD(t)})}const tI=/^[,\s]*[0-9]+(?:[,\s]+[0-9]+)*[,\s]*$/;function nI(i,e){if(e.match(tI)!==null){const d=e.split(/[\s,]+/),u=[],h=new Set;for(let f=0,m=d.length;f<m;++f){const g=d[f];if(g==="")continue;const v=new M.R;if(!v.tryParseString(g))continue;const y=v.toString();h.has(y)||(h.add(y),u.push(v))}return u.sort(M.R.compare),{ids:u}}const t={regexp:void 0,prefix:void 0,includeTags:[],excludeTags:[],numericalConstraints:[],sortBy:[],includeColumns:[]},n=i?.segmentPropertyMap.inlineProperties?.properties,r=i?.tags?.tags||[],o=r.map(d=>d.toLowerCase()),a=i?.labels,l=[];let c;for(let d=0;d<e.length;d=c){let u=e.indexOf(" ",d);u===-1?c=u=e.length:c=u+1;const h=e.substring(d,u);if(h.length===0)continue;const f=(g,v)=>{const y=g.toLowerCase(),S=o.indexOf(y);if(S===-1){l.push({begin:v,end:u,message:`Invalid tag: ${g}`});return}if(g=r[S],t.includeTags.includes(g)||t.excludeTags.includes(g)){l.push({begin:v,end:u,message:`Duplicate tag: ${g}`});return}return g};if(h.startsWith("#")){const g=f(h.substring(1),d+1);g!==void 0&&t.includeTags.push(g);continue}if(h.startsWith("-#")){const g=f(h.substring(2),d+2);g!==void 0&&t.excludeTags.push(g);continue}if(h.startsWith("<")||h.startsWith(">")){let g=h.substring(1).toLowerCase();if(g!=="id"&&g!=="label"){const v=n?.find(y=>y.id.toLowerCase()===g&&(y.type==="number"||y.type==="label"||y.type==="string"));if(v===void 0){l.push({begin:d+1,end:u,message:`Invalid field: ${g}`});continue}g=v.id}if(t.sortBy.find(v=>v.fieldId===g)!==void 0){l.push({begin:d+1,end:u,message:`Duplicate sort field: ${g}`});continue}t.sortBy.push({order:h[0],fieldId:g});continue}if(h.startsWith("|")){let g=h.substring(1).toLowerCase();if(g==="id"||g==="label")continue;const v=n?.find(y=>y.id.toLowerCase()===g&&(y.type==="number"||y.type==="string"));if(v===void 0){l.push({begin:d+1,end:u,message:`Invalid field: ${g}`});continue}if(g=v.id,t.sortBy.find(y=>y.fieldId===g)||t.includeColumns.find(y=>y===g))continue;t.includeColumns.push(g);continue}if(h.startsWith("/")){if(t.regexp!==void 0){l.push({begin:d,end:u,message:"Only one regular expression allowed"});continue}if(t.prefix!==void 0){l.push({begin:d,end:u,message:"Prefix cannot be combined with regular expression"});continue}if(a===void 0&&r.length==0){l.push({begin:d,end:u,message:"No label property"});continue}try{t.regexp=new RegExp(h.substring(1))}catch{l.push({begin:d,end:u,message:"Invalid regular expression syntax"})}continue}const m=h.match(/^([a-zA-Z][a-zA-Z0-9_]*)(<|<=|=|>=|>)([0-9.].*)$/);if(m!==null){let g=m[1].toLowerCase();const v=m[2],y=i?.numericalProperties.find(T=>T.id.toLowerCase()===g);if(y===void 0){l.push({begin:d,end:d+g.length,message:`Invalid numerical field: ${g}`});continue}g=y.id;let S;try{S=qt(y.dataType,m[3])}catch(T){l.push({begin:d+m[1].length+m[2].length,end:u,message:T.message});continue}let x=t.numericalConstraints.find(T=>T.fieldId===g);x===void 0&&(x={fieldId:g,bounds:y.bounds},t.numericalConstraints.push(x));const b=Le(y.bounds,x.bounds[0]),E=Le(y.bounds,x.bounds[1]);let C=E,k=b;switch(v){case"<":C=ne(y.dataType,S,-1);break;case"<=":C=S;break;case"=":C=k=S;break;case">=":k=S;break;case">":k=ne(y.dataType,S,1);break}if(k=nt(b,k)>0?b:k,C=nt(E,C)<0?E:C,nt(k,C)>0){l.push({begin:d,end:u,message:"Constraint would not match any values"});continue}x.bounds=[k,C];continue}if(t.regexp!==void 0){l.push({begin:d,end:u,message:"Prefix cannot be combined with regular expression"});continue}if(a===void 0&&r.length==0){l.push({begin:d,end:u,message:"No label property"});continue}t.prefix!==void 0?t.prefix+=` ${h}`:t.prefix=h}return l.length>0?{errors:l}:(t.sortBy.length===0&&t.sortBy.push({fieldId:Zm(i),order:"<"}),t)}function Td(i){return"\\u"+i.toString(16).padStart(4,"0")}function iI(i,e){if(e.errors!==void 0)return{query:e,total:-1,count:0,errors:e.errors};if(e.ids!==void 0){const{ids:b}=e;return{query:e,total:-1,explicitIds:b,count:b.length}}const t=i?.segmentPropertyMap?.inlineProperties;if(t===void 0)return{query:e,count:0,total:-1};const n=t?.properties,s=t.ids.length/2,r=i?.tags?.tags?.length||0;let o=_s(s,s);const a=_s(r,r);a.fill(1);for(let b=0;b<s;++b)o[b]=b;const l=b=>{const E=o.length;let C=0;for(let k=0;k<E;++k){const T=o[k];b(T)&&(o[C]=T,++C)}o=o.subarray(0,C)},c=b=>{const E=i.tags.tagDescriptions,C=i.tags.tags;a.fill(0);for(let k=0;k<E.length;k++)E[k].match(b)!==null&&(a[k]=1),C[k].match(b)!==null&&(a[k]=1)};if(e.regexp!==void 0||e.prefix!==void 0){const{regexp:b,prefix:E}=e;if(i.labels!==void 0){const C=i.labels.values;b!==void 0&&l(k=>C[k].match(b)!==null),E!==void 0&&l(k=>C[k].startsWith(E))}if(o.length==0&&b!==void 0||i.labels==null&&b!=null){o=_s(s,s);for(let C=0;C<s;++C)o[C]=C;c(b),e.regexp=void 0}}const{includeTags:d,excludeTags:u}=e,h=i.tags;if(d.length>0||u.length>0){const{values:b,tags:E}=h,C=[];for(const R of d)C.push([E.indexOf(R),1]);for(const R of u)C.push([E.indexOf(R),0]);C.sort((R,P)=>R[0]-P[0]);let k="^",T=0;const L=R=>{R<T||(k+=`[${Td(T)}-${Td(R)}]*`)};for(const[R,P]of C)L(R-1),P&&(k+=Td(R)),T=R+1;L(65535),k+="$";const _=new RegExp(k);l(R=>b[R].match(_)!==null)}let f,m;const{numericalConstraints:g}=e;if(g.length>0){const b=i.numericalProperties,E=g.length,C=2**E-1;f=_s(o.length,C);for(let L=0;L<E;++L){const _=g[L],R=b.find(K=>K.id===_.fieldId),{values:P}=R,V=2**L,[$,Q]=_.bounds;for(let K=0,ee=o.length;K<ee;++K){const ce=P[o[K]];f[K]|=V*(ce>=$&&ce<=Q)}}m=o,o=m.slice();const k=o.length;let T=0;for(let L=0;L<k;++L)f[L]===C&&(o[T]=o[L],++T);o=o.subarray(0,T)}let v=[];if(h!==void 0){const b=[],{tags:E,values:C,tagDescriptions:k}=h,T=new Uint32Array(E.length);for(let L=0,_=o.length;L<_;++L){const R=C[o[L]];for(let P=0,V=R.length;P<V;++P)++T[R.charCodeAt(P)]}for(let L=0,_=E.length;L<_;++L){if(a[L]===0)continue;const R=T[L],P=E[L],V=k[L],$={tag:P,tagIndex:L,count:T[L],desc:V};e.includeTags.includes(P)||e.excludeTags.includes(P)?b.push($):R>0&&v.push($)}b.push(...v),v=b}const y=(b,E)=>{if(b.type!=="number"){const{values:C}=b;o.sort((k,T)=>(0,Dr.e)(C[k],C[T])*E)}else{const C=b.values;o.sort((k,T)=>(C[k]-C[T])*E)}},S=b=>{h!==void 0&&y(h,b);const E=i?.labels;E!==void 0&&y(E,b)},{sortBy:x}=e;for(let b=x.length-1;b>=0;--b){const{fieldId:E,order:C}=x[b],k=C==="<"?1:-1;if(E==="id"){if(b+1===x.length){if(C==="<")continue;o.reverse();continue}o.sort((T,L)=>k*(T-L))}else E==="label"?S(k):y(n.find(T=>T.id===E),k)}return{query:e,intermediateIndices:m,intermediateIndicesMask:f,indices:o,tags:v,count:o.length,total:s}}function sI(i,e,t){const{values:s}=e,[r,o]=t,a=o<=r?0:256/(o-r),l=new Uint32Array(258),{numericalConstraints:c}=i.query,d=c.findIndex(u=>u.fieldId===e.id);if(d===-1){const u=i.indices;for(let h=0,f=u.length;h<f;++h){const m=s[u[h]];Number.isNaN(m)||++l[Math.min(255,Math.max(-1,(m-r)*a))+1>>>0]}}else{const u=i.intermediateIndices,h=i.intermediateIndicesMask,f=2**c.length-1-2**d;for(let m=0,g=u.length;m<g;++m)if((h[m]&f)===f){const y=s[u[m]];Number.isNaN(y)||++l[Math.min(255,Math.max(-1,(y-r)*a))+1>>>0]}}return{queryResult:i,histogram:l,window:t}}function rI(i,e,t,n){if(i===void 0){t.length=0,n.length=0;return}const{numericalProperties:s}=i,r=s.length;if(e?.indices===void 0){t.length=0;return}for(let a=0;a<r;++a){const l=t[a],c=n[a],d=s[a];l!==void 0&&l.queryResult===e&&O(d.dataType,l.window,c)||(t[a]=sI(e,d,c))}}function Zm(i){return i?.tags||i?.labels?"label":"id"}function oI(i,e){const{ids:t}=e;if(t!==void 0)return t.map(a=>a.toString()).join(", ");let n="";e=e;const{prefix:s,regexp:r}=e;s!==void 0?n=s:r!==void 0&&(n=`/${r}`);for(const a of e.includeTags)n.length>0&&(n+=" "),n+=`#${a}`;for(const a of e.excludeTags)n.length>0&&(n+=" "),n+=`-#${a}`;for(const a of e.numericalConstraints){const{fieldId:l,bounds:c}=a,[d,u]=c,h=i.numericalProperties.find(f=>f.id===l);if(!O(h.dataType,h.bounds,c)){if(nt(d,u)===0){n.length>0&&(n+=" "),n+=`${l}=${d}`;continue}if(nt(d,h.bounds[0])>0){n.length>0&&(n+=" ");const f=ne(h.dataType,d,-1),m=d.toString(),g=f.toString();h.dataType!==I.FLOAT32||m.length<=g.length?n+=`${l}>=${m}`:n+=`${l}>${g}`}if(nt(u,h.bounds[1])<0){n.length>0&&(n+=" ");const f=ne(h.dataType,u,1),m=u.toString(),g=f.toString();h.dataType!==I.FLOAT32||m.length<=g.length?n+=`${l}<=${m}`:n+=`${l}<${g}`}}}let{sortBy:o}=e;if(o.length===1){const a=o[0];a.order==="<"&&a.fieldId===Zm(i)&&(o=[])}for(const a of o)n.length>0&&(n+=" "),n+=`${a.order}${a.fieldId}`;for(const a of e.includeColumns)n.length>0&&(n+=" "),n+=`|${a}`;return n}const Bs=new M.R;function aI(i,e,t){if(e===void 0)return;const{explicitIds:n}=e;if(n!==void 0){n.forEach(t);return}const{indices:s}=e;if(s!==void 0){const{ids:r}=i.segmentPropertyMap.inlineProperties;for(let o=0,a=s.length;o<a;++o){const l=s[o];Bs.low=r[l*2],Bs.high=r[l*2+1],t(Bs,o)}}}function*lI(i,e,t=!1){if(e===void 0)return;const{explicitIds:n}=e;if(n!==void 0)for(const r of n)yield r;const{indices:s}=e;if(s!==void 0){const{ids:r}=i.segmentPropertyMap.inlineProperties;for(let o=0,a=s.length;o<a;++o){const l=s[o];t?yield new M.R(r[l*2],r[l*2+1]):(Bs.low=r[l*2],Bs.high=r[l*2+1],yield Bs)}}}function ev(i,e,t){if(t.size===0)return 0;let n=0;return aI(i,e,s=>{t.has(s)&&++n}),n}function tv(i,e,t,n){const s=i.includeTags.filter(o=>o!==e),r=i.excludeTags.filter(o=>o!==e);return n===!0&&(t?s:r).push(e),{...i,includeTags:s,excludeTags:r}}function cI(i){return i.ids!==void 0?!1:i.errors!==void 0?!0:!(i.numericalConstraints.length>0||i.includeTags.length>0||i.excludeTags.length>0||i.prefix||i.regexp)}function Ca(i,e){if(i===void 0||i.ids!==void 0||i.errors!==void 0)return!1;const{sortBy:t,includeColumns:n}=i;return t.find(s=>s.fieldId===e)!==void 0||n.includes(e)}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class dI extends Gt{constructor(e){super(),this.layer=e;const{element:t}=this;t.appendChild(this.registerDisposer(new zt(e.displayState.segmentationGroupState.value.graph,(n,s,r)=>{n?.tabContents&&s.appendChild(n.tabContents(e,r,this))})).element)}}class Dd{}class Id extends D.O8{constructor(e,t){super(),this.graph=e,this.segmentsState=t}createRenderLayers(e,t,n){return[]}}function N_(i,e){let t,n;const s=()=>{const{value:a}=e;if(a===void 0){n!==void 0&&(n(),n=void 0,t=void 0);return}t!=null&&Uint64.equal(t,a)||(n!==void 0&&(n(),n=void 0,t=void 0),n=i.trackSegment(a,l=>{t=l,e.value=l??void 0}))};s();const r=e.changed.add(s);return()=>{r(),n!==void 0&&(n(),n=void 0)}}var Rd=G(9100),uI=Object.defineProperty,hI=Object.getOwnPropertyDescriptor,pI=(i,e,t,n)=>{for(var s=n>1?void 0:n?hI(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&uI(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const fI="DisjointUint64Sets",nv="DisjointUint64Sets.add",iv="DisjointUint64Sets.clear",sv="DisjointUint64Sets.highBitRepresentativeChanged",rv="DisjointUint64Sets.deleteSet";let Yi=class extends ho{constructor(){super(...arguments),this.disjointSets=new Rd.I,this.changed=new j.IY}get value(){return this}static makeWithCounterpart(i,e){const t=new Yi;return t.disjointSets.visibleSegmentEquivalencePolicy=e,t.registerDisposer(e.changed.add(()=>{ov(t)})),t.initializeCounterpart(i),e.value&&ov(t),t}disposed(){this.disjointSets=void 0,this.changed=void 0,super.disposed()}link(i,e){if(this.disjointSets.link(i,e)){const{rpc:t}=this;return t&&t.invoke(nv,{id:this.rpcId,al:i.low,ah:i.high,bl:e.low,bh:e.high}),this.changed.dispatch(),!0}return!1}linkAll(i){for(let e=1,t=i.length;e<t;++e)this.link(i[0],i[e])}has(i){return this.disjointSets.has(i)}get(i){return this.disjointSets.get(i)}clear(){if(this.disjointSets.clear()){const{rpc:i}=this;i&&i.invoke(iv,{id:this.rpcId}),this.changed.dispatch()}}setElements(i){return this.disjointSets.setElements(i)}deleteSet(i){if(this.disjointSets.deleteSet(i)){const{rpc:e}=this;e&&e.invoke(rv,{id:this.rpcId,l:i.low,h:i.high}),this.changed.dispatch()}}get size(){return this.disjointSets.size}toJSON(){return this.disjointSets.toJSON()}restoreState(i){if(i!==void 0){const e=[new M.R,new M.R];(0,p.$v)(i,t=>{(0,p.$v)(t,(n,s)=>{e[s%2].parseString(String(n),10),s!==0&&this.link(e[0],e[1])})})}}assignFrom(i){this.clear(),i instanceof Yi&&(i=i.disjointSets);for(const[e,t]of i)this.link(e,t)}};Yi=pI([po(fI)],Yi);const Fs=new M.R,kd=new M.R;dt(nv,function(i){const e=this.get(i.id);Fs.low=i.al,Fs.high=i.ah,kd.low=i.bl,kd.high=i.bh,e.disjointSets.link(Fs,kd)&&e.changed.dispatch()}),dt(iv,function(i){const e=this.get(i.id);e.disjointSets.clear()&&e.changed.dispatch()});function ov(i){i.rpc.invoke(sv,{id:i.rpcId,value:i.disjointSets.visibleSegmentEquivalencePolicy.value})}dt(sv,function(i){const e=this.get(i.id);e.disjointSets.visibleSegmentEquivalencePolicy.value=i.value}),dt(rv,function(i){const e=this.get(i.id);Fs.low=i.l,Fs.high=i.h,e.disjointSets.deleteSet(Fs)&&e.changed.dispatch()});/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class gI extends Dd{constructor(){super(...arguments),this.spanningTreeEdges=new Map,this.equivalences=new Yi,this.connections=new Set,this.changed=new j.HN}link(e,t){this.equivalences.link(e,t);for(const n of this.connections)n.segmentsState.segmentEquivalences.link(e,t)}linkAll(e){this.equivalences.linkAll(e);for(const t of this.connections)t.segmentsState.segmentEquivalences.linkAll(e)}deleteSet(e){this.equivalences.deleteSet(e);for(const t of this.connections)t.segmentsState.segmentEquivalences.deleteSet(e)}normalizeAll(){for(const e of this.connections)Ld(e.segmentsState.visibleSegments,e.segmentsState.segmentEquivalences.disjointSets)}addSpanningTreeEdge(e,t){const n=e.toString(),s=t.toString(),{spanningTreeEdges:r}=this;let o=r.get(n);o===void 0&&(o=new Set,r.set(n,o));let a=r.get(s);a===void 0&&(a=new Set,r.set(s,a)),o.add(s),a.add(n)}removeSpanningTreeEdge(e,t){const n=e.toString(),s=t.toString(),{spanningTreeEdges:r}=this,o=r.get(n),a=r.get(s);o.delete(s),o.size===0&&r.delete(n),a.delete(n),a.size===0&&r.delete(s)}*getSpanningTreeNeighbors(e){const t=new M.R,n=this.spanningTreeEdges.get(e.toString());if(n!==void 0)for(const s of n)t.parseString(s),yield t}restoreState(e){const{equivalences:t,spanningTreeEdges:n}=this;if(t.clear(),n.clear(),e===void 0)return;const s=[new M.R,new M.R];(0,p.$v)(e,r=>{(0,p.$v)(r,(o,a)=>{s[a%2].parseString(String(o),10),a!==0&&t.link(s[0],s[1])&&this.addSpanningTreeEdge(s[0],s[1])})})}toJSON(){const{spanningTreeEdges:e}=this;if(e.size===0)return;const t=new Array;for(const[n,s]of e){const r=M.R.parseString(n);for(const o of s){const a=M.R.parseString(o);M.R.compare(r,a)>0||t.push([r,a])}}return t.sort((n,s)=>M.R.compare(n[0],s[0])||M.R.compare(n[1],s[1])),t.map(n=>n.map(s=>s.toString()))}get visibleSegmentEquivalencePolicy(){return Tt.y6.MIN_REPRESENTATIVE}async merge(e,t){const{equivalences:n}=this;return M.R.equal(n.get(e),n.get(t))?e:(this.addSpanningTreeEdge(e,t),this.link(e,t),this.normalizeAll(),this.changed.dispatch(),n.get(e))}async split(e,t){const n=this.computeSplit(e,t);if(n===void 0)throw new Error("Segments are already split");const{includeBaseSegments:s,includeRepresentative:r,excludeBaseSegments:o,excludeRepresentative:a}=n,{equivalences:l}=this;this.deleteSet(e),this.linkAll(s),this.linkAll(o);const c=(h,f)=>{for(const m of h)for(const g of this.getSpanningTreeNeighbors(m))M.R.equal(l.get(g),f)||this.removeSpanningTreeEdge(m,g)},d=l.get(e),u=l.get(t);c(s,d),c(o,u);for(const h of this.connections){const{selectedSegments:f,visibleSegments:m}=h.segmentsState;f.has(a)&&(f.delete(a),f.add(r),m.add(r))}return this.normalizeAll(),this.changed.dispatch(),{include:d,exclude:u}}trackSegment(e,t){return()=>{}}computeSplit(e,t){const{equivalences:n}=this,s=n.get(e);if(!M.R.equal(s,n.get(t)))return;const r=new Rd.I;for(const u of n.setElements(s))if(!M.R.equal(u,t))for(const h of this.getSpanningTreeNeighbors(u))M.R.equal(h,t)||r.link(u,h);const o=[],a=[],l=r.get(e);let c=e,d=t;for(const u of n.setElements(s))M.R.equal(r.get(u),l)?(o.push(u),M.R.compare(u,c)<0&&(c=u)):(a.push(u),M.R.compare(u,d)<0&&(d=u));return o.sort(M.R.compare),a.sort(M.R.compare),{includeBaseSegments:o,includeRepresentative:c,excludeBaseSegments:a,excludeRepresentative:d}}connect(e){const t=e.displayState.segmentationGroupState.value,n=new mI(this,t);return t.segmentEquivalences.assignFrom(this.equivalences),Ld(t.visibleSegments,t.segmentEquivalences.disjointSets),n.registerDisposer(t.visibleSegments.changed.add(n.registerCancellable((0,xe.A)(()=>Ld(t.visibleSegments,t.segmentEquivalences.disjointSets),0)))),this.connections.add(n),n.registerDisposer(()=>{this.connections.delete(n)}),n}}function Ld(i,e){const t=[];for(const n of i.unsafeKeys()){const s=e.get(n);M.R.equal(n,s)||(t.push(s),i.delete(n))}for(const n of t)i.add(n)}class mI extends Id{computeSplit(e,t){return this.graph.computeSplit(e,t)}}var vI=G(3786);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const av=fr;function xa(i,e){i.addVertexCode(uc),i.addUniform("highp vec3","uCircleParams"),i.addVarying("highp vec4","vCircleCoord"),i.addVertexCode(`
void emitCircle(vec4 position, float diameter, float borderWidth) {
  gl_Position = position;
  float totalDiameter = diameter + 2.0 * (borderWidth + uCircleParams.z);
  if (diameter == 0.0) totalDiameter = 0.0;
  vec2 circleCornerOffset = getQuadVertexPosition(vec2(-1.0, -1.0), vec2(1.0, 1.0));
  gl_Position.xy += circleCornerOffset * uCircleParams.xy * gl_Position.w * totalDiameter;
  vCircleCoord.xy = circleCornerOffset;
  if (borderWidth == 0.0) {
    vCircleCoord.z = totalDiameter;
    vCircleCoord.w = 1e-6;
  } else {
    vCircleCoord.z = diameter / totalDiameter;
    vCircleCoord.w = uCircleParams.z / totalDiameter;
  }
}
`),e?i.addFragmentCode(`
float getCircleAlphaMultiplier() {
  return 1.0 - 2.0 * abs(0.5 - gl_FragCoord.z);
}
`):i.addFragmentCode(`
float getCircleAlphaMultiplier() {
  return 1.0;
}
`),i.addFragmentCode(`
vec4 getCircleColor(vec4 interiorColor, vec4 borderColor) {
  float radius = length(vCircleCoord.xy);
  if (radius > 1.0) {
    discard;
  }

  float borderColorFraction = clamp((radius - vCircleCoord.z) / vCircleCoord.w, 0.0, 1.0);
  float feather = clamp((1.0 - radius) / vCircleCoord.w, 0.0, 1.0);
  vec4 color = mix(interiorColor, borderColor, borderColorFraction);

  return vec4(color.rgb, color.a * feather * getCircleAlphaMultiplier());
}
`)}function Ea(i,e,t){const{gl:n}=i;n.uniform3f(i.uniform("uCircleParams"),1/e.width,1/e.height,Math.max(1e-6,t.featherWidthInPixels))}function Ta(i,e,t){Do(i,e,t)}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function fi(i){i.addAttribute("int","aDummyVertexId",0),i.addVertexCode(`
int getVertexId () {
  return aDummyVertexId + gl_VertexID;
}
#define gl_VertexID (getVertexId())
`)}class jn extends D.O8{constructor(e){super(),this.buffer=new At(e),this.size=0}disposed(){this.buffer.dispose()}enable(e=256){const{buffer:t}=this,{gl:n}=t;t.bind(),e>this.size&&(this.size=e,n.bufferData(WebGL2RenderingContext.ARRAY_BUFFER,new Int32Array(e),WebGL2RenderingContext.STATIC_DRAW)),n.vertexAttribIPointer(0,1,WebGL2RenderingContext.INT,0,0),n.vertexAttribDivisor(0,0),n.enableVertexAttribArray(0)}disable(){const{gl:e}=this.buffer;e.disableVertexAttribArray(0)}static get(e){return e.memoize.get("VertexIdHelper",()=>new jn(e))}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const yI=w.pB.create(),lv=`void main() {
  emitDefault();
}
`,_r=[],SI=zi(new As,I.FLOAT32,3);class cv extends D.O8{constructor(e,t){super(),this.base=e,this.targetIsSliceView=t,this.textureAccessHelper=new ga("vertexData"),this.vertexIdHelper=this.registerDisposer(jn.get(this.gl)),this.edgeShaderGetter=Ii(this,this.gl,{memoizeKey:{type:"skeleton/SkeletonShaderManager/edge",vertexAttributes:this.vertexAttributes},fallbackParameters:this.base.fallbackShaderParameters,parameters:this.base.displayState.skeletonRenderingOptions.shaderControlState.builderState,shaderError:this.base.displayState.shaderError,defineShader:(n,s)=>{if(s.parseResult.errors.length!==0)throw new Error("Invalid UI control specification");this.defineCommonShader(n),this.defineAttributeAccess(n),Tn(n),n.addAttribute("highp uvec2","aVertexIndex"),n.addUniform("highp float","uLineWidth");let r=`
highp vec3 vertexA = readAttribute0(aVertexIndex.x);
highp vec3 vertexB = readAttribute0(aVertexIndex.y);
emitLine(uProjection, vertexA, vertexB, uLineWidth);
highp uint lineEndpointIndex = getLineEndpointIndex();
highp uint vertexIndex = aVertexIndex.x * lineEndpointIndex + aVertexIndex.y * (1u - lineEndpointIndex);
`;n.addFragmentCode(`
vec4 segmentColor() {
  return uColor;
}
void emitRGB(vec3 color) {
  emit(vec4(color * uColor.a, uColor.a * getLineAlpha() * ${this.getCrossSectionFadeFactor()}), uPickID);
}
void emitDefault() {
  emit(vec4(uColor.rgb, uColor.a * getLineAlpha() * ${this.getCrossSectionFadeFactor()}), uPickID);
}
`),n.addFragmentCode(Es);const{vertexAttributes:o}=this,a=o.length;for(let l=1;l<a;++l){const c=o[l];n.addVarying(`highp ${c.glslDataType}`,`vCustom${l}`),r+=`vCustom${l} = readAttribute${l}(vertexIndex);
`,n.addFragmentCode(`#define ${c.name} vCustom${l}
`)}n.setVertexMain(r),Cs(s,n),n.setFragmentMainFunction(ls(s.parseResult.code))}}),this.nodeShaderGetter=Ii(this,this.gl,{memoizeKey:{type:"skeleton/SkeletonShaderManager/node",vertexAttributes:this.vertexAttributes},fallbackParameters:this.base.fallbackShaderParameters,parameters:this.base.displayState.skeletonRenderingOptions.shaderControlState.builderState,shaderError:this.base.displayState.shaderError,defineShader:(n,s)=>{if(s.parseResult.errors.length!==0)throw new Error("Invalid UI control specification");this.defineCommonShader(n),this.defineAttributeAccess(n),xa(n,this.targetIsSliceView),n.addUniform("highp float","uNodeDiameter");let r=`
highp uint vertexIndex = uint(gl_InstanceID);
highp vec3 vertexPosition = readAttribute0(vertexIndex);
emitCircle(uProjection * vec4(vertexPosition, 1.0), uNodeDiameter, 0.0);
`;n.addFragmentCode(`
vec4 segmentColor() {
  return uColor;
}
void emitRGBA(vec4 color) {
  vec4 borderColor = color;
  emit(getCircleColor(color, borderColor), uPickID);
}
void emitRGB(vec3 color) {
  emitRGBA(vec4(color, 1.0));
}
void emitDefault() {
  emitRGBA(uColor);
}
`),n.addFragmentCode(Es);const{vertexAttributes:o}=this,a=o.length;for(let l=1;l<a;++l){const c=o[l];n.addVarying(`highp ${c.glslDataType}`,`vCustom${l}`),r+=`vCustom${l} = readAttribute${l}(vertexIndex);
`,n.addFragmentCode(`#define ${c.name} vCustom${l}
`)}n.setVertexMain(r),Cs(s,n),n.setFragmentMainFunction(ls(s.parseResult.code))}})}get vertexAttributes(){return this.base.vertexAttributes}defineCommonShader(e){fi(e),e.addUniform("highp vec4","uColor"),e.addUniform("highp mat4","uProjection"),e.addUniform("highp uint","uPickID")}get gl(){return this.base.gl}defineAttributeAccess(e){const{textureAccessHelper:t}=this;t.defineShader(e);const n=this.vertexAttributes.length;for(let s=_r.length;s<n;++s)_r[s]=Symbol(`SkeletonShader.vertexAttributeTextureUnit${s}`);this.vertexAttributes.forEach((s,r)=>{e.addTextureSampler(`${pa(s.dataType)}sampler2D`,`uVertexAttributeSampler${r}`,_r[r]),e.addVertexCode(t.getAccessor(`readAttribute${r}`,`uVertexAttributeSampler${r}`,s.dataType,s.numComponents))})}getCrossSectionFadeFactor(){return this.targetIsSliceView?"(clamp(1.0 - 2.0 * abs(0.5 - gl_FragCoord.z), 0.0, 1.0))":"(1.0)"}beginLayer(e,t,n,s){const{viewProjectionMat:r}=n.projectionParameters,o=w.pB.multiply(yI,r,s);e.uniformMatrix4fv(t.uniform("uProjection"),!1,o),this.vertexIdHelper.enable()}setColor(e,t,n){e.uniform4fv(t.uniform("uColor"),n)}setPickID(e,t,n){e.uniform1ui(t.uniform("uPickID"),n)}drawSkeleton(e,t,n,s,r){const{vertexAttributes:o}=this,a=o.length,{vertexAttributeTextures:l}=s;for(let c=0;c<a;++c){const d=WebGL2RenderingContext.TEXTURE0+t.textureUnit(_r[c]);e.activeTexture(d),e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,l[c])}{t.bind();const c=t.attribute("aVertexIndex");s.indexBuffer.bindToVertexAttribI(c,2,WebGL2RenderingContext.UNSIGNED_INT),e.vertexAttribDivisor(c,1),In(t,r,this.targetIsSliceView?1:0),Dn(e,1,s.numIndices/2),e.vertexAttribDivisor(c,0),e.disableVertexAttribArray(c)}n!==null&&(n.bind(),Ea(n,r,{featherWidthInPixels:this.targetIsSliceView?1:0}),Ta(n.gl,2,s.numVertices))}endLayer(e,t){const{vertexAttributes:n}=this,s=n.length;for(let r=0;r<s;++r){const o=t.textureUnit(_r[r])+WebGL2RenderingContext.TEXTURE0;e.activeTexture(o),e.bindTexture(e.TEXTURE_2D,null)}this.vertexIdHelper.disable()}}var dv=(i=>(i[i.LINES=0]="LINES",i[i.LINES_AND_POINTS=1]="LINES_AND_POINTS",i))(dv||{});class uv extends Mi.F{constructor(e,t=e){super(dv,e,t)}}class hv extends A.DN{constructor(e,t=e){super(e,p.Mo,t)}}class bI{constructor(){this.compound=new Ai,this.shader=mo(lv),this.shaderControlState=new Fo(this.shader),this.params2d={mode:new uv(1),lineWidth:new hv(2)},this.params3d={mode:new uv(0),lineWidth:new hv(1)};const{compound:e}=this;e.add("shader",this.shader),e.add("shaderControls",this.shaderControlState),e.add("mode2d",this.params2d.mode),e.add("lineWidth2d",this.params2d.lineWidth),e.add("mode3d",this.params3d.mode),e.add("lineWidth3d",this.params3d.lineWidth)}get changed(){return this.compound.changed}reset(){this.compound.reset()}restoreState(e){e!==void 0&&this.compound.restoreState(e)}toJSON(){const e=this.compound.toJSON();for(const t of Object.values(e))if(t!==void 0)return e}}class wI extends D.O8{constructor(e,t,n){super(),this.chunkManager=e,this.source=t,this.displayState=n,this.layerChunkProgressInfo=new lo,this.redrawNeeded=new j.IY,this.fallbackShaderParameters=new A.B0(Bo(br(lv))),Sd(n,this),this.displayState.shaderError.value=void 0;const{skeletonRenderingOptions:s}=n;this.registerDisposer(s.shader.changed.add(()=>{this.displayState.shaderError.value=void 0,this.redrawNeeded.dispatch()}));const r=this.sharedObject=this.registerDisposer(new ya(e,n,this.layerChunkProgressInfo));r.RPC_TYPE_ID=vI.k,r.initializeCounterpartWithChunkManager({source:t.addCounterpartRef()});const o=this.vertexAttributes=[xI];for(const[a,l]of t.vertexAttributes)o.push({name:a,dataType:l.dataType,numComponents:l.numComponents,webglDataType:CI(l.dataType),glslDataType:l.numComponents>1?`vec${l.numComponents}`:"float"})}get visibility(){return this.sharedObject.visibility}get gl(){return this.chunkManager.chunkQueueManager.gl}draw(e,t,n,s,r){const o=s.lineWidth.value,{gl:a,source:l,displayState:c}=this;if(c.objectAlpha.value<=0)return;const d=sr(c.transform.value,e.projectionParameters.displayDimensionRenderInfo,r);if(d===void 0)return;let u;s.mode.value===1?u=Math.max(5,o*2):u=o;const h=n.edgeShaderGetter(e.emitter),f=n.nodeShaderGetter(e.emitter),{shader:m,parameters:g}=h,{shader:v,parameters:y}=f;if(m===null||v===null)return;const{shaderControlState:S}=this.displayState.skeletonRenderingOptions;m.bind(),n.beginLayer(a,m,e,d),Oi(a,m,S,g.parseResult.controls),a.uniform1f(m.uniform("uLineWidth"),o),v.bind(),n.beginLayer(a,v,e,d),a.uniform1f(v.uniform("uNodeDiameter"),u),Oi(a,v,S,y.parseResult.controls);const x=l.chunks;wd(c,t,e.emitColor,e.emitPickID?e.pickIDs:void 0,(b,E,C)=>{const k=vn(b),T=x.get(k);T===void 0||T.state!==Be.GPU_MEMORY||(E!==void 0&&(m.bind(),n.setColor(a,m,E),v.bind(),n.setColor(a,v,E)),C!==void 0&&(m.bind(),n.setPickID(a,m,C),v.bind(),n.setPickID(a,v,C)),n.drawSkeleton(a,m,v,T,e.projectionParameters))}),n.endLayer(a,m)}isReady(){const{source:e,displayState:t}=this;if(t.objectAlpha.value<=0)return!0;const n=e.chunks;let s=!0;return Ds(t.segmentationGroupState.value,r=>{const o=vn(r),a=n.get(o);if(a===void 0||a.state!==Be.GPU_MEMORY){s=!1;return}}),s}}class Pd extends $i{constructor(e){super(),this.base=e,this.renderHelper=this.registerDisposer(new cv(this.base,!1)),this.renderOptions=this.base.displayState.skeletonRenderingOptions.params3d,this.layerChunkProgressInfo=e.layerChunkProgressInfo,this.registerDisposer(e),this.registerDisposer(e.redrawNeeded.add(this.redrawNeeded.dispatch));const{renderOptions:t}=this;this.registerDisposer(t.mode.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(t.lineWidth.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(e.visibility.add(this.visibility))}get gl(){return this.base.gl}get isTransparent(){return this.base.displayState.objectAlpha.value<1}draw(e,t){!e.emitColor&&e.alreadyEmittedPickID||this.base.draw(e,this,this.renderHelper,this.renderOptions,t)}isReady(){return this.base.isReady()}}class pv extends Bi{constructor(e){super(),this.base=e,this.renderHelper=this.registerDisposer(new cv(this.base,!0)),this.renderOptions=this.base.displayState.skeletonRenderingOptions.params2d,this.layerChunkProgressInfo=e.layerChunkProgressInfo,this.registerDisposer(e);const{renderOptions:t}=this;this.registerDisposer(t.mode.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(t.lineWidth.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(e.redrawNeeded.add(this.redrawNeeded.dispatch)),this.registerDisposer(e.visibility.add(this.visibility))}get gl(){return this.base.gl}draw(e,t){this.base.draw(e,this,this.renderHelper,this.renderOptions,t)}isReady(){return this.base.isReady()}}function CI(i){switch(i){case I.FLOAT32:return WebGL2RenderingContext.FLOAT;default:throw new Error(`Data type not supported by WebGL: ${I[i]}`)}}const xI={dataType:I.FLOAT32,numComponents:3,name:"",webglDataType:WebGL2RenderingContext.FLOAT,glslDataType:"vec3"};class EI extends Wn{constructor(e,t){super(e),this.vertexAttributes=t.vertexAttributes;const n=this.indices=t.indices;this.numVertices=t.numVertices,this.vertexAttributeOffsets=t.vertexAttributeOffsets,this.numIndices=n.length}copyToGPU(e){super.copyToGPU(e);const{attributeTextureFormats:t}=this.source,{vertexAttributes:n,vertexAttributeOffsets:s}=this,r=this.vertexAttributeTextures=[];for(let o=0,a=s.length;o<a;++o){const l=e.createTexture();e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,l),fa(e,t[o],n.subarray(s[o],o+1!==a?s[o+1]:n.length)),r[o]=l}e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null),this.indexBuffer=At.fromData(e,this.indices,WebGL2RenderingContext.ARRAY_BUFFER,WebGL2RenderingContext.STATIC_DRAW)}freeGPUMemory(e){super.freeGPUMemory(e);const{vertexAttributeTextures:t}=this;for(const n of t)e.deleteTexture(n);t.length=0,this.indexBuffer.dispose()}}const TI=new Map;function DI(i){const e=[SI];for(const t of i.values())e.push(zi(new As,t.dataType,t.numComponents));return e}class Br extends tn{get attributeTextureFormats(){let e=this.attributeTextureFormats_;return e===void 0&&(e=this.attributeTextureFormats_=DI(this.vertexAttributes)),e}getChunk(e){return new EI(this,e)}get vertexAttributes(){return TI}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var gt=(i=>(i[i.UNKNOWN=0]="UNKNOWN",i[i.IMAGE=1]="IMAGE",i[i.SEGMENTATION=2]="SEGMENTATION",i))(gt||{});const O_=18;function Ad(i){const{rank:e,dataType:t,fillValue:n=t===I.UINT64?M.R.ZERO:0,compressedSegmentationBlockSize:s}=i,{baseVoxelOffset:r=new Float32Array(e)}=i;return{...zo(i),compressedSegmentationBlockSize:s,baseVoxelOffset:r,dataType:t,fillValue:n}}function II(i){if(i.compressedSegmentationBlockSize!==void 0||i.volumeType!==2&&!i.volumeSourceOptions.discreteValues)return!1;switch(i.dataType){case I.UINT32:case I.UINT64:break;default:return!1}switch(i.rank){case 3:return!0;case 4:{const{chunkDataSize:e}=i;return e[3]===1}default:return!1}}function fv(i){const{rank:e,lowerVoxelBound:t,upperVoxelBound:n}=i;if(!II(i))return Ad(i);let{volumeSourceOptions:{displayRank:s,multiscaleToViewTransform:r},chunkToMultiscaleTransform:o,chunkToViewTransform:a}=i;a===void 0&&(a=we.lw(new Float32Array(e*s),s,r,s,o,e+1,s,e,e));const{maxCompressedSegmentationBlockSize:l,chunkDataSize:c}=i;return Ad({...i,compressedSegmentationBlockSize:Float32Array.from(Go({rank:e,chunkToViewTransform:a,displayRank:s,lowerVoxelBound:t,upperVoxelBound:n,maxVoxelsPerChunkLog2:9,maxBlockSize:l===void 0?c:Xb(new Uint32Array(e),c,l)}))})}function gi(i){const{rank:e}=i,{volumeSourceOptions:{displayRank:t,multiscaleToViewTransform:n,modelChannelDimensionIndices:s},chunkToMultiscaleTransform:r}=i,o=we.lw(new Float32Array(t*e),t,n,t,r,e+1,t,e,e);let{minBlockSize:a}=i;a===void 0?(a=new Uint32Array(e),a.fill(1)):a=new Uint32Array(a);const{lowerVoxelBound:l,upperVoxelBound:c}=i;if(s.length!==0)for(const u of(0,w.PC)(r,e,s)){let h=c[u];l!==void 0&&(h-=l[u]),a[u]=h}const{chunkDataSizes:d=vE({...i,minBlockSize:a,chunkToViewTransform:o,displayRank:t})}=i;return d.map(u=>fv({...i,chunkDataSize:u,chunkToViewTransform:o}))}const V_="volume";/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function gv(i,e,t,n){const{dataType:s}=e;e.defineShader(i,t);let r="",o="";if(t===0)r+="highp int ignoredChannelIndex";else for(let l=0;l<t;++l)l!==0&&(r+=", "),r+=`highp int channelIndex${l}`,o+=`, channelIndex${l}`;i.addFragmentCode(uC);const a=`
${vt(s)} getDataValue(${r}) {
  highp ivec3 p = ivec3(max(vec3(0.0, 0.0, 0.0), min(floor(${n}), uChunkDataSize - 1.0)));
  return getDataValueAt(p${o});
}
${vt(s)} getInterpolatedDataValue(${r}) {
  highp vec3 positionWithinChunk = ${n};
  highp ivec3[2] points;
  points[0] = ivec3(max(vec3(0.0, 0.0, 0.0), min(floor(positionWithinChunk - 0.5), uChunkDataSize - 1.0)));
  points[1] = ivec3(max(vec3(0.0, 0.0, 0.0), min(ceil(positionWithinChunk - 0.5), uChunkDataSize - 1.0)));
  highp vec3 mixCoeff = fract(positionWithinChunk - 0.5);
  ${vt(s)} xvalues[2];
  for (int ix = 0; ix < 2; ++ix) {
    ${vt(s)} yvalues[2];
    for (int iy = 0; iy < 2; ++iy) {
      ${vt(s)} zvalues[2];
      for (int iz = 0; iz < 2; ++iz) {
        zvalues[iz] = getDataValueAt(ivec3(points[ix].x, points[iy].y, points[iz].z)
                                     ${o});
      }
      yvalues[iy] = mixLinear(zvalues[0], zvalues[1], mixCoeff.z);
    }
    xvalues[ix] = mixLinear(yvalues[0], yvalues[1], mixCoeff.y);
  }
  return mixLinear(xvalues[0], xvalues[1], mixCoeff.x);
}
`;i.addFragmentCode(a),t<=1&&i.addFragmentCode(`
${vt(s)} getDataValue() { return getDataValue(0); }
${vt(s)} getInterpolatedDataValue() { return getInterpolatedDataValue(0); }
`)}const mv=new Array;function vv(i){mv.push(i)}function RI(i,e){for(const t of mv){const n=t(i,e);if(n!=null)return n}throw new Error("No chunk format handler found.")}class Mn extends Er{constructor(e,t){super(e,t),this.chunkFormatHandler=this.registerDisposer(RI(e.chunkQueueManager.gl,this.spec));const n=this.spec.upperVoxelBound.length;this.tempChunkGridPosition=new Float32Array(n),this.tempPositionWithinChunk=new Uint32Array(n)}static encodeSpec(e){const t=e;return{...super.encodeSpec(e),dataType:t.dataType,compressedSegmentationBlockSize:t.compressedSegmentationBlockSize&&Array.from(t.compressedSegmentationBlockSize),baseVoxelOffset:Array.from(t.baseVoxelOffset)}}get chunkFormat(){return this.chunkFormatHandler.chunkFormat}getValueAt(e,t){const n=this.spec.rank,s=this.tempChunkGridPosition,r=this.tempPositionWithinChunk,{spec:o}=this;{const{chunkDataSize:g}=o;for(let v=0;v<n;++v){const y=e[v],S=g[v],x=Math.floor(y/S);s[v]=x,r[v]=Math.floor(y-S*x)}}const a=this.chunks.get(s.join());if(a===void 0)return null;const l=a.chunkDataSize;for(let g=0;g<3;++g)if(r[g]>=l[g])return;if(t.channelSpaceShape.length===0)return a.getValueAt(r);const{numChannels:c,chunkChannelCoordinates:d,chunkChannelDimensionIndices:u}=t,h=u.length;let f=0;const m=new Array(c);for(let g=0;g<c;++g){for(let v=0;v<h;++v)r[u[v]]=d[f++];m[g]=a.getValueAt(r)}return m}getChunk(e){return this.chunkFormatHandler.getChunk(this,e)}}class kI extends ig{get chunkFormat(){return this.source.chunkFormat}constructor(e,t){super(e,t),this.chunkDataSize=t.chunkDataSize||e.spec.chunkDataSize}}class Ht extends XE{}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const LI=w.eR.create(),PI=w.eR.create(),Da=.001,yv=.001;function Sv(i){let e=0;for(let t=0;t<3;++t)i[t]<0&&(e+=1<<t);return e}const Md=new Float32Array([0,0,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,1,1]),bv=(()=>{const i=[0,1,2,4,5,3,6,7],e=[0,1,2,5,3,4,6,7],t=[0,1,1,4,4,7,4,7,1,5,0,1,1,4,4,7,0,2,2,5,5,7,5,7,2,6,0,2,2,5,5,7,0,3,3,6,6,7,6,7,3,4,0,3,3,6,6,7],n=[0,1,2,3,4,5,6,7,1,4,5,0,3,7,2,6,2,6,0,5,7,3,1,4,3,0,6,4,1,2,7,5,4,3,7,1,0,6,5,2,5,2,1,7,6,0,4,3,6,7,3,2,5,4,0,1,7,5,4,6,2,1,3,0],s=new Int32Array(8*8*6);for(let r=0;r<8;++r)for(let o=0;o<t.length;++o){const a=e[r]*8+t[o];s[r*8*6+o]=i[n[a]]}return s})();function Ia(i){i.addUniform("highp vec3","uPlaneNormal"),i.addUniform("highp float","uPlaneDistance"),i.addUniform("highp ivec2","uVertexIndex",24),i.addUniform("highp vec3","uVertexBasePosition",8),i.addInitializer(e=>{e.gl.uniform3fv(e.uniform("uVertexBasePosition"),Md)}),i.addVertexCode(`
vec3 getBoundingBoxPlaneIntersectionVertexPosition(vec3 chunkSize, vec3 boxLower, vec3 lowerClipBound, vec3 upperClipBound, int vertexIndex, float planeDistance) {
  for (int e = 0; e < 4; ++e) {
    highp ivec2 vidx = uVertexIndex[vertexIndex*4 + e];
    highp vec3 v1 = max(lowerClipBound, min(upperClipBound, chunkSize * uVertexBasePosition[vidx.x] + boxLower));
    highp vec3 v2 = max(lowerClipBound, min(upperClipBound, chunkSize * uVertexBasePosition[vidx.y] + boxLower));
    highp vec3 vDir = v2 - v1;
    highp float denom = dot(vDir, uPlaneNormal);
    if (abs(denom) > ${yv}) {
      highp float lambda = (planeDistance - dot(v1, uPlaneNormal)) / denom;
      if ((lambda >= -${Da}) && (lambda <= (1.0 + ${Da}))) {
        lambda = clamp(lambda, 0.0, 1.0);
        highp vec3 position = v1 + lambda * vDir;
        return position;
      }
    }
  }
  return vec3(0, 0, 0);
}
vec3 getBoundingBoxPlaneIntersectionVertexPosition(vec3 chunkSize, vec3 boxLower, vec3 lowerClipBound, vec3 upperClipBound, int vertexIndex) {
  return getBoundingBoxPlaneIntersectionVertexPosition(chunkSize, boxLower, lowerClipBound, upperClipBound, vertexIndex, uPlaneDistance);
}
`)}function wv(i,e,t,n,s,r,o,a=!0){const l=Sv(s),c=bv.subarray(l*48,(l+1)*48),d=[0,0],u=[w.eR.create(),w.eR.create()],h=w.eR.create(),f=w.eR.create(),m=g=>Md.subarray(g*3,g*3+3);for(let g=0;g<4;++g){for(let y=0;y<2;++y)d[y]=c[2*(o*4+g)+y],w.eR.multiply(u[y],i,m(d[y])),w.eR.add(u[y],u[y],r),w.eR.min(u[y],u[y],t),w.eR.max(u[y],u[y],e);w.eR.subtract(h,u[1],u[0]);const v=w.eR.dot(h,s);if(Math.abs(v)>yv){let y=(n-w.eR.dot(u[0],s))/v;if(y>=-Da&&y<=1+Da)return a&&console.log(`vertex ${o}, e = ${g}, good, lambda=${y}, denom=${v}, v0=${u[0].join()}, vDir=${h.join()}`),y=Math.max(0,Math.min(1,y)),w.eR.scaleAndAdd(f,u[0],h,y),f;a&&console.log(`vertex ${o}, e = ${g}, skipped, denom = ${v}, vDir = ${h.join()}, v0=${u[0].join()}, v1=${u[1].join()}uPlaneNormal = ${(0,w.nL)(s)}, lambda=${y}`)}else a&&console.log(`vertex ${o}, e = ${g}, skipped, deom = ${v}, vDir = ${(0,w.nL)(h)}, uPlaneNormal = ${(0,w.nL)(s)}, uLowerClipBound=${e.join()}, uUpperClipBound=${t.join()}, chunkSize=${i}, uVertexBasePosition(v0)=${m(d[0]).join()}, uVertexBasePosition(v1)=${m(d[1]).join()}, uTranslation=${r.join()}`)}}function __(i,e,t,n,s,r){const o=[];for(let a=0;a<6;++a){const l=wv(i,e,t,n,s,r,a,!1);l!==void 0&&o.push(l)}return o}function AI(i,e,t){const{gl:n}=i;n.uniform3fv(i.uniform("uPlaneNormal"),e),n.uniform1f(i.uniform("uPlaneDistance"),t);const s=Sv(e);n.uniform2iv(i.uniform("uVertexIndex"),bv.subarray(s*48,(s+1)*48))}function Nd(i,e,t,n,s){const r=(0,w.uD)(LI,e,n);w.eR.normalize(r,r);const o=w.eR.dot(w.eR.transformMat4(PI,t,s),r);AI(i,r,o)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Od=!1,Cv=.001,xv=w.pB.create();function MI(i,e){if(fi(i),Ia(i),i.addUniform("highp vec3","uTranslation"),i.addUniform("highp mat4","uProjectionMatrix"),i.addUniform("highp vec3","uChunkDataSize"),i.addUniform("highp vec3","uLowerClipBound"),i.addUniform("highp vec3","uUpperClipBound"),e){Tn(i),i.setVertexMain(`
int vertexIndex1 = gl_VertexID / ${gn};
int vertexIndex2 = vertexIndex1 == 5 ? 0 : vertexIndex1 + 1;
vec3 vertexPosition1 = getBoundingBoxPlaneIntersectionVertexPosition(uChunkDataSize, uTranslation, uLowerClipBound, uUpperClipBound, vertexIndex1);
vec3 vertexPosition2 = getBoundingBoxPlaneIntersectionVertexPosition(uChunkDataSize, uTranslation, uLowerClipBound, uUpperClipBound, vertexIndex2);
emitLine(uProjectionMatrix * vec4(vertexPosition1, 1.0),
         uProjectionMatrix * vec4(vertexPosition2, 1.0),
         2.0);
`),i.setFragmentMain(`
emit(vec4(1.0, 1.0, 1.0, getLineAlpha()));
`);return}i.addVarying("highp vec3","vChunkPosition"),i.setVertexMain(`
vec3 position = getBoundingBoxPlaneIntersectionVertexPosition(uChunkDataSize, uTranslation, uLowerClipBound, uUpperClipBound, gl_VertexID);
gl_Position = uProjectionMatrix * vec4(position, 1.0);
gl_Position.z = 0.0;
vChunkPosition = (position - uTranslation) +
    ${Cv} * abs(uPlaneNormal);
`)}function NI(i,e,t,n,s,r,o){const a=w.eR.create(),l=w.eR.create(),c=w.eR.fromValues(Math.abs(s[0]),Math.abs(s[1]),Math.abs(s[2])),d=w.eR.create();for(let u=0;u<6;++u){const h=wv(i,e,t,n,s,r,u);if(h===void 0){console.log("no intersection found");return}w.eR.transformMat4(a,h,o);const f=u!==0&&w.eR.equals(a,d);w.eR.copy(d,a),w.eR.sub(l,h,r),w.eR.scaleAndAdd(l,l,c,Cv),console.log(`${f?"SKIPPED":"OUTPUT"} vertex ${u}, at ${a}, vChunkPosition = ${l}, uTranslation=${r.join()}, position=${h.join()}`)}}function OI(i,e,t){t&&In(i,e,1)}function VI(i,e,t,n,s,r){const o=t.projectionParameters.value,{centerDataPosition:a}=o;Nd(e,o.viewportNormalInGlobalCoordinates,a,r.transform,r.invTransform),i.uniformMatrix4fv(e.uniform("uProjectionMatrix"),!1,w.pB.multiply(xv,n,r.transform)),i.uniform3fv(e.uniform("uLowerClipBound"),s.lowerClipDisplayBound),i.uniform3fv(e.uniform("uUpperClipBound"),s.upperClipDisplayBound),Od&&(window.debug_sliceView_uLowerClipBound=s.lowerClipDisplayBound,window.debug_sliceView_uUpperClipBound=s.upperClipDisplayBound,window.debug_sliceView=t,window.debug_sliceView_dataToDevice=w.pB.clone(xv),window.debug_sliceView_chunkLayout=r)}function _I(i,e,t){i.uniform3fv(e.uniform("uChunkDataSize"),t),Od&&(window.debug_sliceView_chunkDataSize=t)}function BI(i,e,t,n){if(i.uniform3fv(e.uniform("uTranslation"),t),n?Dn(e.gl,6,1):i.drawArrays(i.TRIANGLE_FAN,0,6),Od){const r=window.debug_sliceView.projectionParameters.value,o=window.debug_sliceView_chunkDataSize,a=window.debug_sliceView_uLowerClipBound,l=window.debug_sliceView_uUpperClipBound,c=window.debug_sliceView_dataToDevice,d=window.debug_sliceView_chunkLayout;console.log(`Drawing chunk: ${t.join()} of data size ${o.join()}, projection`,c);const u=d.globalToLocalNormal(w.eR.create(),r.viewportNormalInGlobalCoordinates),h=w.eR.dot(w.eR.transformMat4(w.eR.create(),r.centerDataPosition,d.invTransform),u);NI(o,a,l,h,u,t,c)}}function FI(i,e,t){return i>e?t>i?i:e>t?e:t:t>e?e:i>t?i:t}class Vd extends kc{constructor(e,t){const{shaderError:n=ar(),shaderParameters:s}=t;super(e.chunkManager,e,t);const{gl:r}=this;this.vertexIdHelper=this.registerDisposer(jn.get(r)),this.shaderParameters=s;const{channelCoordinateSpace:o}=t;this.channelCoordinateSpace=o===void 0?(0,A.XZ)(Bn):o,this.registerDisposer(s.changed.add(this.redrawNeeded.dispatch));const a=this.registerDisposer((0,A.Uq)((l,c)=>({numChannelDimensions:l.rank,dataHistogramChannelSpecifications:c}),[this.channelCoordinateSpace,this.dataHistogramSpecifications.channels]));this.shaderGetter=vo(this,r,{memoizeKey:`volume/RenderLayer:${St(this.constructor)}`,fallbackParameters:t.fallbackShaderParameters,parameters:s,encodeParameters:t.encodeShaderParameters,shaderError:n,extraParameters:a,defineShader:(l,c,d,u)=>{const{chunkFormat:h,dataHistogramsEnabled:f}=c,{dataHistogramChannelSpecifications:m,numChannelDimensions:g}=u;if(MI(l,h===null),l.addOutputBuffer("vec4","v4f_fragData0",0),l.addFragmentCode(`
void emit(vec4 color) {
  v4f_fragData0 = color;
}
`),h===null)return;gv(l,h,g,"vChunkPosition");const v=m.length;if(f&&v>0){let y="";const{dataType:S}=h;for(let x=0;x<v;++x){const{channel:b}=m[x],E=`out_histogram${x}`;l.addOutputBuffer("vec4",E,1+x);const C=`getDataValue(${b.join(",")})`,k=`invlerpForHistogram${x}`;l.addFragmentCode(us(l,k,S,!1)),l.addFragmentCode(`
float getHistogramValue${x}() {
  return invlerpForHistogram${x}(${C});
}
`),y+=`{
float x = getHistogramValue${x}();
if (x < 0.0) x = 0.0;
else if (x > 1.0) x = 1.0;
else x = (1.0 + x * 253.0) / 255.0;
${E} = vec4(x, x, x, 1.0);
}`}l.addFragmentCode(`void userMain();
void main() {
  ${y}
  userMain();
}
#define main userMain
`)}this.defineShader(l,d)},getContextKey:l=>`${l.chunkFormat?.shaderKey}/${l.dataHistogramsEnabled}`}),this.tempChunkPosition=new Float32Array(e.rank),this.initializeCounterpart()}get dataType(){return this.multiscaleSource.dataType}getValueAt(e){const{tempChunkPosition:t}=this;for(const{source:n,chunkTransform:s}of this.visibleSourcesList){if(!as(t,e,this.localPosition.value,s.layerRank,s.combinedGlobalLocalToChunkTransform))continue;const r=n.getValueAt(t,s);if(r!=null)return r}return null}beginChunkFormat(e,t,n){const{gl:s}=this,r=this.dataHistogramSpecifications.visibility.visible,o=this.shaderGetter({chunkFormat:t,dataHistogramsEnabled:r}),{shader:a,parameters:l,fallback:c}=o;if(a!==null&&(a.bind(),OI(a,n,t===null),t!==null)){if(r){const{dataHistogramChannelSpecifications:d}=o.extraParameters,u=d.length,h=this.dataHistogramSpecifications.bounds.value;for(let f=0;f<u;++f)Pi(a,`invlerpForHistogram${f}`,t.dataType,h[f])}this.initializeShader(e,a,l,c),t.beginDrawing(s,a)}return o}endSlice(e,t,n){}draw(e){const{sliceView:t}=e,n=t.visibleLayers.get(this),{visibleSources:s}=n;if(s.length===0)return;const{projectionParameters:r,wireFrame:o}=e,{gl:a}=this;this.vertexIdHelper.enable();const l=w.eR.create(),{renderScaleHistogram:c}=this;c!==void 0&&c.begin(this.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber);let d,u=null,h;const f=w.eR.create(),m=()=>{u!==null&&(u.unbindTransferFunctionTextures(),h!==null&&h.endDrawing(a,u),this.endSlice(t,u,d.parameters))};let g=!0;for(const v of s){const y=Cc(r,v.chunkLayout),{chunkTransform:{channelToChunkDimensionIndices:S}}=v,x=v.source,{fixedPositionWithinChunk:b,chunkDisplayDimensionIndices:E}=v;for(const V of E)b[V]=0;const C=o?null:x.chunkFormat;if(C!==h&&(h=C,m(),d=this.beginChunkFormat(t,C,r),u=d.shader),u===null)continue;const k=x.chunks;f.fill(1);const T=y.size;let L;const _=x.spec.rank;VI(a,u,t,r.viewProjectionMat,v,y),C!==null&&C.beginSource(a,u),g=!0;let R=0,P=0;if(t.forEachVisibleChunk(v,y,V=>{const $=k.get(V);if($&&$.state===Be.GPU_MEMORY){const Q=$.chunkDataSize;if(Q!==L){L=Q;for(let ee=0;ee<3;++ee){const ce=E[ee];f[ee]=ce===-1||ce>=_?1:L[ce]}_I(a,u,f)}const{chunkGridPosition:K}=$;for(let ee=0;ee<3;++ee){const ce=E[ee];l[ee]=ce===-1||ce>=_?0:T[ee]*K[ce]}C!==null&&C.bindChunk(a,u,$,b,E,S,g),g=!1,BI(a,u,l,o),++R}else++P}),(R!==0||P!==0)&&c!==void 0){const{effectiveVoxelSize:V}=v,$=FI(V[0],V[1],V[2]);c.add($,$/r.pixelSize,R,P)}}if(m(),this.vertexIdHelper.disable(),!e.wireFrame){const v=this.getDataHistogramCount();v>0&&t.computeHistograms(v,this.dataHistogramSpecifications)}}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Ev{constructor(e){this.disjointSets=e,this.generation=Number.NaN,this.hashMap=new ld}update(){const{disjointSets:e}=this,{generation:t}=e;if(this.generation!==t){this.generation=t;const{hashMap:n}=this;n.clear();for(const[s,r]of e.mappings())n.set(s,r)}}}const Tv=1,Dv=2;class Iv extends Vd{constructor(e,t){super(e,{shaderParameters:new A.wP(n=>({hasEquivalences:n.registerDisposer((0,A.Uq)(s=>s.size!==0,[t.segmentationGroupState.value.segmentEquivalences])),hasSegmentStatedColors:n.registerDisposer((0,A.Uq)((s,r,o)=>(o?r:s).size!==0,[t.segmentStatedColors,t.tempSegmentStatedColors2d,t.useTempSegmentStatedColors2d])),hasSegmentDefaultColor:n.registerDisposer((0,A.Uq)((s,r)=>s!==void 0||r!==void 0,[t.segmentDefaultColor,t.tempSegmentDefaultColor2d])),hasHighlightColor:n.registerDisposer((0,A.Uq)(s=>s!==void 0,[t.highlightColor])),hideSegmentZero:t.hideSegmentZero,baseSegmentColoring:t.baseSegmentColoring,baseSegmentHighlighting:t.baseSegmentHighlighting})),transform:t.transform,renderScaleHistogram:t.renderScaleHistogram,renderScaleTarget:t.renderScaleTarget,localPosition:t.localPosition}),this.displayState=t,this.segmentationGroupState=this.displayState.segmentationGroupState.value,this.segmentColorShaderManager=new lD("segmentColorHash"),this.segmentStatedColorShaderManager=new cD("segmentStatedColor"),this.hashTableManager=new gm("visibleSegments"),this.gpuHashTable=this.registerDisposer(Wi.get(this.gl,this.segmentationGroupState.visibleSegments.hashTable)),this.gpuTemporaryHashTable=Wi.get(this.gl,this.segmentationGroupState.temporaryVisibleSegments.hashTable),this.equivalencesShaderManager=new mm("equivalences"),this.equivalencesHashMap=new Ev(this.segmentationGroupState.segmentEquivalences.disjointSets),this.temporaryEquivalencesHashMap=new Ev(this.segmentationGroupState.temporarySegmentEquivalences.disjointSets),this.gpuEquivalencesHashTable=this.registerDisposer(Wi.get(this.gl,this.equivalencesHashMap.hashMap)),this.gpuTemporaryEquivalencesHashTable=this.registerDisposer(Wi.get(this.gl,this.temporaryEquivalencesHashMap.hashMap)),this.registerDisposer(this.shaderParameters),Vm(t,this),this.registerDisposer(t.selectedAlpha.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(t.notSelectedAlpha.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(t.ignoreNullVisibleSet.changed.add(this.redrawNeeded.dispatch))}disposed(){this.gpuSegmentStatedColorHashTable?.dispose()}getSources(e){return this.multiscaleSource.getSources({...e,discreteValues:!0})}defineShader(e,t){this.hashTableManager.defineShader(e);let n=`
uint64_t getUint64DataValue() {
  uint64_t x = toUint64(getDataValue());
`;n+=`return x;
}
`,e.addFragmentCode(n),t.hasEquivalences?(this.equivalencesShaderManager.defineShader(e),e.addFragmentCode(`
uint64_t getMappedObjectId(uint64_t value) {
  uint64_t mappedValue;
  if (${this.equivalencesShaderManager.getFunctionName}(value, mappedValue)) {
    return mappedValue;
  }
  return value;
}
`)):e.addFragmentCode(`
uint64_t getMappedObjectId(uint64_t value) {
  return value;
}
`),e.addUniform("highp uvec2","uSelectedSegment"),e.addUniform("highp uint","uFlags"),e.addUniform("highp float","uSelectedAlpha"),e.addUniform("highp float","uNotSelectedAlpha"),e.addUniform("highp float","uSaturation");let s=`
  uint64_t baseValue = getUint64DataValue();
  uint64_t value = getMappedObjectId(baseValue);
  uint64_t valueForColor = ${t.baseSegmentColoring?"baseValue":"value"};
  uint64_t valueForHighlight = ${t.baseSegmentHighlighting?"baseValue":"value"};

  float alpha = uSelectedAlpha;
  float saturation = uSaturation;
`;t.hideSegmentZero&&(s+=`
  if (value.value[0] == 0u && value.value[1] == 0u) {
    emit(vec4(vec4(0, 0, 0, 0)));
    return;
  }
`),s+=`
  bool has = (uFlags & ${Dv}u) != 0u ? true : ${this.hashTableManager.hasFunctionName}(value);
  if ((uFlags & ${Tv}u) != 0u && uSelectedSegment == valueForHighlight.value) {
    float adjustment = has ? 0.5 : 0.75;
    if (saturation > adjustment) {
      saturation -= adjustment;
    } else {
      saturation += adjustment;
    }
`,t.hasHighlightColor&&(e.addUniform("highp vec4","uHighlightColor"),s+=`
    emit(uHighlightColor);
    return;
`),s+=`
  } else if (!has) {
    alpha = uNotSelectedAlpha;
  }
`;let r=`vec4 getMappedIdColor(uint64_t value) {
`;t.hasSegmentStatedColors&&(this.segmentStatedColorShaderManager.defineShader(e),r+=`
  vec4 rgba;
  if (${this.segmentStatedColorShaderManager.getFunctionName}(value, rgba)) {
    return rgba;
  }
`),t.hasSegmentDefaultColor?(e.addUniform("highp vec4","uSegmentDefaultColor"),r+=`  return uSegmentDefaultColor;
`):(this.segmentColorShaderManager.defineShader(e),r+=`  return vec4(segmentColorHash(value), 0.0);
`),r+=`
}
`,e.addFragmentCode(r),s+=`
  vec4 rgba = getMappedIdColor(valueForColor);
  if (rgba.a > 0.0) {
    alpha = rgba.a;
  }
  emit(vec4(mix(vec3(1.0,1.0,1.0), vec3(rgba), saturation), alpha));
`,e.setFragmentMain(s)}initializeShader(e,t,n){const{gl:s}=this,{displayState:r,segmentationGroupState:o}=this,{segmentSelectionState:a}=this.displayState,{segmentDefaultColor:{value:l},segmentColorHash:{value:c},highlightColor:{value:d},tempSegmentDefaultColor2d:{value:u}}=this.displayState,h=ng(o),f=this.displayState.ignoreNullVisibleSet.value;let m=0,g=0,v=0;if(a.hasSelectedSegment&&r.hoverHighlight.value){const S=r.baseSegmentHighlighting.value?a.baseSelectedSegment:a.selectedSegment;m=S.low,g=S.high,v|=Tv}if(s.uniform1f(t.uniform("uSelectedAlpha"),r.selectedAlpha.value),s.uniform1f(t.uniform("uSaturation"),r.saturation.value),s.uniform1f(t.uniform("uNotSelectedAlpha"),r.notSelectedAlpha.value),s.uniform2ui(t.uniform("uSelectedSegment"),m,g),h.hashTable.size===0&&f&&(v|=Dv),s.uniform1ui(t.uniform("uFlags"),v),this.hashTableManager.enable(s,t,o.useTemporaryVisibleSegments.value?this.gpuTemporaryHashTable:this.gpuHashTable),n.hasEquivalences){const S=o.useTemporarySegmentEquivalences.value;(S?this.temporaryEquivalencesHashMap:this.equivalencesHashMap).update(),this.equivalencesShaderManager.enable(s,t,S?this.gpuTemporaryEquivalencesHashTable:this.gpuEquivalencesHashTable)}const y=u||l;if(y){const[S,x,b,E]=y;s.uniform4f(t.uniform("uSegmentDefaultColor"),S,x,b,E===void 0?0:E)}else this.segmentColorShaderManager.enable(s,t,c);if(n.hasSegmentStatedColors){const S=r.useTempSegmentStatedColors2d.value?r.tempSegmentStatedColors2d.value:r.segmentStatedColors.value;let{gpuSegmentStatedColorHashTable:x}=this;(x===void 0||x.hashTable!==S.hashTable)&&(x?.dispose(),this.gpuSegmentStatedColorHashTable=x=Wi.get(s,S.hashTable)),this.segmentStatedColorShaderManager.enable(s,t,x)}d!==void 0&&s.uniform4fv(t.uniform("uHighlightColor"),d)}endSlice(e,t,n){const{gl:s}=this;this.hashTableManager.disable(s,t),n.hasEquivalences&&this.equivalencesShaderManager.disable(s,t),n.hasSegmentStatedColors&&this.segmentStatedColorShaderManager.disable(s,t),super.endSlice(e,t,n)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Fr(i=.5){return new A.DN(i,p.xU)}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const _d=12,Rv=8,UI=6,$I=`
vec3 getBoxFaceVertexPosition(int vertexIndex) {
  const vec3 vertexPositions[] = vec3[](
  // Front face
  vec3(0.0, 0.0,  1.0), // 0
  vec3(1.0, 0.0,  1.0), // 1
  vec3(1.0,  1.0,  1.0), // 2
  vec3(0.0,  1.0,  1.0), // 3

  // Back face
  vec3(0.0, 0.0, 0.0), // 4
  vec3(0.0,  1.0, 0.0), // 5
  vec3(1.0,  1.0, 0.0), // 6
  vec3(1.0, 0.0, 0.0), // 7

  // Top face
  vec3(0.0,  1.0, 0.0), // 8
  vec3(0.0,  1.0,  1.0), // 9
  vec3(1.0,  1.0,  1.0), // 10
  vec3(1.0,  1.0, 0.0), // 11

  // Bottom face
  vec3(0.0, 0.0, 0.0), // 12
  vec3( 1.0, 0.0, 0.0), // 13
  vec3( 1.0, 0.0,  1.0), // 14
  vec3(0.0, 0.0,  1.0), // 15

  // Right face
  vec3( 1.0, 0.0, 0.0), // 16
  vec3( 1.0,  1.0, 0.0), // 17
  vec3( 1.0,  1.0,  1.0), // 18
  vec3( 1.0, 0.0,  1.0), // 19

  // Left face
  vec3(0.0, 0.0, 0.0), // 20
  vec3(0.0, 0.0,  1.0), // 21
  vec3(0.0,  1.0,  1.0), // 22
  vec3(0.0,  1.0, 0.0) // 23
  );
  const int indices[] = int[](
    0,  1,  2,      0,  2,  3,    // front
    4,  5,  6,      4,  6,  7,    // back
    8,  9,  10,     8,  10, 11,   // top
    12, 13, 14,     12, 14, 15,   // bottom
    16, 17, 18,     16, 18, 19,   // right
    20, 21, 22,     20, 22, 23   // left
  );
  return vertexPositions[indices[vertexIndex]];
}
`;function GI(i,e,t){i.drawArraysInstanced(WebGL2RenderingContext.TRIANGLES,0,6*UI*e,t)}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const kv=0,Ra=kv+1,It=Ra+Rv,Bd=It+_d,zI=Bd+6,WI=Float32Array.from([0,0,0,0,0,1,It+0,1,0,0,1,0,1,It+1,0,1,0,0,1,1,It+2,1,1,0,1,1,1,It+3,0,0,0,0,1,0,It+4,0,0,1,0,1,1,It+5,1,0,0,1,1,0,It+6,1,0,1,1,1,1,It+7,0,0,0,1,0,0,It+8,0,0,1,1,0,1,It+9,0,1,0,1,1,0,It+10,0,1,1,1,1,1,It+11]),Lv=w.pB.create(),mi=new Float32Array(6);class Pv extends Wo{constructor(){super(...arguments),this.vertexIdHelper=this.registerDisposer(jn.get(this.gl))}defineShader(e){fi(e);const{rank:t}=this;wo(e,"float",WebGL2RenderingContext.FLOAT,!1,"Bounds",t,2),e.addUniform("vec3","uModelSpaceBoundOffsets",2)}enable(e,t,n){w.pB.invert(Lv,t.modelViewProjectionMatrix),(0,w.bS)(Lv,mi);const{numChunkDisplayDims:s}=t.chunkDisplayTransform;for(let r=0;r<s;++r)mi[r]=0,mi[r+3]=0;for(let r=s;r<3;++r){const o=Math.abs(mi[r+3]-mi[r]);mi[r]-=o,mi[r+3]+=o}super.enable(e,t,r=>{const o=r.vertexShaderInputBinders.Bounds;o.enable(1);const{gl:a}=this;a.uniform3fv(r.uniform("uModelSpaceBoundOffsets"),mi),a.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,t.buffer.buffer),o.bind(this.geometryDataStride,t.bufferOffset);const{vertexIdHelper:l}=this;l.enable(),n(r),l.disable(),o.disable()})}}function Av(i){i.addVertexCode(`
void setBoundingBoxBorderWidth(float width) {}
void setBoundingBoxBorderColor(vec4 color) {}
`)}function Mv(i){i.addVertexCode(`
void setBoundingBoxFillColor(vec4 color) {}
`)}function Fd(i){Mv(i),i.addVertexCode(`
float ng_lineWidth;
void setBoundingBoxBorderWidth(float size) {
  ng_lineWidth = size;
}
void setBoundingBoxBorderColor(vec4 color) {
  vColor = color;
}
`)}function HI(i){Av(i),i.addVertexCode(`
void setBoundingBoxFillColor(vec4 color) {
  vColor = color;
}
`)}class JI extends Pv{constructor(){super(...arguments),this.edgeBoxCornerOffsetsBuffer=this.registerDisposer(At.fromData(this.gl,(0,z.CS)(WI,7,1,gn))),this.edgeShaderGetter=this.getDependentShader("annotation/boundingBox/projection/border",e=>{const{rank:t}=this;this.defineShader(e),Tn(e),e.addAttribute("highp vec3","aBoxCornerOffset1"),e.addAttribute("highp vec4","aBoxCornerOffset2"),e.addVarying("highp float","vClipCoefficient"),Fd(e),e.setVertexMain(`
float modelPositionA[${t}] = getBounds0();
float modelPositionB[${t}] = getBounds1();
vec3 subspacePositionA = projectModelVectorToSubspace(modelPositionA) + uModelSpaceBoundOffsets[0];
vec3 subspacePositionB = projectModelVectorToSubspace(modelPositionB) + uModelSpaceBoundOffsets[1];
vec3 endpointA = mix(subspacePositionA, subspacePositionB, aBoxCornerOffset1);
vec3 endpointB = mix(subspacePositionA, subspacePositionB, aBoxCornerOffset2.xyz);
vClipCoefficient = getMaxSubspaceClipCoefficient(modelPositionA, modelPositionB);
if (vClipCoefficient == 0.0) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
ng_lineWidth = 1.0;
${this.invokeUserMain}
emitLine(uModelViewProjection * vec4(endpointA, 1.0),
         uModelViewProjection * vec4(endpointB, 1.0),
         ng_lineWidth);
${this.setPartIndex(e,"uint(aBoxCornerOffset2.w)")};
`),e.setFragmentMain(`
emitAnnotation(vec4(vColor.rgb, getLineAlpha() * vClipCoefficient));
`)}),this.boxCornerOffsetsBuffer=this.registerDisposer(At.fromData(this.gl,(0,z.CS)(Md,3,1,av))),this.cornerShaderGetter=this.getDependentShader("annotation/boundingBox/projection/corner",e=>{const{rank:t}=this;this.defineShader(e),xa(e,this.targetIsSliceView),e.addAttribute("highp vec3","aBoxCornerOffset"),e.addVarying("highp float","vClipCoefficient"),Fd(e),e.setVertexMain(`
float modelPositionA[${t}] = getBounds0();
float modelPositionB[${t}] = getBounds1();
vClipCoefficient = getMaxEndpointSubspaceClipCoefficient(modelPositionA, modelPositionB);
if (vClipCoefficient == 0.0) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
vec3 subspacePositionA = projectModelVectorToSubspace(modelPositionA) + uModelSpaceBoundOffsets[0];
vec3 subspacePositionB = projectModelVectorToSubspace(modelPositionB) + uModelSpaceBoundOffsets[1];
vec3 vertexPosition = mix(subspacePositionA, subspacePositionB, aBoxCornerOffset);
emitCircle(uModelViewProjection * vec4(vertexPosition, 1.0), ng_lineWidth, 0.0);
uint cornerIndex = uint(aBoxCornerOffset.x + aBoxCornerOffset.y * 2.0 + aBoxCornerOffset.z * 4.0);
uint cornerPickOffset = ${Ra}u + cornerIndex;
${this.setPartIndex(e,"cornerPickOffset")};
`),e.setFragmentMain(`
vec4 borderColor = vec4(0.0, 0.0, 0.0, 1.0);
vec4 color = getCircleColor(vColor, borderColor);
color.a *= vClipCoefficient;
emitAnnotation(color);
`)})}drawEdges(e){const{gl:t}=this;this.enable(this.edgeShaderGetter,e,n=>{const s=n.attribute("aBoxCornerOffset1"),r=n.attribute("aBoxCornerOffset2");this.edgeBoxCornerOffsetsBuffer.bindToVertexAttrib(s,3,WebGL2RenderingContext.FLOAT,!1,28,0),this.edgeBoxCornerOffsetsBuffer.bindToVertexAttrib(r,4,WebGL2RenderingContext.FLOAT,!1,28,12),In(n,e.renderContext.projectionParameters,1),Dn(t,_d,e.count),t.disableVertexAttribArray(s),t.disableVertexAttribArray(r)})}drawCorners(e){const{gl:t}=this;this.enable(this.cornerShaderGetter,e,n=>{const s=n.attribute("aBoxCornerOffset");this.boxCornerOffsetsBuffer.bindToVertexAttrib(s,3,WebGL2RenderingContext.FLOAT,!1),Ea(n,e.renderContext.projectionParameters,{featherWidthInPixels:0}),Ta(n.gl,Rv,e.count),t.disableVertexAttribArray(s)})}draw(e){this.drawEdges(e),this.drawCorners(e)}}class jI extends Pv{constructor(){super(...arguments),this.faceShaderGetter=this.getDependentShader("annotation/boundingBox/crossSection/face",e=>{const{rank:t}=this;super.defineShader(e),Ia(e),Tn(e),e.addVarying("highp float","vClipCoefficient"),Fd(e),e.setVertexMain(`
float modelPositionA[${t}] = getBounds0();
float modelPositionB[${t}] = getBounds1();
for (int i = 0; i < ${t}; ++i) {
  float a = modelPositionA[i];
  float b = modelPositionB[i];
  modelPositionA[i] = min(a, b);
  modelPositionB[i] = max(a, b);
}
vClipCoefficient = getMaxSubspaceClipCoefficient(modelPositionA, modelPositionB);
if (vClipCoefficient == 0.0) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
vec3 subspacePositionA = projectModelVectorToSubspace(modelPositionA) + uModelSpaceBoundOffsets[0];
vec3 subspacePositionB = projectModelVectorToSubspace(modelPositionB) + uModelSpaceBoundOffsets[1];
int vertexIndex1 = gl_VertexID / ${gn};
int vertexIndex2 = vertexIndex1 == 5 ? 0 : vertexIndex1 + 1;
vec3 vertexPosition1 = getBoundingBoxPlaneIntersectionVertexPosition(subspacePositionB - subspacePositionA, subspacePositionA, subspacePositionA, subspacePositionB, vertexIndex1);
vec3 vertexPosition2 = getBoundingBoxPlaneIntersectionVertexPosition(subspacePositionB - subspacePositionA, subspacePositionA, subspacePositionA, subspacePositionB, vertexIndex2);
ng_lineWidth = 1.0;
${this.invokeUserMain}
emitLine(uModelViewProjection * vec4(vertexPosition1, 1.0),
         uModelViewProjection * vec4(vertexPosition2, 1.0),
         ng_lineWidth);
${this.setPartIndex(e)};
`),e.setFragmentMain(`
emitAnnotation(vec4(vColor.rgb, vColor.a * getLineAlpha() * vClipCoefficient));
`)}),this.fillShaderGetter=this.getDependentShader("annotation/boundingBox/crossSection/fill",e=>{const{rank:t}=this;super.defineShader(e),Ia(e),e.addVarying("highp float","vClipCoefficient"),HI(e),e.setVertexMain(`
float modelPositionA[${t}] = getBounds0();
float modelPositionB[${t}] = getBounds1();
for (int i = 0; i < ${t}; ++i) {
  float a = modelPositionA[i];
  float b = modelPositionB[i];
  modelPositionA[i] = min(a, b);
  modelPositionB[i] = max(a, b);
}
vClipCoefficient = getMaxSubspaceClipCoefficient(modelPositionA, modelPositionB);
if (vClipCoefficient == 0.0) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
vec3 subspacePositionA = projectModelVectorToSubspace(modelPositionA) + uModelSpaceBoundOffsets[0];
vec3 subspacePositionB = projectModelVectorToSubspace(modelPositionB) + uModelSpaceBoundOffsets[1];
int vertexIndex = gl_VertexID;
vec3 vertexPosition = getBoundingBoxPlaneIntersectionVertexPosition(subspacePositionB - subspacePositionA, subspacePositionA, subspacePositionA, subspacePositionB, vertexIndex);
gl_Position = uModelViewProjection * vec4(vertexPosition, 1);
${this.invokeUserMain}
${this.setPartIndex(e)};
`),e.setFragmentMain(`
emitAnnotation(vec4(vColor.rgb, vColor.a * vClipCoefficient));
`)})}enableForBoundingBox(e,t,n){super.enable(e,t,s=>{const r=t.renderContext.sliceView.projectionParameters.value;Nd(s,r.viewportNormalInGlobalCoordinates,r.centerDataPosition,t.renderSubspaceModelMatrix,t.renderSubspaceInvModelMatrix),n(s)})}draw(e){this.shaderControlState.parseResult.value.code.match(/\bsetBoundingBoxFillColor\b/)&&this.enableForBoundingBox(this.fillShaderGetter,e,()=>{eC(this.gl,WebGL2RenderingContext.TRIANGLE_FAN,0,6,e.count)}),this.enableForBoundingBox(this.faceShaderGetter,e,t=>{In(t,e.renderContext.projectionParameters,1),Dn(t.gl,6,e.count)})}}function YI(i,e){const t=i.length;for(let n=0;n<t;++n){const s=e[n],r=e[n+t],o=i[n];i[n]=Math.abs(s-o)<Math.abs(r-o)?s:r}}Ho(Je.AXIS_ALIGNED_BOUNDING_BOX,{sliceViewRenderHelper:jI,perspectiveViewRenderHelper:JI,defineShaderNoOpSetters(i){Mv(i),Av(i)},pickIdsPerInstance:zI,snapPosition(i,e,t,n){const s=i.length,r=new Float32Array(e,t,s*2);n>=Ra&&n<It?YI(i,r):n>=It&&n<Bd},getRepresentativePoint(i,e,t){t===kv||t>=Ra&&t<It||t>=It&&t<Bd,i.set(e.pointA)},updateViaRepresentativePoint(i,e,t){const n=e.length,{pointA:s,pointB:r}=i,o=new Float32Array(n),a=new Float32Array(n);for(let l=0;l<n;++l){const c=o[l]=e[l];a[l]=r[l]+(c-s[l])}return{...i,pointA:o,pointB:a}}});/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Us=0,Ud=Us+1,QI=Ud+2;function Nv(i){i.addVertexCode(`
void setEndpointMarkerSize(float startSize, float endSize) {}
void setEndpointMarkerBorderWidth(float startSize, float endSize) {}
void setEndpointMarkerColor(vec4 startColor, vec4 endColor) {}
void setEndpointMarkerBorderColor(vec4 startColor, vec4 endColor) {}
`)}function Ov(i){i.addVertexCode(`
void setLineWidth(float width) {}
void setLineColor(vec4 startColor, vec4 endColor) {}
`)}class Vv extends Wo{constructor(){super(...arguments),this.vertexIdHelper=this.registerDisposer(jn.get(this.gl)),this.edgeShaderGetter=this.getDependentShader("annotation/line/edge",e=>{const{rank:t}=this;this.defineShader(e),Tn(e),e.addVarying(`highp float[${t}]`,"vModelPosition"),e.addVertexCode(`
float ng_LineWidth;
`),Nv(e),e.addVertexCode(`
void setLineWidth(float width) {
  ng_LineWidth = width;
}
void setLineColor(vec4 startColor, vec4 endColor) {
  vColor = mix(startColor, endColor, getLineEndpointCoefficient());
}
`),e.setVertexMain(`
float modelPositionA[${t}] = getVertexPosition0();
float modelPositionB[${t}] = getVertexPosition1();
for (int i = 0; i < ${t}; ++i) {
  vModelPosition[i] = mix(modelPositionA[i], modelPositionB[i], getLineEndpointCoefficient());
}
ng_LineWidth = 1.0;
vColor = vec4(0.0, 0.0, 0.0, 0.0);
${this.invokeUserMain}
emitLine(uModelViewProjection * vec4(projectModelVectorToSubspace(modelPositionA), 1.0),
         uModelViewProjection * vec4(projectModelVectorToSubspace(modelPositionB), 1.0),
         ng_LineWidth);
${this.setPartIndex(e)};
`),e.setFragmentMain(`
float clipCoefficient = getSubspaceClipCoefficient(vModelPosition);
emitAnnotation(vec4(vColor.rgb, vColor.a * getLineAlpha() *
                                ${this.getCrossSectionFadeFactor()} *
                                clipCoefficient));
`)}),this.endpointShaderGetter=this.getDependentShader("annotation/line/endpoint",e=>{const{rank:t}=this;this.defineShader(e),xa(e,this.targetIsSliceView),e.addVarying("highp float","vClipCoefficient"),e.addVarying("highp vec4","vBorderColor"),Ov(e),e.addVertexCode(`
float ng_markerDiameter;
float ng_markerBorderWidth;
int getEndpointIndex() {
  return gl_VertexID / ${av};
}
void setEndpointMarkerSize(float startSize, float endSize) {
  ng_markerDiameter = mix(startSize, endSize, float(getEndpointIndex()));
}
void setEndpointMarkerBorderWidth(float startSize, float endSize) {
  ng_markerBorderWidth = mix(startSize, endSize, float(getEndpointIndex()));
}
void setEndpointMarkerColor(vec4 startColor, vec4 endColor) {
  vColor = mix(startColor, endColor, float(getEndpointIndex()));
}
void setEndpointMarkerBorderColor(vec4 startColor, vec4 endColor) {
  vBorderColor = mix(startColor, endColor, float(getEndpointIndex()));
}
`),e.setVertexMain(`
float modelPosition[${t}] = getVertexPosition0();
float modelPositionB[${t}] = getVertexPosition1();
for (int i = 0; i < ${t}; ++i) {
  modelPosition[i] = mix(modelPosition[i], modelPositionB[i], float(getEndpointIndex()));
}
vClipCoefficient = getSubspaceClipCoefficient(modelPosition);
vColor = vec4(0.0, 0.0, 0.0, 0.0);
vBorderColor = vec4(0.0, 0.0, 0.0, 1.0);
ng_markerDiameter = 5.0;
ng_markerBorderWidth = 1.0;
${this.invokeUserMain}
emitCircle(uModelViewProjection * vec4(projectModelVectorToSubspace(modelPosition), 1.0), ng_markerDiameter, ng_markerBorderWidth);
${this.setPartIndex(e,"uint(getEndpointIndex()) + 1u")};
`),e.setFragmentMain(`
vec4 color = getCircleColor(vColor, vBorderColor);
color.a *= vClipCoefficient;
emitAnnotation(color);
`)})}defineShader(e){fi(e);const{rank:t}=this;wo(e,"float",WebGL2RenderingContext.FLOAT,!1,"VertexPosition",t,2)}enable(e,t,n){super.enable(e,t,s=>{const r=s.vertexShaderInputBinders.VertexPosition;r.enable(1),this.gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,t.buffer.buffer),r.bind(this.geometryDataStride,t.bufferOffset);const{vertexIdHelper:o}=this;o.enable(),n(s),o.disable(),r.disable()})}drawEdges(e){this.enable(this.edgeShaderGetter,e,t=>{In(t,e.renderContext.projectionParameters,1),Dn(t.gl,1,e.count)})}drawEndpoints(e){this.enable(this.endpointShaderGetter,e,t=>{Ea(t,e.renderContext.projectionParameters,{featherWidthInPixels:.5}),Ta(t.gl,2,e.count)})}draw(e){this.drawEdges(e),this.drawEndpoints(e)}}function qI(i,e){const t=i.length;(0,w._q)(i,e.subarray(0,t),e.subarray(t),i)}function KI(i,e,t){const n=i.length,s=n*t;for(let r=0;r<n;++r)i[r]=e[s+r]}Ho(Je.LINE,{sliceViewRenderHelper:Vv,perspectiveViewRenderHelper:Vv,defineShaderNoOpSetters(i){Nv(i),Ov(i)},pickIdsPerInstance:QI,snapPosition(i,e,t,n){const s=i.length,r=new Float32Array(e,t,s*2);n===Us?qI(i,r):KI(i,r,n-Ud)},getRepresentativePoint(i,e,t){i.set(t===Us||t===Ud?e.pointA:e.pointB)},updateViaRepresentativePoint(i,e,t){const n={...i},s=e.length;switch(t){case Us:{const{pointA:r,pointB:o}=i,a=new Float32Array(s),l=new Float32Array(s);for(let c=0;c<s;++c){const d=a[c]=e[c];l[c]=o[c]+(d-r[c])}return{...i,pointA:a,pointB:l}}case Us+1:return{...i,pointA:new Float32Array(e)};case Us+2:return{...i,pointB:new Float32Array(e)}}return n}});/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class _v extends Wo{constructor(){super(...arguments),this.shaderGetter3d=this.getDependentShader("annotation/point:3d",e=>{fi(e),xa(e,this.targetIsSliceView),this.defineShaderCommon(e),e.addVertexMain(`
emitCircle(uModelViewProjection *
           vec4(projectModelVectorToSubspace(modelPosition), 1.0), ng_markerDiameter, ng_markerBorderWidth);
`),e.setFragmentMain(`
vec4 color = getCircleColor(vColor, vBorderColor);
emitAnnotation(color);
`)}),this.makeShaderGetter2d=e=>this.getDependentShader(`annotation/point:2d:${e}`,t=>{fi(t),Tn(t,!0),this.defineShaderCommon(t),t.addVertexMain(`
vec3 subspacePositionA = projectModelVectorToSubspace(modelPosition);
vec3 subspacePositionB = subspacePositionA;
vec4 baseProjection = uModelViewProjection * vec4(subspacePositionA, 1.0);
vec4 zCoeffs = uModelViewProjection[${e}];
float minZ = 1e30;
float maxZ = -1e30;
for (int i = 0; i < 3; ++i) {
  // Want: baseProjection[i] + z * zCoeffs[i] = -2.0 * (baseProjection.w - z * zCoeffs.w)
  //  i.e. baseProjection[i] + 2.0 * baseProjection.w < -z * (2.0 * zCoeffs.w + zCoeffs[i])
  //  i.e. baseProjection[i] + 2.0 * baseProjection.w < -z * k1
  float k1 = 2.0 * zCoeffs.w + zCoeffs[i];
  float q1 = -(baseProjection[i] + 2.0 * baseProjection.w) / k1;
  if (k1 != 0.0) {
    minZ = min(minZ, q1);
    maxZ = max(maxZ, q1);
  }
  // Want: baseProjection[i] + z * zCoeffs[i] = 2.0 * (baseProjection.w + z * zCoeffs.w)
  //  i.e. baseProjection[i] - 2.0 * baseProjection.w > z * (2.0 * zCoeffs.w - zCoeffs[i])
  //  i.e. baseProjection[i] - 2.0 * baseProjection.w > z * k2
  float k2 = 2.0 * zCoeffs.w - zCoeffs[i];
  float q2 = (baseProjection[i] - 2.0 * baseProjection.w) / k2;
  if (k2 != 0.0) {
    minZ = min(minZ, q2);
    maxZ = max(maxZ, q2);
  }
}
if (minZ > maxZ) minZ = maxZ = 0.0;
subspacePositionA[${e}] = minZ;
subspacePositionB[${e}] = maxZ;
emitLine(uModelViewProjection, subspacePositionA, subspacePositionB, ng_markerDiameter, ng_markerBorderWidth);
`),t.setFragmentMain(`
vec4 color = getRoundedLineColor(vColor, vBorderColor);
emitAnnotation(vec4(color.rgb, color.a * ${this.getCrossSectionFadeFactor()}));
`)}),this.shaderGetter2d=this.makeShaderGetter2d(2),this.shaderGetter1d=this.makeShaderGetter2d(1),this.vertexIdHelper=this.registerDisposer(jn.get(this.gl))}defineShaderCommon(e){const{rank:t}=this;wo(e,"float",WebGL2RenderingContext.FLOAT,!1,"VertexPosition",t),e.addVarying("highp vec4","vBorderColor"),e.addVertexCode(`
float ng_markerDiameter;
float ng_markerBorderWidth;
void setPointMarkerSize(float size) {
  ng_markerDiameter = size;
}
void setPointMarkerBorderWidth(float size) {
  ng_markerBorderWidth = size;
}
void setPointMarkerColor(vec4 color) {
  vColor = color;
}
void setPointMarkerBorderColor(vec4 color) {
  vBorderColor = color;
}
`),e.addVertexMain(`
ng_markerDiameter = 5.0;
ng_markerBorderWidth = 1.0;
vBorderColor = vec4(0.0, 0.0, 0.0, 1.0);
float modelPosition[${t}] = getVertexPosition0();
float clipCoefficient = getSubspaceClipCoefficient(modelPosition);
if (clipCoefficient == 0.0) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
${this.invokeUserMain}
vColor.a *= clipCoefficient;
vBorderColor.a *= clipCoefficient;
${this.setPartIndex(e)};
`)}enable(e,t,n){super.enable(e,t,s=>{const r=s.vertexShaderInputBinders.VertexPosition;r.enable(1),this.gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,t.buffer.buffer),r.bind(this.geometryDataStride,t.bufferOffset);const{vertexIdHelper:o}=this;o.enable(),n(s),o.disable(),r.disable()})}draw(e){const{numChunkDisplayDims:t}=e.chunkDisplayTransform;switch(t){case 3:this.enable(this.shaderGetter3d,e,n=>{Ea(n,e.renderContext.projectionParameters,{featherWidthInPixels:1}),Ta(n.gl,1,e.count)});break;case 2:case 1:this.enable(t===2?this.shaderGetter2d:this.shaderGetter1d,e,n=>{In(n,e.renderContext.projectionParameters,1),Dn(n.gl,1,e.count)});break}}}Ho(Je.POINT,{sliceViewRenderHelper:_v,perspectiveViewRenderHelper:_v,defineShaderNoOpSetters(i){i.addVertexCode(`
void setPointMarkerSize(float size) {}
void setPointMarkerBorderWidth(float size) {}
void setPointMarkerColor(vec4 color) {}
void setPointMarkerBorderColor(vec4 color) {}
`)},pickIdsPerInstance:1,snapPosition(i,e,t){i.set(new Float32Array(e,t,i.length))},getRepresentativePoint(i,e){i.set(e.point)},updateViaRepresentativePoint(i,e){return{...i,point:new Float32Array(e)}}});/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Bv=`
struct EllipseQuadraticForm {
  highp float A;  // x*x coefficient
  highp float B;  // x*y coefficient
  highp float C;  // y*y coefficient
  highp float D;  // x coefficient
  highp float E;  // y coefficient
  highp float F;  // 1 coefficient
};
`,XI=[Bv,`
EllipseQuadraticForm computeCrossSectionEllipse(mat3 A, vec3 c) {
  EllipseQuadraticForm p;
  p.A = A[0][0];
  p.B = A[0][1] + A[1][0];
  p.C = A[1][1];
  p.D = -2.0 * c[0] * A[0][0] - c[1] * (A[0][1] + A[1][0]) +
        c[2] * (A[0][2] + A[2][0]);
  p.E = -c[0] * (A[0][1] + A[1][0]) - 2.0 * c[1] * A[1][1] +
        c[2] * (A[1][2] + A[2][1]);
  p.F = c[0] * c[0] * A[0][0] + c[0] * c[1] * (A[0][1] + A[1][0]) -
        c[0] * c[2] * (A[0][2] + A[2][0]) + c[1] * c[1] * A[1][1] -
        c[1] * c[2] * (A[1][2] + A[2][1]) + c[2] * c[2] * A[2][2] - 1.0;
  return p;
}
`];function ZI(i,e){const t=[[i[0],i[1],i[2]],[i[3],i[4],i[5]],[i[6],i[7],i[8]]];return{A:t[0][0],B:t[0][1]+t[1][0],C:t[1][1],D:-2*e[0]*t[0][0]-e[1]*(t[0][1]+t[1][0])+e[2]*(t[0][2]+t[2][0]),E:-e[0]*(t[0][1]+t[1][0])-2*e[1]*t[1][1]+e[2]*(t[1][2]+t[2][1]),F:e[0]*e[0]*t[0][0]+e[0]*e[1]*(t[0][1]+t[1][0])-e[0]*e[2]*(t[0][2]+t[2][0])+e[1]*e[1]*t[1][1]-e[1]*e[2]*(t[1][2]+t[2][1])+e[2]*e[2]*t[2][2]-1}}const eR=[Bv,`
struct CenterOrientEllipse {
  vec2 k;   // center
  vec2 u1;  // minor axis direction
  vec2 u2;  // major axis direction
  float a;  // semimajor axis
  float b;  // semiminor axis
  bool valid; // indicates if the ellipse is valid
};
`,`
CenterOrientEllipse computeCenterOrientEllipse(EllipseQuadraticForm p) {
  CenterOrientEllipse r;
  float a11 = p.A;
  float a12 = p.B / 2.0;
  float a22 = p.C;
  float b1 = p.D;
  float b2 = p.E;
  float c = p.F;
  float kdenom = 2.0 * (a12 * a12 - a11 * a22);
  float k1 = r.k.x = (a22 * b1 - a12 * b2) / kdenom;
  float k2 = r.k.y = (a11 * b2 - a12 * b1) / kdenom;
  float mu = 1.0 / (a11 * k1 * k1 + 2.0 * a12 * k1 * k2 + a22 * k2 * k2 - c);
  float m11 = mu * a11;
  float m12 = mu * a12;
  float m22 = mu * a22;
  float lambdaTerm1 = m11 + m22;
  float lambdaTerm2 = sqrt((m11 - m22) * (m11 - m22) + 4.0 * m12 * m12);
  float lambda1 = ((lambdaTerm1 + lambdaTerm2) / 2.0);
  float lambda2 = ((lambdaTerm1 - lambdaTerm2) / 2.0);
  r.a = 1.0 / sqrt(lambda1);
  r.b = 1.0 / sqrt(lambda2);
  r.valid = lambda1 > 0.0 && lambda2 > 0.0;
  if (abs(m11 - m22) < 1e-6 && abs(m12) < 1e-6) {
    r.u1 = vec2(1.0, 0.0);
  } else if (m11 >= m22) {
    r.u1 = normalize(vec2(lambda1 - m22, m12));
  } else {
    r.u1 = normalize(vec2(m12, lambda1 - m11));
  }
  r.u2 = vec2(-r.u1.y, r.u1.x);
  return r;
}
`];function tR(i){const e=i.A,t=i.B/2,n=i.C,s=i.D,r=i.E,o=i.F,a=2*(t*t-e*n),l=(n*s-t*r)/a,c=(e*r-t*s)/a,d=1/(e*l*l+2*t*l*c+n*c*c-o),u=d*e,h=d*t,f=d*n,m=u+f,g=Math.sqrt((u-f)*(u-f)+4*h*h),v=(m+g)/2,y=(m-g)/2,S=1/Math.sqrt(v),x=1/Math.sqrt(y);let b;u>=f?b=w.Zc.fromValues(v-f,h):b=w.Zc.fromValues(h,v-u),w.Zc.normalize(b,b);const E=w.Zc.fromValues(-b[1],b[0]);return{k:w.Zc.fromValues(l,c),u1:b,u2:E,a:S,b:x,lambda1:v,lambda2:y,m11:u,m12:h,m22:f,valid:v>0&&y>0}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function nR(i,e){const t=new Float32Array((i+1)*(e+1)*3);let n=0;for(let s=0;s<=i;++s){const r=s*Math.PI/i,o=Math.sin(r),a=Math.cos(r);for(let l=0;l<=e;++l){const c=l*2*Math.PI/e,d=Math.sin(c),u=Math.cos(c);t[n++]=u*o,t[n++]=a,t[n++]=d*o}}return t}function iR(i,e){const t=new Uint16Array(i*e*6);let n=0;for(let s=0;s<i;s++)for(let r=0;r<e;r++){const o=s*(e+1)+r,a=o+e+1;t[n++]=o,t[n++]=a,t[n++]=o+1,t[n++]=a,t[n++]=a+1,t[n++]=o+1}return t}class sR extends D.O8{constructor(e,t,n){super(),this.vertexBuffer=this.registerDisposer(Ri(e,WebGL2RenderingContext.ARRAY_BUFFER,nR,t,n)).value,this.indexBuffer=this.registerDisposer(Ri(e,WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER,iR,t,n)).value,this.numIndices=t*n*6}defineShader(e){e.addAttribute("highp vec3","aSphereVertex"),e.addVarying("highp float","vLightingFactor"),e.addVertexCode(`
void emitSphere(mat4 projectionMatrix, mat4 normalTransformMatrix, vec3 centerPosition, vec3 radii, vec4 lightDirection) {
  vec3 vertexPosition = aSphereVertex * radii + centerPosition;
  gl_Position = projectionMatrix * vec4(vertexPosition, 1.0);
  vec3 normal = normalize((normalTransformMatrix * vec4(aSphereVertex / max(radii, 1e-6), 0.0)).xyz);
  vLightingFactor = abs(dot(normal, uLightDirection.xyz)) + uLightDirection.w;
}
`)}draw(e,t){const n=e.attribute("aSphereVertex");this.vertexBuffer.bindToVertexAttrib(n,3,WebGL2RenderingContext.FLOAT,!1),this.indexBuffer.bind(),e.gl.drawElementsInstanced(WebGL2RenderingContext.TRIANGLES,this.numIndices,WebGL2RenderingContext.UNSIGNED_SHORT,0,t),e.gl.disableVertexAttribArray(n)}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Fv=w.pB.create(),rR=!1;class Uv extends Wo{defineShader(e){const{rank:t}=this;wo(e,"float",WebGL2RenderingContext.FLOAT,!1,"CenterAndRadii",t,2),e.addVertexCode(`
struct SubspaceParams {
  highp vec3 subspaceCenter;
  highp vec3 subspaceRadii;
  highp float clipCoefficient;
  bool cull;
};
SubspaceParams getSubspaceParams() {
  SubspaceParams params;
  highp float modelCenter[${t}] = getCenterAndRadii0();
  highp float modelRadii[${t}] = getCenterAndRadii1();
  float radiusAdjustment = 1.0;
  float clipCoefficient = 1.0;
  for (int i = 0; i < ${t}; ++i) {
    float r = modelRadii[i];
    float c = modelCenter[i];
    float x = uModelClipBounds[i];
    float clipRadius = uModelClipBounds[i + ${t}];
    if (r != 0.0 && clipRadius != 0.0) {
      float d = c - x;
      d = d * d;
      radiusAdjustment -= d / (r * r);
    }
    float e = abs(x - clamp(x, c - r, c + r)) * clipRadius;
    clipCoefficient *= max(0.0, 1.0 - e);
  }
  radiusAdjustment = sqrt(max(0.0, radiusAdjustment));
  params.subspaceCenter = projectModelVectorToSubspace(modelCenter);
  params.subspaceRadii = projectModelVectorToSubspace(modelRadii) * radiusAdjustment;
  params.clipCoefficient = clipCoefficient;
  params.cull = clipCoefficient == 0.0 || radiusAdjustment == 0.0;
  return params;
}
void setEllipsoidFillColor(vec4 color) {
  vColor = color;
}
`)}enable(e,t,n){super.enable(e,t,s=>{const r=s.vertexShaderInputBinders.CenterAndRadii;r.enable(1),this.gl.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER,t.buffer.buffer),r.bind(this.geometryDataStride,t.bufferOffset),n(s),r.disable()})}}class oR extends Uv{constructor(){super(...arguments),this.sphereRenderHelper=this.registerDisposer(new sR(this.gl,10,10)),this.shaderGetter=this.getDependentShader("annotation/ellipsoid/projection",e=>{this.defineShader(e),this.sphereRenderHelper.defineShader(e),e.addUniform("highp vec4","uLightDirection"),e.addUniform("highp mat4","uNormalTransform"),e.addVarying("highp float","vClipCoefficient"),e.setVertexMain(`
SubspaceParams params = getSubspaceParams();
if (params.cull) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
vClipCoefficient = params.clipCoefficient;
${this.invokeUserMain}
emitSphere(uModelViewProjection, uNormalTransform, params.subspaceCenter, params.subspaceRadii, uLightDirection);
${this.setPartIndex(e)};
`),e.setFragmentMain(`
emitAnnotation(vec4(vColor.rgb * vLightingFactor, vColor.a * vClipCoefficient));
`)}),this.tempLightVec=new Float32Array(4)}draw(e){this.enable(this.shaderGetter,e,t=>{const{gl:n}=t,s=this.tempLightVec,{lightDirection:r,ambientLighting:o,directionalLighting:a}=e.renderContext;w.eR.scale(s,r,a),s[3]=o,n.uniform4fv(t.uniform("uLightDirection"),s),n.uniformMatrix4fv(t.uniform("uNormalTransform"),!1,w.pB.transpose(w.pB.create(),e.renderSubspaceInvModelMatrix)),this.sphereRenderHelper.draw(t,e.count)})}}class aR extends Uv{constructor(){super(...arguments),this.shaderGetter=this.getDependentShader("annotation/ellipsoid/crossSection",e=>{fi(e),this.defineShader(e),e.addUniform("highp mat4","uViewportToObject"),e.addUniform("highp mat4","uObjectToViewport"),e.addUniform("highp mat4","uViewportToDevice"),e.addAttribute("highp vec2","aCornerOffset"),e.addVarying("highp vec2","vCircleCoord"),e.addVarying("highp float","vClipCoefficient"),e.addVertexCode(XI),e.addVertexCode(eR),e.addVertexCode(uc),e.setVertexMain(`
SubspaceParams params = getSubspaceParams();
if (params.cull) {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
  return;
}
vClipCoefficient = params.clipCoefficient;
mat3 Aobject = mat3(0.0);
for (int i = 0; i < 3; ++i) {
  float r = max(params.subspaceRadii[i], 1e-3);
  Aobject[i][i] = 1.0 / (r * r);
}
mat3 RviewportToObject = mat3(uViewportToObject);
mat3 Aviewport = transpose(RviewportToObject) * Aobject * RviewportToObject;
vec3 cViewport = (uObjectToViewport * vec4(params.subspaceCenter, 1.0)).xyz;
EllipseQuadraticForm quadraticForm = computeCrossSectionEllipse(Aviewport, cViewport);
vec2 u1, u2;
float a, b;
CenterOrientEllipse centerOrient = computeCenterOrientEllipse(quadraticForm);
vec2 cornerOffset = getQuadVertexPosition(vec2(-1.0, -1.0), vec2(1.0, 1.0));
vec2 viewportCorner = centerOrient.k +
  centerOrient.u1 * cornerOffset.x * centerOrient.a +
  centerOrient.u2 * cornerOffset.y * centerOrient.b;
if (centerOrient.valid) {
  gl_Position = uViewportToDevice * vec4(viewportCorner, 0.0, 1.0);
} else {
  gl_Position = vec4(2.0, 0.0, 0.0, 1.0);
}
vCircleCoord = cornerOffset;
${this.invokeUserMain}
${this.setPartIndex(e)};
`),e.setFragmentMain(`
if (dot(vCircleCoord, vCircleCoord) > 1.0) {
  discard;
}
emitAnnotation(vec4(vColor.rgb, vColor.a * vClipCoefficient));
`)}),this.vertexIdHelper=this.registerDisposer(jn.get(this.gl))}draw(e){this.enable(this.shaderGetter,e,t=>{const{gl:n}=t,s=e.renderContext.sliceView.projectionParameters.value,r=w.pB.multiply(Fv,e.renderSubspaceInvModelMatrix,s.invViewMatrix);n.uniformMatrix4fv(t.uniform("uViewportToObject"),!1,r),n.uniformMatrix4fv(t.uniform("uViewportToDevice"),!1,s.projectionMat);const o=Fv;w.pB.invert(o,r),n.uniformMatrix4fv(t.uniform("uObjectToViewport"),!1,o);const{vertexIdHelper:a}=this;if(a.enable(),Do(n,1,e.count),a.disable(),rR){const l=w.eR.fromValues(3406.98779296875,3234.910400390625,4045),c=w.eR.fromValues(10,10,10),d=w.w0.create();d[0]=1/(c[0]*c[0]),d[4]=1/(c[1]*c[1]),d[8]=1/(c[2]*c[2]);const u=w.w0.fromMat4(w.w0.create(),r),h=w.w0.multiply(w.w0.create(),w.w0.transpose(w.w0.create(),u),d);w.w0.multiply(h,h,u);const f=w.eR.transformMat4(w.eR.create(),l,o);console.log("Aviewport",h),console.log("cViewport",f);const m=ZI(h,f),g=tR(m);console.log(m),console.log(g)}})}}Ho(Je.ELLIPSOID,{sliceViewRenderHelper:aR,perspectiveViewRenderHelper:oR,defineShaderNoOpSetters(i){i.addVertexCode(`
void setEllipsoidFillColor(vec4 color) {}
`)},pickIdsPerInstance:1,snapPosition:()=>{},getRepresentativePoint(i,e){i.set(e.center)},updateViaRepresentativePoint(i,e){return{...i,center:new Float32Array(e)}}});/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const $v=w.pB.create(),Gv=w.eR.create();function zv(i){i.addUniform("highp vec3","uTranslation"),i.addUniform("highp mat4","uProjectionMatrix"),i.addUniform("highp vec3","uChunkDataSize"),i.addUniform("highp vec3","uLowerClipBound"),i.addUniform("highp vec3","uUpperClipBound"),i.setFragmentMain(`
emit(vec4(1.0, 1.0, 1.0, getLineAlpha()), 0u);
`)}const lR={defineShader(i){zv(i),Tn(i),i.addVertexCode(`
const vec3[24] boxCornerOffsets = vec3[](
  vec3(0, 0, 0), vec3(0, 0, 1),  // e1
  vec3(1, 0, 0), vec3(1, 0, 1),  // e2
  vec3(0, 1, 0), vec3(0, 1, 1),  // e3
  vec3(1, 1, 0), vec3(1, 1, 1),  // e4
  vec3(0, 0, 0), vec3(0, 1, 0),  // e5
  vec3(0, 0, 1), vec3(0, 1, 1),  // e6
  vec3(1, 0, 0), vec3(1, 1, 0),  // e7
  vec3(1, 0, 1), vec3(1, 1, 1),  // e8
  vec3(0, 0, 0), vec3(1, 0, 0),  // e9
  vec3(0, 0, 1), vec3(1, 0, 1),  // e10
  vec3(0, 1, 0), vec3(1, 1, 0),  // e11
  vec3(0, 1, 1), vec3(1, 1, 1)  // e12
);
`),i.setVertexMain(`
int edgeIndex = gl_VertexID / ${gn};
vec3 cornerA = max(uLowerClipBound, min(uUpperClipBound, uTranslation));
vec3 cornerB = max(uLowerClipBound, min(uUpperClipBound, uTranslation + uChunkDataSize));
vec3 vertexPosition1 = mix(cornerA, cornerB, boxCornerOffsets[edgeIndex * 2]);
vec3 vertexPosition2 = mix(cornerA, cornerB, boxCornerOffsets[edgeIndex * 2 + 1]);
emitLine(uProjectionMatrix * vec4(vertexPosition1, 1.0),
         uProjectionMatrix * vec4(vertexPosition2, 1.0),
         2.0);
`)},initialize(i,e){In(i,e,1)},draw(i,e,t){const{gl:n}=i,s=$v,{chunkLayout:r}=e;w.pB.multiply(s,t.viewProjectionMat,r.transform),n.uniformMatrix4fv(i.uniform("uProjectionMatrix"),!1,s),n.uniform3fv(i.uniform("uChunkDataSize"),r.size),n.uniform3fv(i.uniform("uLowerClipBound"),e.lowerClipDisplayBound),n.uniform3fv(i.uniform("uUpperClipBound"),e.upperClipDisplayBound);const o=r.size,{curPositionInChunks:a,chunkDisplayDimensionIndices:l}=e,c=Gv;for(let d=0;d<3;++d){const u=l[d];c[d]=(u===-1?0:a[u])*o[d]}n.uniform3fv(i.uniform("uTranslation"),c),Dn(n,_d,1)}},cR={defineShader(i){Ia(i),zv(i),Tn(i),i.setVertexMain(`
int vertexIndex1 = gl_VertexID / ${gn};
int vertexIndex2 = vertexIndex1 == 5 ? 0 : vertexIndex1 + 1;
vec3 vertexPosition1 = getBoundingBoxPlaneIntersectionVertexPosition(uChunkDataSize, uTranslation, uLowerClipBound, uUpperClipBound, vertexIndex1);
vec3 vertexPosition2 = getBoundingBoxPlaneIntersectionVertexPosition(uChunkDataSize, uTranslation, uLowerClipBound, uUpperClipBound, vertexIndex2);
emitLine(uProjectionMatrix * vec4(vertexPosition1, 1.0),
         uProjectionMatrix * vec4(vertexPosition2, 1.0),
         2.0);
`)},initialize(i,e){In(i,e,1)},draw(i,e,t){const{gl:n}=i,s=$v,{chunkLayout:r}=e;w.pB.multiply(s,t.viewProjectionMat,r.transform),n.uniformMatrix4fv(i.uniform("uProjectionMatrix"),!1,s),n.uniform3fv(i.uniform("uChunkDataSize"),r.size),n.uniform3fv(i.uniform("uLowerClipBound"),e.lowerClipDisplayBound),n.uniform3fv(i.uniform("uUpperClipBound"),e.upperClipDisplayBound);const o=r.size,{curPositionInChunks:a,chunkDisplayDimensionIndices:l}=e,c=Gv;for(let d=0;d<3;++d){const u=l[d];c[d]=(u===-1?0:a[u])*o[d]}n.uniform3fv(i.uniform("uTranslation"),c),Nd(i,t.viewportNormalInGlobalCoordinates,t.centerDataPosition,r.transform,r.invTransform),Dn(n,6,1)}};var dR=Object.defineProperty,uR=Object.getOwnPropertyDescriptor,hR=(i,e,t,n)=>{for(var s=n>1?void 0:n?uR(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&dR(e,t,s),s};/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const pR=w.pB.create();function fR(i){if(i!==void 0)return e=>{const{relatedSegments:t}=e;if(t===void 0)return!1;for(let n=0,s=t.length;n<s;++n){const r=i[n];if(r==null)continue;const{visibleSegments:o,segmentEquivalences:a}=r.segmentationGroupState.value;for(const l of t[n])if(o.has(a.get(l)))return!0}return!1}}function gR(i,e){const t=new jb(i.annotationPropertySerializers);for(const n of i)(e===void 0||e(n))&&t.add(n);return t.serialize()}let $d=class extends ir(Cr){constructor(i,e,t,n){super(n),this.chunkManager=i,this.source=e,this.segmentationStates=t,this.initializeCounterpart(this.chunkManager.rpc,{chunkManager:this.chunkManager.rpcId,source:e.rpcId,segmentationStates:this.serializeDisplayState()});const s=()=>{const r={id:this.rpcId,segmentationStates:this.serializeDisplayState()};this.rpc.invoke(OE,r)};this.registerDisposer(t.changed.add(s))}serializeDisplayState(){const{value:i}=this.segmentationStates;if(i!==void 0)return i.map(e=>e==null?e:Bm(e.segmentationGroupState.value))}};$d=hR([Kt(NE)],$d);class mR extends D.O8{constructor(e,t){super(),this.chunkManager=e,this.state=t,this.layerChunkProgressInfo=new lo,this.numPickIds=0,this.generation=-1,this.redrawNeeded=new j.IY,this.serializedAnnotations=void 0,this.handleChangeAffectingBuffer=()=>{this.generation=-1,this.redrawNeeded.dispatch()},this.segmentationStates=this.registerDisposer((0,A.Uq)((s,r)=>{const{displayState:o,source:a}=this.state,{relationshipStates:l}=o;return o.displayUnfiltered.value?void 0:a.relationships.map(c=>{const d=l.get(c);return d.showMatches.value?d.segmentationState.value:void 0})},[this.state.displayState.relationshipStates,this.state.displayState.ignoreNullSegmentFilter],(s,r)=>s===void 0||r===void 0?s===r:(0,z.r1)(s,r))),this.registerDisposer(t),this.registerDisposer(this.source.changed.add(this.handleChangeAffectingBuffer)),this.registerDisposer((0,A.no)((s,r)=>{if(this.handleChangeAffectingBuffer(),r!==void 0)for(const o of r)o!=null&&s.registerDisposer((0,A.aM)((a,l)=>{a.registerDisposer(l.visibleSegments.changed.add(()=>this.handleChangeAffectingBuffer())),a.registerDisposer(l.segmentEquivalences.changed.add(()=>this.handleChangeAffectingBuffer()))},o.segmentationGroupState))},this.segmentationStates)),this.source instanceof ss||(this.sharedObject=this.registerDisposer(new $d(e,this.source,this.segmentationStates,this.layerChunkProgressInfo)));const{displayState:n}=this.state;this.registerDisposer(n.color.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(n.shader.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(n.shaderControls.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.hoverState.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.transform.changed.add(this.redrawNeeded.dispatch))}get source(){return this.state.source}get transform(){return this.state.transform}get hoverState(){return this.state.displayState.hoverState}get visibility(){const{sharedObject:e}=this;if(e!==void 0)return e.visibility}get gl(){return this.chunkManager.gl}updateBuffer(){const{source:e}=this;if(e instanceof ss){const t=e.changed.count;if(this.generation!==t){let{buffer:n}=this;n===void 0&&(n=this.buffer=this.registerDisposer(new At(this.chunkManager.gl))),this.generation=t;const s=this.serializedAnnotations=gR(e,fR(this.segmentationStates.value));n.setData(this.serializedAnnotations.data),this.numPickIds=sg(s)}}}}function Wv(i){const{chunkTransform:e}=i,{unpaddedRank:t}=e.modelTransform,n=new Float32Array(t*2),s=new Float32Array(t*3);s.fill(0),n.fill(1,t);const{numChunkDisplayDims:r,chunkDisplayDimensionIndices:o}=i;for(let a=0;a<r;++a){const l=o[a];n[t+l]=0,s[l*3+a]=1}return{modelClipBounds:n,renderSubspaceTransform:s}}function Hv(i,e,t){t.clearMessages();const n=l=>{t.addMessage({severity:xn.error,message:l})};if(i.error!==void 0)return n(i.error);const s=Jh(i.modelTransform,e.displayDimensionIndices);let r;try{r=jh(i,s)}catch(l){return n(l.message)}const{modelClipBounds:o,renderSubspaceTransform:a}=Wv(r);return{chunkTransform:i,chunkDisplayTransform:r,modelClipBounds:o,renderSubspaceTransform:a}}function Gd(i,e){class t extends i{constructor(s,r){super(),this.base=s,this.renderScaleHistogram=r,this.curRank=-1,this.renderHelpers=[],this.isAnnotation=!0;const o=s.visibility;o!==void 0&&this.registerDisposer(o.add(this.visibility)),this.registerDisposer(this.renderScaleHistogram.visibility.add(this.visibility)),this.registerDisposer(()=>{for(const a of this.renderHelpers)a.dispose()}),this.role=s.state.role,this.registerDisposer(s.redrawNeeded.add(this.redrawNeeded.dispatch)),this.handleRankChanged(),this.registerDisposer(this.base.state.displayState.shaderControls.histogramSpecifications.producerVisibility.add(this.visibility))}handleRankChanged(){const{rank:s}=this.base.source;if(s===this.curRank)return;this.curRank=s,this.tempChunkPosition=new Float32Array(s);const{renderHelpers:r,gl:o}=this;for(const c of r)c.dispose();const{properties:a}=this.base.source,{displayState:l}=this.base.state;for(const c of _n){const d=wr(c),u=d[e],h=r[c]=new u(o,c,s,a,l.shaderControls,l.fallbackShaderControls,l.shaderError);h.pickIdsPerInstance=d.pickIdsPerInstance,h.targetIsSliceView=e==="sliceViewRenderHelper"}}attach(s){super.attach(s),this.handleRankChanged();const{chunkTransform:r}=this,o=s.view.displayDimensionRenderInfo.value;s.state={chunkTransform:r,displayDimensionRenderInfo:o,chunkRenderParameters:Hv(r,o,s.messages)}}updateAttachmentState(s){const r=s.state;this.handleRankChanged();const{chunkTransform:o}=this,a=s.view.displayDimensionRenderInfo.value;return r!==void 0&&r.chunkTransform===o&&r.displayDimensionRenderInfo===a?r.chunkRenderParameters:(r.chunkTransform=o,r.displayDimensionRenderInfo=a,r.chunkRenderParameters=Hv(o,a,s.messages))}get chunkTransform(){return this.base.state.chunkTransform.value}updateModelClipBounds(s,r){const{modelClipBounds:o}=r,a=this.curRank,{chunkTransform:l}=r;as(o.subarray(0,a),s.projectionParameters.globalPosition,this.base.state.localPosition.value,l.layerRank,l.combinedGlobalLocalToChunkTransform)}get gl(){return this.base.chunkManager.gl}drawGeometryChunkData(s,r,o,a=1){if(!s.bufferValid){let{buffer:l}=s;l===void 0&&(l=s.buffer=new At(this.gl));const{serializedAnnotations:c}=s;l.setData(c.data),s.numPickIds=sg(c),s.bufferValid=!0}this.drawGeometry(s,r,o,a)}drawGeometry(s,r,o,a=1){const{base:l}=this,{chunkDisplayTransform:c}=o,{serializedAnnotations:d}=s,{typeToIdMaps:u,typeToOffset:h}=d;let f=0;r.emitPickID&&(f=r.pickIDs.register(this,s.numPickIds,0,0,s));const m=l.hoverState.value,g=w.pB.multiply(pR,r.projectionParameters.viewProjectionMat,c.displaySubspaceModelMatrix),v={annotationLayer:l,renderContext:r,selectedIndex:0,basePickId:f,buffer:s.buffer,bufferOffset:0,count:0,modelViewProjectionMatrix:g,modelClipBounds:o.modelClipBounds,subspaceMatrix:o.renderSubspaceTransform,renderSubspaceModelMatrix:c.displaySubspaceModelMatrix,renderSubspaceInvModelMatrix:c.displaySubspaceInvModelMatrix,chunkDisplayTransform:c},y=this.base.state.displayState.shaderControls.histogramSpecifications.visibleHistograms>0;for(const S of _n){const x=u[S];let b=x.size;if(b>0){const E=wr(S);let C=4294967295;if(m!==void 0){const T=x.get(m.id);T!==void 0&&(C=T*E.pickIdsPerInstance)}b=Math.round(b*a),v.count=b,v.bufferOffset=h[S],v.selectedIndex=C;const k=this.renderHelpers[S];k.draw(v),y&&(k.computeHistograms(v,r.frameNumber),r.bindFramebuffer()),v.basePickId+=b*E.pickIdsPerInstance}}}updateMouseState(s,r,o,a){const l=a,{serializedAnnotations:c}=l,{typeToIds:d,typeToOffset:u}=c,h=this.curRank,f=this.chunkTransform;if(f.error===void 0)for(const m of _n){const g=d[m],v=wr(m),{pickIdsPerInstance:y}=v;if(o<g.length*y){const S=Math.floor(o/y),x=g[S],b=o%y;s.pickedAnnotationId=x,s.pickedAnnotationLayer=this.base.state,s.pickedOffset=b,s.pickedAnnotationBuffer=c.data.buffer,s.pickedAnnotationType=m,s.pickedAnnotationBufferBaseOffset=c.data.byteOffset+u[m],s.pickedAnnotationIndex=S,s.pickedAnnotationCount=g.length;const E=this.tempChunkPosition,{chunkToLayerTransform:C,combinedGlobalLocalToChunkTransform:k,layerRank:T}=f,{globalToRenderLayerDimensions:L}=f.modelTransform,{position:_}=s;if(!as(E,_,this.base.state.localPosition.value,T,k))return;const R=this.base.source.annotationPropertySerializers[m];v.snapPosition(E,s.pickedAnnotationBuffer,s.pickedAnnotationBufferBaseOffset+s.pickedAnnotationIndex*R.propertyGroupBytes[0],b);const P=L.length;for(let V=0;V<P;++V){const $=L[V];if($===-1)continue;let Q=C[(h+1)*h+$];for(let K=0;K<h;++K)Q+=E[K]*C[K*(T+1)+$];Number.isFinite(Q)&&(_[V]=Q)}return}o-=g.length*y}}transformPickedValue(s){const{pickedAnnotationBuffer:r}=s;if(r===void 0)return;const{properties:o}=this.base.source;if(o.length===0)return;const{pickedAnnotationBufferBaseOffset:a,pickedAnnotationType:l,pickedAnnotationIndex:c,pickedAnnotationCount:d}=s,{annotationPropertySerializers:u}=this.base.source,h=new Array(o.length);return u[l].deserialize(new DataView(r),a,c,d,F.LITTLE===te,h),Vb(o[0],h[0])}}return t}const Jv=i=>class extends i{constructor(){super(...arguments),this.layerChunkProgressInfo=this.base.layerChunkProgressInfo}draw(t,n){const s=this.updateAttachmentState(n);if(this.curRank===0||s===void 0)return;this.updateModelClipBounds(t,s);const{source:r}=this.base;if(r instanceof ss){const{base:o}=this;o.updateBuffer(),this.drawGeometry(o,t,s)}else{const{renderScaleHistogram:o}=this;o.begin(this.base.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber),this.drawGeometryChunkData(r.temporary.data,t,s);const{value:a}=this.base.segmentationStates;let l=0,c=0;if(a!==void 0)for(let d=0,u=a.length;d<u;++d){const h=a[d];if(h==null)continue;const f=r.segmentFilteredSources[d].chunks;Ds(h.segmentationGroupState.value,m=>{const g=vn(m),v=f.get(g);if(v!==void 0&&v.state===Be.GPU_MEMORY){const{data:y}=v;if(y===void 0)return;this.drawGeometryChunkData(y,t,s),++l}else++c})}o.add(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,l,c)}}isReady(){const{base:t}=this,{source:n}=t;if(!(n instanceof Tr))return!0;const{value:s}=this.base.segmentationStates;if(s===void 0)return!0;for(let r=0,o=s.length;r<o;++r){const a=s[r];if(a===null)return!1;if(a===void 0)continue;const l=n.segmentFilteredSources[r].chunks;let c=!1;if(Ds(a.segmentationGroupState.value,d=>{const u=vn(d);l.has(u)||(c=!0)}),c)return!1}return!0}},jv=Gd($i,"perspectiveViewRenderHelper");class vR extends Jv(jv){}const Yv=i=>{class e extends i{constructor(n){super(n.annotationLayer,n.renderScaleHistogram),this.wireFrameRenderHelper=this instanceof Bi?cR:lR,this.wireFrameShaderGetter=Ii(this,this.gl,{memoizeKey:`annotation/wireFrameShader:${this instanceof Bi}`,parameters:(0,A.XZ)(void 0),defineShader:o=>{this.wireFrameRenderHelper.defineShader(o)}}),this.renderScaleTarget=n.renderScaleTarget,this.registerDisposer(this.renderScaleTarget.changed.add(this.redrawNeeded.dispatch));const s=this.registerDisposer(new Cr(this.layerChunkProgressInfo)),r=this.base.chunkManager.rpc;s.RPC_TYPE_ID=AE,s.initializeCounterpart(r,{chunkManager:this.base.chunkManager.rpcId,localPosition:this.registerDisposer(ut.makeFromExisting(r,this.base.state.localPosition)).rpcId,renderScaleTarget:this.registerDisposer(ut.makeFromExisting(r,this.renderScaleTarget)).rpcId}),this.backend=s}attach(n){super.attach(n),n.state.sources=n.registerDisposer((0,A.no)((s,r,o)=>{const a=Ko(o,r,l=>this.base.state.source.getSources(l),n.messages,this);for(const l of a)for(const c of l)s.registerDisposer(c.source),Object.assign(c,Wv(c.chunkDisplayTransform));return n.view.flushBackendProjectionParameters(),this.backend.rpc.invoke(ME,{layer:this.backend.rpcId,view:n.view.rpcId,displayDimensionRenderInfo:o,sources:Yo(a)}),this.redrawNeeded.dispatch(),a},this.base.state.transform,n.view.displayDimensionRenderInfo))}draw(n,s){const r=this.updateAttachmentState(s);if(this.curRank===0||r===void 0)return;const o=s.state.sources.value;if(o.length===0)return;this.updateModelClipBounds(n,r);const{renderScaleHistogram:a}=this;a.begin(this.base.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber);const{projectionParameters:l}=n;let c;if(n.wireFrame){const{shader:d}=this.wireFrameShaderGetter(n.emitter);if(d===null)return;d.bind(),this.wireFrameRenderHelper.initialize(d,l),c=d}Qf(l,this.base.state.localPosition.value,this.renderScaleTarget.value,o[0],()=>{},(d,u,h,f,m)=>{const g=d.source.chunks.get(d.curPositionInChunks.join());let v;if(g===void 0||g.state!==Be.GPU_MEMORY)v=0;else{const{data:y}=g;if(y===void 0)return;c!==void 0?this.wireFrameRenderHelper.draw(c,d,l):this.drawGeometryChunkData(y,n,r,h),v=1}a.add(f,m,v,1-v)})}isReady(n,s){const r=this.updateAttachmentState(s);if(this.curRank===0||r===void 0)return;const o=s.state.sources.value;if(o.length===0)return;this.updateModelClipBounds(n,r);const{projectionParameters:a}=n;let l=!0;return Qf(a,this.base.state.localPosition.value,this.renderScaleTarget.value,o[0],()=>{},(c,d,u,h,f)=>{const m=c.source.chunks.get(c.curPositionInChunks.join());if(m===void 0||m.state!==Be.GPU_MEMORY){l=!1;return}}),l}}return e},yR=Yv(jv),SR=Yv(Gd(Bi,"sliceViewRenderHelper")),bR=Jv(Gd(Bi,"sliceViewRenderHelper"));var ka=G(4499);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Qv(i={}){return _e({svg:ka,...i})}var wR=G(1252);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Yn(i={}){const e=_e({svg:wR,...i}),t=e.firstElementChild;return t.style.fill="white",e}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const qv=10,La=.5;class CR{constructor(){this.anchorIndex=0,this.anchorClientOffset=0}splice(e){let{anchorIndex:t}=this,n=0;for(const s of e){if(n+=s.retainCount,t<n)break;const{deleteCount:r}=s;if(t<n+r){t=n;break}const{insertCount:o}=s;t=t-r+o,n+=o-o}this.anchorIndex=t}}class Kv{constructor(){this.startIndex=0,this.endIndex=0,this.anchorIndex=0,this.anchorOffset=0,this.scrollOffset=0,this.viewportWidth=0}}class xR{constructor(){this.itemSize=[],this.totalKnownSize=0,this.numItemsInTotalKnownSize=0}get averageSize(){return this.totalKnownSize/this.numItemsInTotalKnownSize}getEstimatedSize(e){return this.itemSize[e]??this.averageSize}getEstimatedTotalSize(){return this.totalKnownSize/this.numItemsInTotalKnownSize*this.itemSize.length}getEstimatedOffset(e,t=0,n=0){for(;t<e;++t)n+=this.getEstimatedSize(t);for(;t>e;--t)n-=this.getEstimatedSize(t-1);return n}getRangeSize(e,t){let n=0;const{itemSize:s,averageSize:r}=this;for(let o=e;o<t;++o)n+=s[o]??r;return n}splice(e){let{itemSize:t}=this;t=this.itemSize=(0,z.eL)(t,e),this.totalKnownSize=t.reduce((n,s)=>n+s,0),this.numItemsInTotalKnownSize=t.reduce(n=>n+1,0)}}function ER(i,e,t,n,s,r){const{anchorIndex:o,anchorClientOffset:a}=r,l=s.getEstimatedOffset(o);let c,d,u,h,f;if(n===0||s.totalKnownSize===0)c=Math.max(0,o-qv/2),d=Math.min(t,c+qv),f=o,u=0,h=a;else{const m=s.getEstimatedTotalSize(),g=Math.max(0,m-n);h=l-a,h=Math.max(0,Math.min(g,h));const v=h-2*La*n,y=h-La*n,S=h+n+La*n,x=l-a+n+2*La*n;c=Math.min(t,e.startIndex);let b=s.getEstimatedOffset(c,o,l);if(b<v)for(;c+1<t;++c){const C=s.getEstimatedSize(c);if(b+C>=y)break;b+=C}if(b>=y)for(;b>v&&c>0;--c){const C=s.getEstimatedSize(c-1);b-=C}d=Math.min(t,e.endIndex);let E=s.getEstimatedOffset(d,o,l);if(E<S)for(;E<=x&&d+1<=t;++d){const C=s.getEstimatedSize(d);E+=C}else if(E>=x)for(;d>c;--d){const C=s.getEstimatedSize(d-1);if(E-C<S)break;E-=C}for(f=o,u=l;f<c;++f){const C=s.getEstimatedSize(f);u+=C}for(;f>d;--f){const C=s.getEstimatedSize(f-1);u-=C}}i.startIndex=c,i.endIndex=d,i.anchorIndex=f,i.anchorOffset=u,i.scrollOffset=h}function TR(i,e){const t=e.getEstimatedOffset(i.anchorIndex),n=i.anchorOffset;i.anchorOffset=t,i.scrollOffset+=t-n}function DR(i,e){return i.startIndex<e.startIndex||i.endIndex>e.endIndex||i.viewportWidth!==0&&e.viewportWidth===0}class Pa extends D.O8{constructor(e){super(),this.element=document.createElement("div"),this.scrollContent=document.createElement("div"),this.header=document.createElement("div"),this.body=document.createElement("div"),this.topItems=document.createElement("div"),this.bottomItems=document.createElement("div"),this.renderedItems=[],this.renderGeneration=-1,this.listGeneration=-1,this.newRenderedItems=[],this.state=new CR,this.renderParams=new Kv,this.newRenderParams=new Kv,this.sizes=new xR,this.debouncedUpdateView=this.registerCancellable((0,je.t)(()=>this.updateView())),this.resizeObserver=new ResizeObserver(()=>this.updateView());const{selectedIndex:t}=e;t!==void 0&&(this.state.anchorIndex=t,this.state.anchorClientOffset=0);const n=this.source=e.source;this.sizes.itemSize.length=n.length;const{element:s,header:r,body:o,scrollContent:a,topItems:l,bottomItems:c}=this;this.resizeObserver.observe(s),this.registerDisposer(()=>this.resizeObserver.disconnect()),s.appendChild(a),s.style.overflowAnchor="none",a.appendChild(r),a.appendChild(o),r.style.position="sticky",r.style.zIndex="1",r.style.top="0",e.horizontalScroll?(a.style.width="min-content",a.style.minWidth="100%",r.style.width="min-content",r.style.minWidth="100%",c.style.width="min-content",c.style.minWidth="100%"):(a.style.width="100%",r.style.width="100%",c.style.width="100%"),o.appendChild(l),o.appendChild(c),l.style.width="min-content",l.style.position="relative",l.style.height="0",l.style.minWidth="100%",c.style.height="0",c.style.position="relative",s.addEventListener("scroll",()=>{const d=s.scrollTop;this.state.anchorClientOffset=this.renderParams.anchorOffset-d,this.renderParams.scrollOffset=d,this.debouncedUpdateView()}),n.changed!==void 0&&this.registerDisposer(n.changed.add(d=>{this.sizes.splice(d),this.state.splice(d),this.renderedItems.length=0,this.debouncedUpdateView()})),n.renderChanged!==void 0&&this.registerDisposer(n.renderChanged.add(this.debouncedUpdateView))}updateView(){const{element:e}=this,t=e.clientHeight-this.header.offsetHeight,n=e.clientWidth,{source:s,state:r,sizes:o}=this,a=s.length,{body:l,topItems:c,bottomItems:d}=this,{changed:u,renderChanged:h}=s;let f;for(;;){f=this.newRenderParams;const v=this.renderParams;ER(f,v,a,t,o,r),f.viewportWidth=n;let y;if(h!==void 0&&h.count!==this.renderGeneration||u!==void 0&&u.count!==this.listGeneration?(this.renderGeneration=h===void 0?-1:h.count,this.listGeneration=u===void 0?-1:u.count,y=!0,this.renderedItems.length=0):y=!1,!y&&!DR(f,v)){v.scrollOffset=f.scrollOffset,f=v;break}this.renderParams=f,this.newRenderParams=v;const S=this.renderedItems,x=this.newRenderedItems;x.length=0,this.renderedItems=x,this.newRenderedItems=S;const{source:b}=this,{render:E}=b,{startIndex:C,endIndex:k,anchorIndex:T}=f;function*L(_,R){for(let P=_;P<R;++P){let V=S[P];V===void 0&&(V=E.call(b,P)),x[P]=V,yield V}}Zt(c,L(C,T)),Zt(d,L(T,k));for(let _=C;_<k;++_){const V=x[_].getBoundingClientRect().height,$=o.itemSize[_];$!==void 0&&(o.totalKnownSize-=$,--o.numItemsInTotalKnownSize),o.itemSize[_]=V,o.totalKnownSize+=V,++o.numItemsInTotalKnownSize}}TR(f,o),r.anchorIndex=f.anchorIndex,r.anchorClientOffset=f.anchorOffset-f.scrollOffset;const m=o.getRangeSize(f.startIndex,f.anchorIndex),g=o.getEstimatedTotalSize()||0;l.style.height=`${g}px`,c.style.top=`${f.anchorOffset-m}px`,d.style.top=`${f.anchorOffset}px`,e.scrollTop=f.scrollOffset}getItemElement(e){return this.renderedItems[e]}forEachRenderedItem(e){const{startIndex:t,endIndex:n}=this.renderParams,{renderedItems:s}=this;for(let r=t;r<n;++r){const o=s[r];o!==void 0&&e(o,r)}}scrollToTop(){this.state.anchorIndex=0,this.state.anchorClientOffset=0,this.debouncedUpdateView()}scrollItemIntoView(e){const t=this.sizes.getEstimatedOffset(e),n=t+this.sizes.getEstimatedSize(e),s=this.element.scrollTop;if(t<s)this.state.anchorIndex=e,this.state.anchorClientOffset=0;else if(t>s&&n>s+this.element.offsetHeight)this.state.anchorIndex=e+1,this.state.anchorClientOffset=this.element.offsetHeight;else return;this.debouncedUpdateView()}disposed(){lt(this.element)}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Xv extends D.O8{constructor(){super(...arguments),this.changed=new j.IY,this.isLoadingChanged=new j.IY,this.states=[],this.relationships=[],this.loadingCount=0}get value(){return this.states}get isLoading(){return this.loadingCount!==0}markLoading(){return this.loadingCount++,()=>{--this.loadingCount===0&&this.isLoadingChanged.dispatch()}}sort(){this.states.sort((e,t)=>{const n=e.sourceIndex-t.sourceIndex;return n!==0?n:e.subsourceIndex-t.subsourceIndex})}updateRelationships(){const e=new Set;for(const t of this.states)for(const n of t.source.relationships)e.add(n);this.relationships=Array.from(e)}add(e){return this.states.push(e),this.sort(),this.updateRelationships(),this.changed.dispatch(),()=>{const t=this.states.indexOf(e);this.states.splice(t,1),this.updateRelationships(),this.changed.dispatch()}}}function IR(i,e){switch(e.type){case Je.AXIS_ALIGNED_BOUNDING_BOX:case Je.LINE:Ll(i,e.pointA,e.pointB),Kb(i,i,.5);break;case Je.POINT:i.set(e.point);break;case Je.ELLIPSOID:i.set(e.center);break}}function Zv(i,e,t){e.error===void 0&&i.setLayerPosition(e.modelTransform,t)}function ey(i,e,t){const{layerRank:n}=e,s=new Float32Array(n);Bt[i.type].visitGeometry(i,(r,o)=>{s.set(r);const a=new Float32Array(n);(o?we._U:we.vo)(a,e.chunkToLayerTransform,n+1,s,n),t(a,o)})}class ty extends Gt{constructor(e,t){super(),this.layer=e,this.displayState=t,this.previousSelectedState=void 0,this.previousHoverId=void 0,this.previousHoverAnnotationLayerState=void 0,this.virtualListSource={length:0,render:h=>this.render(h),changed:new j.HN},this.virtualList=new Pa({source:this.virtualListSource}),this.listElements=[],this.updated=!1,this.mutableControls=document.createElement("div"),this.headerRow=document.createElement("div"),this.attachedAnnotationStates=new Map,this.forceUpdateView=()=>{this.updated=!1,this.updateView()},this.globalDimensionIndices=[],this.localDimensionIndices=[],this.curCoordinateSpaceGeneration=-1,this.prevCoordinateSpaceGeneration=-1,this.columnWidths=[],this.gridTemplate="",this.selectedAnnotationState=(0,A.ol)((h,f)=>{if(h===void 0)return;const{layer:m}=this,g=h.layers.find(S=>S.layer===m)?.state;if(g===void 0)return;const{annotationId:v}=g;if(v===void 0)return;const y=this.annotationStates.states.find(S=>S.sourceIndex===g.annotationSourceIndex&&(g.annotationSubsource===void 0||S.subsourceId===g.annotationSubsource));if(y!==void 0)return{annotationId:v,annotationLayerState:y,pin:f}},this.layer.manager.root.selectionState,this.layer.manager.root.selectionState.pin),this.element.classList.add("neuroglancer-annotation-layer-view"),this.registerDisposer(this.visibility.changed.add(()=>this.updateView())),this.registerDisposer(this.annotationStates.changed.add(()=>this.updateAttachedAnnotationLayerStates())),this.headerRow.classList.add("neuroglancer-annotation-list-header");const n=document.createElement("div");n.className="neuroglancer-annotation-toolbox",e.initializeAnnotationLayerViewTab(this);const s=this.registerDisposer(new Ro(this.displayState.color));s.element.title="Change annotation display color",this.registerDisposer(new Xt((0,A.ol)(h=>h.match(/\bdefaultColor\b/)!==null,t.shaderControls.processedFragmentMain),s.element)),n.appendChild(s.element);const{mutableControls:r}=this,o=_e({text:Bt[Je.POINT].icon,title:"Annotate point",onClick:()=>{this.layer.tool.value=new ay(this.layer,{})}});r.appendChild(o);const a=_e({text:Bt[Je.AXIS_ALIGNED_BOUNDING_BOX].icon,title:"Annotate bounding box",onClick:()=>{this.layer.tool.value=new zd(this.layer,{})}});r.appendChild(a);const l=_e({text:Bt[Je.LINE].icon,title:"Annotate line",onClick:()=>{this.layer.tool.value=new Ma(this.layer,{})}});r.appendChild(l);const c=_e({text:Bt[Je.ELLIPSOID].icon,title:"Annotate ellipsoid",onClick:()=>{this.layer.tool.value=new dy(this.layer,{})}});r.appendChild(c),n.appendChild(r),this.element.appendChild(n),this.element.appendChild(this.headerRow);const{virtualList:d}=this;d.element.classList.add("neuroglancer-annotation-list"),this.element.appendChild(d.element),this.virtualList.element.addEventListener("mouseleave",()=>{this.displayState.hoverState.value=void 0});const u=uD();this.registerDisposer(new fn(this.virtualList.element,u)),this.virtualList.element.title=u.describe(),this.registerDisposer(this.displayState.hoverState.changed.add(()=>this.updateHoverView())),this.registerDisposer(this.selectedAnnotationState.changed.add(()=>this.updateSelectionView())),this.registerDisposer(this.layer.localCoordinateSpace.changed.add(()=>{this.updateCoordinateSpace(),this.updateView()})),this.registerDisposer(this.layer.manager.root.coordinateSpace.changed.add(()=>{this.updateCoordinateSpace(),this.updateView()})),this.updateCoordinateSpace(),this.updateAttachedAnnotationLayerStates(),this.updateSelectionView()}get annotationStates(){return this.layer.annotationStates}updateAttachedAnnotationLayerStates(){const e=this.annotationStates.states,{attachedAnnotationStates:t}=this,n=new Map;for(const[s,r]of t)e.includes(s)||(t.delete(s),r.refCounted.dispose());for(const s of e){const r=t.get(s);if(r!==void 0){n.set(s,r);continue}const o=s.source,a=new D.O8;o instanceof ss&&(a.registerDisposer(o.childAdded.add(l=>this.addAnnotationElement(l,s))),a.registerDisposer(o.childUpdated.add(l=>this.updateAnnotationElement(l,s))),a.registerDisposer(o.childDeleted.add(l=>this.deleteAnnotationElement(l,s)))),a.registerDisposer(s.transform.changed.add(this.forceUpdateView)),n.set(s,{refCounted:a,annotations:[],idToIndex:new Map,listOffset:0})}this.attachedAnnotationStates=n,t.clear(),this.updateCoordinateSpace(),this.forceUpdateView()}updateCoordinateSpace(){const e=this.layer.localCoordinateSpace.value,t=this.layer.manager.root.coordinateSpace.value,n=[],s=[];for(let r=0,o=t.rank;r<o;++r)this.annotationStates.states.some(a=>{const l=a.transform.value;return l.error!==void 0?!1:l.globalToRenderLayerDimensions[r]!==-1})&&n.push(r);for(let r=0,o=e.rank;r<o;++r)this.annotationStates.states.some(a=>{const l=a.transform.value;return l.error!==void 0?!1:l.localToRenderLayerDimensions[r]!==-1})&&s.push(r);(!(0,z.r1)(n,this.globalDimensionIndices)||!(0,z.r1)(s,this.localDimensionIndices))&&(this.localDimensionIndices=s,this.globalDimensionIndices=n,++this.curCoordinateSpaceGeneration)}getRenderedAnnotationListElement(e,t,n=!1){const s=this.attachedAnnotationStates.get(e);if(s===void 0)return;const r=s.idToIndex.get(t);if(r===void 0)return;const o=s.listOffset+r;return n&&this.virtualList.scrollItemIntoView(r),this.virtualList.getItemElement(o)}clearSelectionClass(){const{previousSelectedState:e}=this;if(e===void 0)return;this.previousSelectedState=void 0;const t=this.getRenderedAnnotationListElement(e.annotationLayerState,e.annotationId);t!==void 0&&t.classList.remove("neuroglancer-annotation-selected")}clearHoverClass(){const{previousHoverId:e,previousHoverAnnotationLayerState:t}=this;if(t!==void 0){this.previousHoverAnnotationLayerState=void 0,this.previousHoverId=void 0;const n=this.getRenderedAnnotationListElement(t,e);n!==void 0&&n.classList.remove("neuroglancer-annotation-hover")}}updateSelectionView(){const e=this.selectedAnnotationState.value,{previousSelectedState:t}=this;if(t===e||t!==void 0&&e!==void 0&&t.annotationId===e.annotationId&&t.annotationLayerState===e.annotationLayerState&&t.pin===e.pin||(this.clearSelectionClass(),this.previousSelectedState=e,e===void 0))return;const n=this.getRenderedAnnotationListElement(e.annotationLayerState,e.annotationId,e.pin);n!==void 0&&n.classList.add("neuroglancer-annotation-selected")}updateHoverView(){const e=this.displayState.hoverState.value;let t,n;e!==void 0&&(t=e.id,n=e.annotationLayerState);const{previousHoverId:s,previousHoverAnnotationLayerState:r}=this;if(t===s&&n===r||(this.clearHoverClass(),this.previousHoverId=t,this.previousHoverAnnotationLayerState=n,t===void 0))return;const o=this.getRenderedAnnotationListElement(n,t);o!==void 0&&o.classList.add("neuroglancer-annotation-hover")}render(e){const{annotation:t,state:n}=this.listElements[e];return this.makeAnnotationListElement(t,n)}setColumnWidth(e,t){t+=2;const{columnWidths:n}=this;n[e]>t||(n[e]=t,this.element.style.setProperty(`--neuroglancer-column-${e}-width`,`${t}ch`))}updateView(){if(!this.visible)return;if(this.curCoordinateSpaceGeneration!==this.prevCoordinateSpaceGeneration){this.updated=!1;const{columnWidths:s}=this;s.length=0;const{headerRow:r}=this,o=document.createElement("div");o.style.gridColumn="symbol";const a=document.createElement("div");a.style.gridColumn="delete",Ae(r),r.appendChild(o);let l=0,c="[symbol] 2ch";const d=(f,m)=>{const g=document.createElement("div");g.classList.add("neuroglancer-annotations-view-dimension");const v=document.createElement("span");v.classList.add("neuroglancer-annotations-view-dimension-name"),v.textContent=f.names[m];const y=document.createElement("scale");y.classList.add("neuroglancer-annotations-view-dimension-scale"),y.textContent=Ci(f.scales[m],f.units[m],{precision:2}),g.appendChild(v),g.appendChild(y),g.style.gridColumn=`dim ${l+1}`,this.setColumnWidth(l,y.textContent.length+v.textContent.length+3),c+=` [dim] var(--neuroglancer-column-${l}-width)`,++l,r.appendChild(g)},u=this.layer.manager.root.coordinateSpace.value;for(const f of this.globalDimensionIndices)d(u,f);const h=this.layer.localCoordinateSpace.value;for(const f of this.localDimensionIndices)d(h,f);r.appendChild(a),c+=" [delete] 2ch",this.gridTemplate=c,r.style.gridTemplateColumns=c,this.prevCoordinateSpaceGeneration=this.curCoordinateSpaceGeneration}if(this.updated)return;let e=!1;const{listElements:t}=this;t.length=0;for(const[s,r]of this.attachedAnnotationStates){if(s.source.readonly||(e=!0),s.chunkTransform.value.error!==void 0)continue;const{source:o}=s,a=Array.from(o);r.annotations=a;const{idToIndex:l}=r;l.clear();for(let c=0,d=a.length;c<d;++c)l.set(a[c].id,c);for(const c of a)t.push({state:s,annotation:c})}const n=this.virtualListSource.length;this.updateListLength(),this.virtualListSource.changed.dispatch([{retainCount:0,deleteCount:n,insertCount:t.length}]),this.mutableControls.style.display=e?"contents":"none",this.resetOnUpdate()}updateListLength(){let e=0;for(const t of this.attachedAnnotationStates.values())t.listOffset=e,e+=t.annotations.length;this.virtualListSource.length=e}addAnnotationElement(e,t){if(!this.visible){this.updated=!1;return}if(!this.updated){this.updateView();return}const n=this.attachedAnnotationStates.get(t);if(n!==void 0){const s=n.annotations.length;n.annotations.push(e),n.idToIndex.set(e.id,s);const r=n.listOffset+s;this.listElements.splice(r,0,{state:t,annotation:e}),this.updateListLength(),this.virtualListSource.changed.dispatch([{retainCount:r,deleteCount:0,insertCount:1}])}this.resetOnUpdate()}updateAnnotationElement(e,t){if(!this.visible){this.updated=!1;return}if(!this.updated){this.updateView();return}const n=this.attachedAnnotationStates.get(t);if(n!==void 0){const s=n.idToIndex.get(e.id);if(s!==void 0){const r=n.listOffset+s;n.annotations[s]=e,this.listElements[r].annotation=e,this.virtualListSource.changed.dispatch([{retainCount:r,deleteCount:1,insertCount:1}])}}this.resetOnUpdate()}deleteAnnotationElement(e,t){if(!this.visible){this.updated=!1;return}if(!this.updated){this.updateView();return}const n=this.attachedAnnotationStates.get(t);if(n!==void 0){const{idToIndex:s}=n,r=s.get(e);if(r!==void 0){const o=n.listOffset+r,{annotations:a}=n;a.splice(r,1),s.delete(e);for(let l=r,c=a.length;l<c;++l)s.set(a[l].id,l);this.listElements.splice(o,1),this.updateListLength(),this.virtualListSource.changed.dispatch([{retainCount:o,deleteCount:1,insertCount:0}])}}this.resetOnUpdate()}resetOnUpdate(){this.clearHoverClass(),this.clearSelectionClass(),this.updated=!0,this.updateHoverView(),this.updateSelectionView()}makeAnnotationListElement(e,t){const n=t.chunkTransform.value,s=document.createElement("div");s.classList.add("neuroglancer-annotation-list-entry"),s.dataset.color=t.displayState.color.toString(),s.style.gridTemplateColumns=this.gridTemplate;const r=document.createElement("div");r.className="neuroglancer-annotation-icon",r.textContent=Bt[e.type].icon,s.appendChild(r);let o;const a=()=>{t.source.readonly||o===void 0&&(o=Yn({title:"Delete annotation",onClick:d=>{d.stopPropagation(),d.preventDefault();const u=t.source.getReference(e.id);try{t.source.delete(u)}finally{u.dispose()}}}),o.classList.add("neuroglancer-annotation-list-entry-delete"),s.appendChild(o))};let l=0;if(ey(e,n,(d,u)=>{++l;const h=document.createElement("div");h.className="neuroglancer-annotation-position",s.appendChild(h);let f=0;const m=(g,v)=>{for(const y of g){const S=v[y];if(S!==-1){const x=Math.floor(d[S]),b=document.createElement("div"),E=x.toString();b.textContent=E,b.classList.add("neuroglancer-annotation-coordinate"),b.style.gridColumn=`dim ${f+1}`,this.setColumnWidth(f,E.length),h.appendChild(b)}++f}};m(this.globalDimensionIndices,n.modelTransform.globalToRenderLayerDimensions),m(this.localDimensionIndices,n.modelTransform.localToRenderLayerDimensions),a()}),e.description){++l;const d=document.createElement("div");d.classList.add("neuroglancer-annotation-description"),d.textContent=e.description,s.appendChild(d)}r.style.gridRow=`span ${l}`,o!==void 0&&(o.style.gridRow=`span ${l}`),s.addEventListener("mouseenter",()=>{this.displayState.hoverState.value={id:e.id,partIndex:0,annotationLayerState:t},this.layer.selectAnnotation(t,e.id,!1)}),s.addEventListener("action:select-position",d=>{d.stopPropagation(),this.layer.selectAnnotation(t,e.id,"toggle")}),s.addEventListener("action:pin-annotation",d=>{d.stopPropagation(),this.layer.selectAnnotation(t,e.id,!0)}),s.addEventListener("action:move-to-annotation",d=>{d.stopPropagation(),d.preventDefault();const{layerRank:u}=n,h=new Float32Array(u),f=new Float32Array(u);IR(h,e),we.vo(f,n.chunkToLayerTransform,u+1,h,u),Zv(this.layer,n,f)});const c=this.selectedAnnotationState.value;return c!==void 0&&c.annotationLayerState===t&&c.annotationId===e.id&&s.classList.add("neuroglancer-annotation-selected"),s}}class RR extends Gt{constructor(e){super(),this.layer=e,this.layerView=this.registerDisposer(new ty(this.layer,this.layer.annotationDisplayState));const{element:t}=this;t.classList.add("neuroglancer-annotations-tab"),t.appendChild(this.layerView.element)}}function Aa(i,e=!1){const t=[],{relationships:n}=i.source,{relationshipStates:s}=i.displayState;for(let r=0,o=n.length;r<o;++r){const a=s.get(n[r]).segmentationState.value;if(a!=null&&a.segmentSelectionState.hasSelectedSegment){t[r]=[a.segmentSelectionState.selectedSegment.clone()],e&&(t[r]=[...t[r],a.segmentSelectionState.baseSelectedSegment.clone()]);continue}t[r]=[]}return t}class ny extends Sf{constructor(e,t){super(e)}get annotationLayer(){for(const e of this.layer.annotationStates.states)if(!e.source.readonly)return e}}const iy="annotatePoint",sy="annotateLine",ry="annotateBoundingBox",oy="annotateSphere";class ay extends ny{trigger(e){const{annotationLayer:t}=this;if(t!==void 0&&e.updateUnconditionally()){const n=Ur(e,t);if(n===void 0)return;const s={id:"",description:"",relatedSegments:Aa(t),point:n,type:Je.POINT,properties:t.source.properties.map(o=>o.default)},r=t.source.add(s,!0);this.layer.selectAnnotation(t,r.id,!0),r.dispose()}}get description(){return"annotate point"}toJSON(){return iy}}function Ur(i,e){const t=e.chunkTransform.value;if(t.error!==void 0)return;const n=new Float32Array(t.modelTransform.unpaddedRank);if(as(n,i.unsnappedPosition,e.localPosition.value,t.layerRank,t.combinedGlobalLocalToChunkTransform))return n}class ly extends ny{constructor(){super(...arguments),this.inProgressAnnotation=new A.B0(void 0)}trigger(e){const{annotationLayer:t,inProgressAnnotation:n}=this;if(t!==void 0&&e.updateUnconditionally()){const s=()=>{const r=n.value,o=r.reference,a=this.getUpdatedAnnotation(o.value,e,t);JSON.stringify(Dl(a,t.source))!==JSON.stringify(Dl(o.value,t.source))&&(r.annotationLayer.source.update(o,a),this.layer.selectAnnotation(t,o.id,!0))};if(n.value===void 0){const r=t.source.add(this.getInitialAnnotation(e,t),!1);this.layer.selectAnnotation(t,r.id,!0);const o=e.changed.add(s),a=()=>{o(),r.dispose()};n.value={annotationLayer:t,reference:r,disposer:a}}else{s();const r=n.value;r.annotationLayer.source.commit(r.reference),r.disposer(),n.value=void 0}}}disposed(){this.deactivate(),super.disposed()}deactivate(){const e=this.inProgressAnnotation.value;e!==void 0&&(e.annotationLayer.source.delete(e.reference),e.disposer(),this.inProgressAnnotation.value=void 0)}}class cy extends ly{getInitialAnnotation(e,t){const n=Ur(e,t);return{id:"",type:this.annotationType,description:"",pointA:n,pointB:n,properties:t.source.properties.map(s=>s.default)}}getUpdatedAnnotation(e,t,n){const s=Ur(t,n);return s===void 0?e:{...e,pointB:s}}}class zd extends cy{get description(){return"annotate bounding box"}getUpdatedAnnotation(e,t,n){const s=super.getUpdatedAnnotation(e,t,n),{pointA:r,pointB:o}=s,a=r.length;for(let l=0;l<a;++l)r[l]===o[l]&&(o[l]+=1);return s}toJSON(){return ry}}zd.prototype.annotationType=Je.AXIS_ALIGNED_BOUNDING_BOX;class Ma extends cy{constructor(){super(...arguments),this.getBaseSegment=!1}get description(){return"annotate line"}getInitialAnnotation(e,t){const n=super.getInitialAnnotation(e,t);return this.initialRelationships=n.relatedSegments=Aa(t,this.getBaseSegment),n}getUpdatedAnnotation(e,t,n){const s=super.getUpdatedAnnotation(e,t,n),r=this.initialRelationships,o=Aa(n,this.getBaseSegment);return r===void 0?s.relatedSegments=o:s.relatedSegments=Array.from(o,(a,l)=>{const c=r[l];return a=a.filter(d=>c.findIndex(u=>M.R.equal(d,u))===-1),[...c,...a]}),s}toJSON(){return sy}}Ma.prototype.annotationType=Je.LINE;class dy extends ly{getInitialAnnotation(e,t){const n=Ur(e,t);return{type:Je.ELLIPSOID,id:"",description:"",segments:Aa(t),center:n,radii:w.eR.fromValues(0,0,0),properties:t.source.properties.map(s=>s.default)}}getUpdatedAnnotation(e,t,n){const s=Ur(t,n);if(s===void 0)return e;const r=e.center,o=r.length;for(let a=0;a<o;++a)s[a]=Math.abs(r[a]-s[a]);return{...e,radii:s}}get description(){return"annotate ellipsoid"}toJSON(){return oy}}vr(iy,(i,e)=>new ay(i,e)),vr(ry,(i,e)=>new zd(i,e)),vr(sy,(i,e)=>new Ma(i,e)),vr(oy,(i,e)=>new dy(i,e));const kR=Pe.fromObject({enter:{action:"commit"},escape:{action:"cancel"}});function LR(i,e,t,n){return new zt(t,(s,r,o)=>{const a=document.createElement("div");a.classList.add("neuroglancer-related-segment-list"),s!=null&&o.registerDisposer(Vr(s,a));const l=document.createElement("div");l.classList.add("neuroglancer-related-segment-list-header");const c=zn({title:"Copy segment IDs",onClick:()=>{ai(e.map(m=>m.toString()).join(", "))}});l.appendChild(c);let d;if(s!=null&&(d=document.createElement("input"),d.type="checkbox",d.addEventListener("change",()=>{const{visibleSegments:m}=s.segmentationGroupState.value,g=e.some(v=>!m.has(v));for(const v of e)m.set(v,g)}),l.appendChild(d)),n!==void 0){const m=Yn({title:"Remove all IDs",onClick:()=>{n([])}});l.appendChild(m)}const u=document.createElement("span");if(u.classList.add("neuroglancer-related-segment-list-title"),u.textContent=i,l.appendChild(u),n!==void 0){const m=Qv({title:"Add related segment ID",onClick:()=>{const g=new D.O8,v=o.registerDisposer((0,D.K9)(g)),y=document.createElement("div");y.classList.add("neuroglancer-segment-list-entry"),y.classList.add("neuroglancer-segment-list-entry-new");const S=zn({});if(S.classList.add("neuroglancer-segment-list-entry-copy"),y.appendChild(S),s!=null){const k=document.createElement("input");k.classList.add("neuroglancer-segment-list-entry-visible-checkbox"),k.type="checkbox",y.appendChild(k)}const x=Yn({title:"Cancel adding new segment ID",onClick:()=>{v()}});x.classList.add("neuroglancer-segment-list-entry-delete"),y.appendChild(x);const b=document.createElement("input");b.autocomplete="off",b.spellcheck=!1,b.classList.add("neuroglancer-segment-list-entry-id");const E=g.registerDisposer(new mn(b,kR));E.allShortcutsAreGlobal=!0;const C=()=>{const k=new M.R;if(k.tryParseString(b.value))return b.dataset.valid="true",k;b.dataset.valid="false"};C(),b.addEventListener("input",()=>{C()}),b.addEventListener("blur",()=>{const k=C();k!==void 0&&n([...e,k]),v()}),X(b,"cancel",v),X(b,"commit",()=>{const k=C();k!==void 0&&n([...e,k]),v()}),y.appendChild(b),a.appendChild(y),b.focus(),g.registerDisposer(()=>{b.value="",y.remove()})}});l.appendChild(m)}a.appendChild(l);const h=[],f=Os.make(s??void 0,!1);for(const m of e){const g=f.get(m);if(h.push(g),n!==void 0){const v=Yn({title:"Remove ID",onClick:y=>{n(e.filter(S=>!M.R.equal(S,m))),y.stopPropagation()}});v.classList.add("neuroglancer-segment-list-entry-delete"),g.children[0].appendChild(v)}a.appendChild(g)}if(s!=null){const m=o.registerCancellable((0,je.t)(()=>{const{visibleSegments:g}=s.segmentationGroupState.value;let v=0;for(const y of e)g.has(y)&&++v;for(const y of h)f.update(y);d.checked=v===e.length&&v>0,d.indeterminate=v>0&&v<e.length}));m(),m.flush(),Vs(s,o,m),o.registerDisposer(s.segmentationGroupState.changed.add(m))}r.appendChild(a)})}const uy="annotationColor";function Wd(i){class e extends i{constructor(...n){super(...n),this.annotationStates=this.registerDisposer(new Xv),this.annotationDisplayState=new $f,this.annotationCrossSectionRenderScaleHistogram=new Rs,this.annotationCrossSectionRenderScaleTarget=_i(8),this.annotationProjectionRenderScaleHistogram=new Rs,this.annotationProjectionRenderScaleTarget=_i(8),this.annotationDisplayState.color.changed.add(this.specificationChanged.dispatch),this.annotationDisplayState.shader.changed.add(this.specificationChanged.dispatch),this.annotationDisplayState.shaderControls.changed.add(this.specificationChanged.dispatch),this.tabs.add("annotations",{label:"Annotations",order:10,getter:()=>new RR(this)});let s;const r=()=>{const a=this.isReady;a&&s!==void 0?(s(),s=void 0):!a&&s===void 0&&(s=this.annotationStates.markLoading())};this.readyStateChanged.add(r),r();const{mouseState:o}=this.manager.layerSelectedValues;this.registerDisposer(o.changed.add(()=>{if(o.active){const{pickedAnnotationLayer:a}=o;if(a!==void 0&&this.annotationStates.states.includes(a)){const l=this.annotationDisplayState.hoverState.value;(l===void 0||l.id!==o.pickedAnnotationId||l.partIndex!==o.pickedOffset||l.annotationLayerState!==a)&&(this.annotationDisplayState.hoverState.value={id:o.pickedAnnotationId,partIndex:o.pickedOffset,annotationLayerState:a});return}}this.annotationDisplayState.hoverState.value=void 0}))}initializeAnnotationLayerViewTab(n){}restoreState(n){super.restoreState(n),this.annotationDisplayState.color.restoreState(n[uy])}captureSelectionState(n,s){super.captureSelectionState(n,s);const r=s.pickedAnnotationLayer;r===void 0||!this.annotationStates.states.includes(r)||(n.annotationId=s.pickedAnnotationId,n.annotationType=s.pickedAnnotationType,n.annotationBuffer=new Uint8Array(s.pickedAnnotationBuffer,s.pickedAnnotationBufferBaseOffset),n.annotationIndex=s.pickedAnnotationIndex,n.annotationCount=s.pickedAnnotationCount,n.annotationPartIndex=s.pickedOffset,n.annotationSourceIndex=r.sourceIndex,n.annotationSubsource=r.subsourceId)}displayAnnotationState(n,s,r){if(n.annotationId===void 0)return!1;const o=this.annotationStates.states.find(l=>l.sourceIndex===n.annotationSourceIndex&&l.subsubsourceId===n.annotationSubsubsourceId&&(n.annotationSubsource===void 0||l.subsourceId===n.annotationSubsource));if(o===void 0)return!1;const a=r.registerDisposer(o.source.getReference(n.annotationId));return s.appendChild(r.registerDisposer(new zt(r.registerDisposer(new A.wP(()=>({annotation:a,chunkTransform:o.chunkTransform}))),({annotation:l,chunkTransform:c},d,u)=>{let h;if(l==null)if(n.annotationType!==void 0&&n.annotationBuffer!==void 0){const f=Bt[n.annotationType],m=o.source.rank,g=f.serializedBytes(m),v=n.annotationBuffer.byteOffset,y=new DataView(n.annotationBuffer.buffer),S=F.LITTLE===te,{properties:x}=o.source,b=new yh(m,g,x),E=n.annotationIndex,C=n.annotationCount;l=f.deserialize(y,v+b.propertyGroupBytes[0]*E,S,m,n.annotationId),b.deserialize(y,v,E,C,S,l.properties=new Array(x.length)),o.source.hasNonSerializedProperties()&&(h="Loading...")}else h=l===null?"Annotation not found":"Loading...";if(l!=null){const f=c.error===void 0?c.layerRank:0,m=document.createElement("div");m.classList.add("neuroglancer-selected-annotation-details-position-grid"),m.style.gridTemplateColumns=`[icon] 0fr [copy] 0fr repeat(${f}, [dim] 0fr [coord] 0fr) [move] 0fr [delete] 0fr`,d.appendChild(m);const g=Bt[l.type],v=document.createElement("div");if(v.className="neuroglancer-selected-annotation-details-icon",v.textContent=g.icon,m.appendChild(v),f!==0){const{layerDimensionNames:T}=c.modelTransform;for(let L=0;L<f;++L){const _=document.createElement("div");_.classList.add("neuroglancer-selected-annotation-details-position-dim"),_.textContent=T[L],_.style.gridColumn=`dim ${L+1}`,m.appendChild(_)}ey(l,c,(L,_)=>{const R=zn({title:"Copy position",onClick:()=>{ai(L.map(P=>Math.floor(P)).join(", "))}});R.style.gridColumn="copy",m.appendChild(R);for(let P=0;P<f;++P){const V=document.createElement("div");V.classList.add("neuroglancer-selected-annotation-details-position-coord"),V.style.gridColumn=`coord ${P+1}`,V.textContent=Math.floor(L[P]).toString(),m.appendChild(V)}if(!_){const P=Dm({title:"Move to position",onClick:()=>{Zv(this,c,L)}});P.style.gridColumn="move",m.appendChild(P)}})}if(!o.source.readonly){const T=Yn({title:"Delete annotation",onClick:()=>{o.source.delete(a)}});T.classList.add("neuroglancer-selected-annotation-details-delete"),m.appendChild(T)}const{relationships:y,properties:S}=o.source,x=o.source.readonly,b=document.createElement("label");b.classList.add("neuroglancer-annotation-property");const E=document.createElement("span");E.classList.add("neuroglancer-annotation-property-label"),E.textContent="ID",b.appendChild(E);const C=document.createElement("span");C.classList.add("neuroglancer-annotation-property-value"),C.textContent=a.id,b.appendChild(C),d.appendChild(b);for(let T=0,L=S.length;T<L;++T){const _=S[T],R=document.createElement("label");R.classList.add("neuroglancer-annotation-property");const P=document.createElement("span");P.classList.add("neuroglancer-annotation-property-label"),P.textContent=_.identifier,R.appendChild(P);const{description:V}=_;V!==void 0&&(R.title=V);const $=l.properties[T],Q=document.createElement("span");switch(Q.classList.add("neuroglancer-annotation-property-value"),_.type){case"rgb":{const K=Ze($),ee=ze(K);Q.textContent=ee,Q.style.backgroundColor=ee,Q.style.color=Ve(K)?"white":"black";break}case"rgba":{const K=Ze($);Q.textContent=ze(Pt($)),Q.style.backgroundColor=ze(Ze($)),Q.style.color=Ve(K)?"white":"black";break}default:Q.textContent=Sh(_,$);break}R.appendChild(Q),d.appendChild(R)}const{relatedSegments:k}=l;for(let T=0,L=y.length;T<L;++T){const _=k===void 0?[]:k[T];if(_.length===0&&x)continue;const R=T,P=y[T];d.appendChild(u.registerDisposer(LR(P,_,o.displayState.relationshipStates.get(P).segmentationState,x?void 0:V=>{const $=a.value;if($==null)return;let{relatedSegments:Q}=$;Q===void 0?Q=o.source.relationships.map(()=>[]):Q=Q.slice(),Q[R]=V;const K={...$,relatedSegments:Q};o.source.update(a,K),o.source.commit(a)})).element)}if(!o.source.readonly||l.description)if(o.source.readonly){const T=document.createElement("div");T.className="neuroglancer-annotation-details-description",T.textContent=l.description||"",d.appendChild(T)}else{const T=document.createElement("textarea");T.value=l.description||"",T.rows=3,T.className="neuroglancer-annotation-details-description",T.placeholder="Description",T.addEventListener("change",()=>{const L=T.value;o.source.update(a,{...l,description:L||void 0}),o.source.commit(a)}),d.appendChild(T)}}if(h!==void 0){const f=document.createElement("div");f.classList.add("neuroglancer-selection-annotation-status"),f.textContent=h,d.appendChild(f)}})).element),!0}displaySelectionState(n,s,r){let o=this.displayAnnotationState(n,s,r);return super.displaySelectionState(n,s,r)&&(o=!0),o}addLocalAnnotations(n,s,r){const{subsourceEntry:o}=n,a=new Uo({localPosition:this.localPosition,transform:n.getRenderLayerTransform(),source:s,displayState:this.annotationDisplayState,dataSource:n.loadedDataSource.layerDataSource,subsourceIndex:n.subsourceIndex,subsourceId:o.id,role:r});this.addAnnotationLayerState(a,n)}addStaticAnnotations(n){const{subsourceEntry:s}=n,{staticAnnotations:r}=s.subsource;return r===void 0?!1:(n.activate(()=>{this.addLocalAnnotations(n,r,si.DEFAULT_ANNOTATION)}),!0)}addAnnotationLayerState(n,s){const r=s.activated;r.registerDisposer(this.annotationStates.add(n));const o=new mR(this.manager.chunkManager,n.addRef());if(o.source instanceof Tr){const a=new SR({annotationLayer:o.addRef(),renderScaleTarget:this.annotationCrossSectionRenderScaleTarget,renderScaleHistogram:this.annotationCrossSectionRenderScaleHistogram});r.registerDisposer(s.messages.addChild(a.messages));const l=new yR({annotationLayer:o.addRef(),renderScaleTarget:this.annotationProjectionRenderScaleTarget,renderScaleHistogram:this.annotationProjectionRenderScaleHistogram});r.registerDisposer(s.messages.addChild(l.messages)),r.registerDisposer((0,A.no)((c,d)=>{d&&(c.registerDisposer(this.addRenderLayer(a.addRef())),c.registerDisposer(this.addRenderLayer(l.addRef())))},this.annotationDisplayState.displayUnfiltered))}{const a=new bR(o,this.annotationCrossSectionRenderScaleHistogram);r.registerDisposer(this.addRenderLayer(a)),r.registerDisposer(s.messages.addChild(a.messages))}{const a=new vR(o.addRef(),this.annotationProjectionRenderScaleHistogram);r.registerDisposer(this.addRenderLayer(a)),r.registerDisposer(s.messages.addChild(a.messages))}}selectAnnotation(n,s,r){this.manager.root.selectionState.captureSingleLayerState(this,o=>(o.annotationId=s,o.annotationSourceIndex=n.sourceIndex,o.annotationSubsource=n.subsourceId,o.annotationSubsubsourceId=n.subsubsourceId,!0),r)}toJSON(){const n=super.toJSON();return n[uy]=this.annotationDisplayState.color.toJSON(),n}}return e}/**
 * /**
 * @license
 * This work is a derivative of the Google Neuroglancer project,
 * Copyright 2016 Google Inc.
 * The Derivative Work is covered by
 * Copyright 2021 Howard Hughes Medical Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Hd="selectSegments",Jd="mousedown0",PR=Pe.fromObject({[`at:alt?+shift?+${Jd}`]:"drag-select-segments"});var AR=(i=>(i[i.IDLE=0]="IDLE",i[i.SELECT=1]="SELECT",i[i.DESELECT=2]="DESELECT",i))(AR||{});class MR extends vs{toJSON(){return Hd}activate(e){const{layer:t}=this,{body:n,header:s}=Ss(e);let r=0,o=!1;e.bindInputEventMap(PR);const a=()=>Lo.value&Kp.ALT?2:1,l=h=>{r!==h&&(r=h,o=!1,c())},c=()=>{Ae(n);const h=document.createElement("span");switch(r){case 0:s.textContent="Select/Deselect segments",h.textContent=`${Jd} to select segments; alt+${Jd} to deselect segments.`;break;case 1:case 2:s.textContent=`${r===1?"Select":"Deselect"} segments`,h.textContent=`Drag to ${r===1?"select":"deselect"} segments (${t.displayState.segmentationGroupState.value.visibleSegments.size} selected).`}n.appendChild(h)};c();const d=()=>{if(r===0)return;const{segmentSelectionState:h}=t.displayState;if(h.hasSelectedSegment){const f=h.selectedSegment,{selectedSegments:m,visibleSegments:g}=t.displayState.segmentationGroupState.value;switch(r){case 1:m.add(f),g.add(f);break;case 2:m.delete(f);break}}};e.registerDisposer(t.displayState.segmentSelectionState.changed.add(()=>{o&&d()})),e.registerDisposer(t.displayState.segmentationGroupState.value.visibleSegments.changed.add(c)),e.registerDisposer(Lo.changed.add(()=>{r!==0&&l(a())}));const u=(h,f)=>{h.stopPropagation(),l(f),d();const m=h.detail.screenX,g=h.detail.screenY;$t(h.detail,(v,y,S)=>{if(!o){const x=v.screenX-m,b=v.screenY-g;x*x+b*b>25&&(d(),o=!0)}},v=>{o=!1,l(0)})};e.bindAction("drag-select-segments",h=>u(h,a()))}get description(){return"select"}}function NR(i){Rn(i,Hd,e=>new MR(e))}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const jd="mergeSegments",Yd="splitSegments",OR=Pe.fromObject({"at:shift?+mousedown0":{action:"merge-segments"},"at:shift?+mousedown2":{action:"set-anchor"}}),VR=Pe.fromObject({"at:shift?+mousedown0":{action:"split-segments"},"at:shift?+alt+mousedown0":{action:"split-and-select-segments"},"at:shift?+mousedown2":{action:"set-anchor"}});class _R extends vs{constructor(e){super(e),this.lastAnchorBaseSegment=new A.B0(void 0);const t=()=>{const n=e.anchorSegment.value;if(n===void 0)return;const{segmentSelectionState:s}=e.displayState;if(!s.hasSelectedSegment)return;const{segmentEquivalences:r}=e.displayState.segmentationGroupState.value,o=r.get(n);if(!M.R.equal(s.selectedSegment,o))return;const a=s.baseSelectedSegment,l=(0,Tt.YR)(a),c=r.disjointSets.visibleSegmentEquivalencePolicy.value;c&Tt.y6.NONREPRESENTATIVE_EXCLUDED&&l||c&Tt.y6.REPRESENTATIVE_EXCLUDED&&!l||(this.lastAnchorBaseSegment.value=a.clone())};this.registerDisposer(e.displayState.segmentSelectionState.changed.add(t)),this.registerDisposer(e.anchorSegment.changed.add(t))}toJSON(){return jd}activate(e){const t=this.layer.displayState.segmentationGroupState.value,n=()=>{const c=this.layer.anchorSegment.value,d=this.lastAnchorBaseSegment.value;if(c===void 0)return{anchorSegment:void 0,error:"Select anchor segment for merge"};const u=t.segmentEquivalences.get(c);return t.visibleSegments.has(u)?d===void 0||!M.R.equal(t.segmentEquivalences.get(d),u)?{anchorSegment:c,error:"Hover over base segment within anchor segment that is closest to merge location"}:{anchorSegment:d,error:void 0}:{anchorSegment:c,error:"Anchor segment must be in visible set"}},s=()=>{const{anchorSegment:c,error:d}=n();if(c===void 0||d!==void 0)return{anchorSegment:c,error:d,otherSegment:void 0,anchorSegmentValid:!1};const{displayState:u}=this.layer,h=u.segmentSelectionState.baseValue;return h===void 0||M.R.equal(u.segmentSelectionState.selectedSegment,t.segmentEquivalences.get(c))?{anchorSegment:c,otherSegment:void 0,error:"Hover over segment to merge",anchorSegmentValid:!0}:{anchorSegment:c,otherSegment:h,error:void 0,anchorSegmentValid:!0}},{body:r,header:o}=Ss(e);o.textContent="Merge segments",r.classList.add("neuroglancer-merge-segments-status"),e.bindInputEventMap(OR),e.registerDisposer(()=>{Or(t)});const a=()=>{Ae(r);const{displayState:c}=this.layer,{anchorSegment:d,otherSegment:u,anchorSegmentValid:h,error:f}=s(),m=y=>{const S=yd(this.layer.displayState,y);return S.classList.add("neuroglancer-segment-list-entry-double-line"),S};if(d!==void 0&&r.appendChild(m(ji(c,d))),f!==void 0){const y=document.createElement("span");y.textContent=f,r.appendChild(y)}if(u!==void 0){const y=document.createElement("span");y.textContent=" merge ",r.appendChild(y),r.appendChild(m(ji(c,u)))}const{segmentEquivalences:g}=t;if(!h){Or(t);return}t.useTemporaryVisibleSegments.value=!0;const v=t.temporaryVisibleSegments;v.clear(),v.add(g.get(d)),u!==void 0&&v.add(g.get(u))};a(),e.registerDisposer(Vr(this.layer.displayState,r));const l=e.registerCancellable((0,je.t)(a));Vs(this.layer.displayState,e,l),e.registerDisposer(this.layer.anchorSegment.changed.add(l)),e.registerDisposer(this.lastAnchorBaseSegment.changed.add(l)),e.bindAction("merge-segments",c=>{c.stopPropagation(),(async()=>{const{graph:{value:d}}=t;if(d===void 0)return;const{anchorSegment:u,otherSegment:h,error:f}=s();if(!(u===void 0||h===void 0||f!==void 0))try{await d.merge(u,h),Se.showTemporaryMessage("Merge performed")}catch(m){Se.showTemporaryMessage(`Merge failed: ${m}`)}})()}),e.bindAction("set-anchor",c=>{c.stopPropagation();const{segmentSelectionState:d}=this.layer.displayState,u=d.baseValue;if(u===void 0)return;const h=this.layer.anchorSegment.value;if(t.visibleSegments.add(u),h===void 0||!M.R.equal(h,u)){this.layer.anchorSegment.value=u.clone();return}})}get description(){return"merge"}}class BR extends vs{toJSON(){return Yd}activate(e){const t=this.layer.displayState.segmentationGroupState.value,n=()=>{const d=this.layer.anchorSegment.value;if(d===void 0)return{anchorSegment:void 0,error:"Select anchor segment for split"};const u=t.segmentEquivalences.get(d);return t.visibleSegments.has(u)?{anchorSegment:d,error:void 0}:{anchorSegment:d,error:"Anchor segment must be in visible set"}},{body:s,header:r}=Ss(e);r.textContent="Split segments",s.classList.add("neuroglancer-merge-segments-status"),e.bindInputEventMap(VR);const o=()=>{const{anchorSegment:d,error:u}=n();if(d===void 0||u!==void 0)return{anchorSegment:d,error:u,otherSegment:void 0,anchorSegmentValid:!1};const{displayState:h}=this.layer,f=h.segmentSelectionState.baseValue;return f===void 0||!M.R.equal(h.segmentSelectionState.selectedSegment,t.segmentEquivalences.get(d))||M.R.equal(f,d)?{anchorSegment:d,otherSegment:void 0,anchorSegmentValid:!0,error:"Hover over base segment to seed split"}:{anchorSegment:d,otherSegment:f,anchorSegmentValid:!0,error:void 0}};e.registerDisposer(()=>{Or(t)});const a=()=>{Ae(s);const{displayState:d}=this.layer,{anchorSegment:u,otherSegment:h,anchorSegmentValid:f,error:m}=o();let g,v;(()=>{const{segmentEquivalences:x}=t,{graphConnection:{value:b}}=this.layer;if(!f||b===void 0){Or(t);return}if(t.useTemporaryVisibleSegments.value=!0,h!==void 0){const C=b.computeSplit(u,h);if(C!==void 0){g=new hi(u,C.includeRepresentative),v=new hi(h,C.excludeRepresentative),t.useTemporarySegmentEquivalences.value=!0;const k=C.includeRepresentative,T=C.excludeRepresentative,L=t.temporarySegmentEquivalences;L.clear();for(const R of C.includeBaseSegments)L.link(R,k);for(const R of C.excludeBaseSegments)L.link(R,T);const _=t.temporaryVisibleSegments;_.clear(),_.add(k),_.add(T);return}}t.useTemporarySegmentEquivalences.value=!1;const E=t.temporaryVisibleSegments;E.clear(),E.add(x.get(u))})();const S=x=>{const b=yd(this.layer.displayState,x);return b.classList.add("neuroglancer-segment-list-entry-double-line"),b};if(u!==void 0&&s.appendChild(S(g??ji(d,u))),m!==void 0){const x=document.createElement("span");x.textContent=m,s.appendChild(x)}if(v!==void 0){const x=document.createElement("span");x.textContent=" split ",s.appendChild(x),s.appendChild(S(v))}};e.registerDisposer(Vr(this.layer.displayState,s)),a();const l=e.registerCancellable((0,je.t)(a));Vs(this.layer.displayState,e,l),e.registerDisposer(this.layer.anchorSegment.changed.add(l));const c=async d=>{const{graph:{value:u}}=t;if(u===void 0)return;const{anchorSegment:h,otherSegment:f,error:m}=o();if(!(h===void 0||f===void 0||m!==void 0))try{await u.split(h,f),d&&t.visibleSegments.add(t.segmentEquivalences.get(f)),Se.showTemporaryMessage("Split performed")}catch(g){Se.showTemporaryMessage(`Split failed: ${g}`)}};e.bindAction("split-segments",d=>{d.stopPropagation(),c(!1)}),e.bindAction("split-and-select-segments",d=>{d.stopPropagation(),c(!0)}),e.bindAction("set-anchor",d=>{d.stopPropagation();const{segmentSelectionState:u}=this.layer.displayState,h=u.baseValue;if(h===void 0)return;t.visibleSegments.add(h);const f=this.layer.anchorSegment.value;if(f===void 0||!M.R.equal(f,h)){this.layer.anchorSegment.value=h.clone();return}})}get description(){return"split"}}function FR(i){Rn(i,jd,e=>new _R(e)),Rn(i,Yd,e=>new BR(e))}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const UR=new M.R;class hy extends D.O8{constructor(e,t){super(),this.segmentationDisplayState=e,this.parentElement=t,this.changed=new j.HN,this.explicitSegmentsVisible=!1,this.debouncedUpdate=(0,xe.A)(()=>this.update(),0)}updateRendering(e){this.segmentWidgetFactory.update(e)}updateRenderedItems(e){e.forEachRenderedItem(t=>{this.updateRendering(t)})}}class py extends hy{constructor(e,t){super(e,t),this.segmentationDisplayState=e,this.parentElement=t,this.render=n=>{const{explicitSegments:s}=this,r=s[n];return this.segmentWidgetFactory.get(r)},this.update(),this.registerDisposer(e.segmentationGroupState.value.selectedSegments.changed.add(this.debouncedUpdate))}update(){const e=[],{selectedSegments:t}=this.segmentationDisplayState.segmentationGroupState.value,n=[...t],{explicitSegments:s}=this;s===void 0?e.push({retainCount:0,insertCount:n.length,deleteCount:0}):e.push(...(0,z.ak)(s,n,M.R.equal)),this.explicitSegments=n,this.length=n.length,this.changed.dispatch(e)}}class fy extends hy{constructor(e,t,n,s){super(n,s),this.query=e,this.segmentPropertyMap=t,this.segmentationDisplayState=n,this.parentElement=s,this.queryResult=new A.B0(void 0),this.prevQueryResult=new A.B0(void 0),this.statusText=new A.B0(""),this.selectedMatches=0,this.visibleMatches=0,this.matchStatusTextPrefix="",this.selectedSegmentsGeneration=-1,this.visibleSegmentsGeneration=-1,this.explicitSegmentsVisible=!1,this.render=r=>{const{explicitSegments:o}=this;let a;if(o!==void 0)a=o[r];else{a=UR;const l=this.queryResult.value.indices[r],{ids:c}=this.segmentPropertyMap.segmentPropertyMap.inlineProperties;a.low=c[l*2],a.high=c[l*2+1]}return this.segmentWidgetFactory.get(a)},this.update(),this.registerDisposer(n.segmentationGroupState.value.selectedSegments.changed.add(this.debouncedUpdate)),this.registerDisposer(n.segmentationGroupState.value.visibleSegments.changed.add(this.debouncedUpdate)),e&&this.registerDisposer(e.changed.add(this.debouncedUpdate))}get numMatches(){return this.queryResult.value?.count??0}update(){const e=this.query.value,{segmentPropertyMap:t}=this;this.prevQueryResult.value=this.queryResult.value;const n=this.prevQueryResult.value;let s;if(this.prevQuery===e)s=n;else{const b=nI(t,e);s=iI(t,b)}const r=[];let o=!1,a="";const l=cI(s.query);l||this.explicitSegments!==void 0&&this.explicitSegmentsVisible&&(r.push({deleteCount:this.explicitSegments.length,retainCount:0,insertCount:0}),this.explicitSegments=void 0,o=!0);const{explicitIds:c}=s;c!==void 0?this.explicitSegments=c:this.explicitSegmentsVisible||(this.explicitSegments=void 0),n!==s&&(r.push({retainCount:0,deleteCount:n?.count??0,insertCount:s.count}),o=!0,this.queryResult.value=s),s.explicitIds!==void 0?a=`${s.count} ids`:l?a=`${s.count} total ids`:s.total>0&&(a=`${s.count} match /${s.total} total ids`);const{selectedSegments:d,visibleSegments:u}=this.segmentationDisplayState.segmentationGroupState.value,h=d.changed.count,f=u.changed.count,m=this.selectedSegmentsGeneration,g=this.visibleSegmentsGeneration,v=n!==s,y=m!==h||v,S=g!==f||v;this.selectedSegmentsGeneration=h,this.visibleSegmentsGeneration=f,y&&(this.selectedMatches=s.count>0?ev(t,s,d):0),S&&(this.visibleMatches=s.count>0?ev(t,s,u):0);let x=a;this.selectedMatches>0&&(this.selectedMatches===this.visibleMatches?x=`${this.selectedMatches} vis/${x}`:this.visibleMatches>0?x=`${this.visibleMatches} vis/${this.selectedMatches} star/${x}`:x=`${this.selectedMatches} star/${x}`),this.statusText.value=x,this.prevQuery=e,this.matchStatusTextPrefix=a,this.length=s.count,o&&this.changed.dispatch(r)}}const gy=Pe.fromObject({enter:{action:"toggle-listed"},"shift+enter":{action:"hide-listed"},"control+enter":{action:"hide-all"},escape:{action:"cancel"}});function my(i){Ft(i,Math.max(1,i.value.length+.1))}function Qd(i,e){let t;if(Number.isInteger(e))t=e.toString();else{const n=e.toString(),s=e.toPrecision(6);t=n.length<s.length?n:s}i.value=t,my(i)}function $R(i,e){const t=document.createElement("input");return t.addEventListener("focus",()=>{t.select()}),t.classList.add(`neuroglancer-segment-query-result-numerical-plot-${i}-bound`),t.classList.add("neuroglancer-segment-query-result-numerical-plot-bound"),t.type="text",t.spellcheck=!1,t.autocomplete="off",t.title=(e===0?"Lower":"Upper")+" bound "+(i==="range"?"range":"for distribution"),t.addEventListener("input",()=>{my(t)}),t}function GR(i,e,t){if(i===void 0||i.indices===void 0)return;const n=i.query;let{sortBy:s,includeColumns:r}=n;Ca(n,t)?(s=s.filter(a=>a.fieldId!==t),r=r.filter(a=>a!==t)):r.push(t),e({...n,sortBy:s,includeColumns:r})}function vy(i,e,t){const n=i?.query,s=n?.sortBy;if(s===void 0)return;const{includeColumns:r}=n,a=s.find(c=>c.fieldId===t)?.order==="<"?">":"<",l=r.filter(c=>c!==t);for(const c of s)c.fieldId!=="id"&&c.fieldId!=="label"&&c.fieldId!==t&&l.push(c.fieldId);e({...n,sortBy:[{fieldId:t,order:a}],includeColumns:l})}function yy(i,e,t){const s=i?.query?.sortBy?.find(r=>r.fieldId===t)?.order;e.textContent=s===">"?"\u25BC":"\u25B2",e.style.visibility=s===void 0?"":"visible",e.title=`Sort by ${t} in ${s==="<"?"descending":"ascending"} order`}class zR extends D.O8{constructor(e,t,n){super(),this.segmentPropertyMap=e,this.queryResult=t,this.setQuery=n,this.propertyHistograms=[],this.bounds={window:new A.B0([]),range:new A.B0([])},this.throttledUpdate=this.registerCancellable((0,Ls.A)(()=>this.updateHistograms(),100)),this.debouncedRender=this.registerCancellable((0,je.t)(()=>this.updateHistogramRenderings())),this.debouncedSetQuery=this.registerCancellable((0,xe.A)(()=>this.setQueryFromBounds(),200));const s=e?.numericalProperties,r=[];let o;if(s!==void 0&&s.length>0){o=document.createElement("details");const a=document.createElement("summary");a.textContent=`${s.length} numerical propert${s.length>1?"ies":"y"}`,o.appendChild(a),o.classList.add("neuroglancer-segment-query-result-numerical-list");const l=this.bounds.window.value;for(let c=0,d=s.length;c<d;++c){const u=s[c],h=this.makeNumericalPropertySummary(c,u);r.push(h),o.appendChild(h.element),l[c]=u.bounds}}this.listElement=o,this.properties=r,this.registerDisposer(this.queryResult.changed.add(()=>{this.handleNewQueryResult()})),this.registerDisposer(this.bounds.window.changed.add(this.throttledUpdate)),this.registerDisposer(this.bounds.window.changed.add(this.debouncedRender)),this.registerDisposer(this.bounds.range.changed.add(this.debouncedRender)),this.registerDisposer(this.bounds.range.changed.add(this.debouncedSetQuery)),this.handleNewQueryResult()}setQueryFromBounds(){const e=this.queryResult.value;if(e===void 0||e.indices===void 0)return;const t=e.query,n=[],s=this.bounds.range.value,{properties:r}=this;for(let o=0,a=r.length;o<a;++o){const l=r[o].property;n.push({fieldId:l.id,bounds:s[o]})}this.setQuery({...t,numericalConstraints:n})}getBounds(e){const{bounds:t}=this;return{range:t.range.value[e],window:t.window.value[e]}}setBounds(e,t){const{property:n}=this.properties[e];let s=qe(n.bounds,t.range);nt(s[0],s[1])>0&&(s=[s[1],s[0]]);const r=qe(n.bounds,t.window),o=this.getBounds(e),{dataType:a}=this.properties[e].property;O(a,r,o.window)||(this.bounds.window.value[e]=r,this.bounds.window.changed.dispatch()),O(a,s,o.range)||(this.bounds.range.value[e]=s,this.bounds.range.changed.dispatch())}setBound(e,t,n,s){const o=this.segmentPropertyMap.numericalProperties[n].bounds;s=Le(o,s);const a=this.getBounds(n),l=gr(a,e,t,s,!0);this.setBounds(n,l)}handleNewQueryResult(){const e=this.queryResult.value,{listElement:t}=this;if(t!==void 0){if(e?.indices!==void 0){const{numericalConstraints:n}=e.query,{numericalProperties:s}=this.segmentPropertyMap,r=this.bounds.range.value,o=n.length,a=s.length;r.length=a;for(let l=0;l<a;++l)r[l]=s[l].bounds;for(let l=0;l<o;++l){const c=n[l],d=s.findIndex(u=>u.id===c.fieldId);r[d]=c.bounds}}this.updateHistograms(),this.throttledUpdate.cancel()}}updateHistograms(){const e=this.queryResult.value,{listElement:t}=this;t!==void 0&&(rI(this.segmentPropertyMap,e,this.propertyHistograms,this.bounds.window.value),this.updateHistogramRenderings())}updateHistogramRenderings(){this.debouncedRender.cancel();const{listElement:e}=this;if(e===void 0)return;const{propertyHistograms:t}=this;if(t.length===0){e.style.display="none";return}e.style.display="";const{properties:n}=this;for(let s=0,r=n.length;s<r;++s)this.updateNumericalPropertySummary(s,n[s],t[s])}makeNumericalPropertySummary(e,t){const n=document.createElement("div");n.classList.add("neuroglancer-segment-query-result-numerical-plot-container");const s=document.createElement("img");s.classList.add("neuroglancer-segment-query-result-numerical-plot");const r=new lf(s,t.dataType,()=>this.getBounds(e),d=>this.setBounds(e,d)),o=document.createElement("span");o.classList.add("neuroglancer-segment-query-result-numerical-plot-sort");const a=document.createElement("input");a.type="checkbox",a.addEventListener("click",()=>{GR(this.queryResult.value,this.setQuery,t.id)});const l=d=>{const u=document.createElement("div");u.classList.add("neuroglancer-segment-query-result-numerical-plot-bounds"),u.classList.add(`neuroglancer-segment-query-result-numerical-plot-bounds-${d}`);const h=g=>{const v=$R(d,g);return v.addEventListener("change",()=>{if(this.bounds[d].value[e]!==void 0){try{const S=qt(t.dataType,v.value);this.setBound(d,g,e,S),this.bounds[d].changed.dispatch()}catch{}Qd(v,this.bounds[d].value[e][g])}}),v},f=[h(0),h(1)];let m;if(d==="range"){m=[document.createElement("div"),document.createElement("div"),document.createElement("div")],m[1].classList.add("neuroglancer-segment-query-result-numerical-plot-bound-constraint-spacer"),m[1].appendChild(a);const g=document.createElement("span");g.classList.add("neuroglancer-segment-query-result-numerical-plot-label"),g.appendChild(document.createTextNode(t.id)),g.appendChild(o),g.addEventListener("click",()=>{vy(this.queryResult.value,this.setQuery,t.id)}),m[1].appendChild(g);const{description:v}=t;v&&(m[1].title=v),u.appendChild(m[0]),u.appendChild(f[0]);const y=document.createElement("div");y.textContent="\u2264",y.classList.add("neuroglancer-segment-query-result-numerical-plot-bound-constraint-symbol"),u.appendChild(y),u.appendChild(m[1]);const S=document.createElement("div");S.textContent="\u2264",S.classList.add("neuroglancer-segment-query-result-numerical-plot-bound-constraint-symbol"),u.appendChild(S),u.appendChild(f[1]),u.appendChild(m[2])}else u.appendChild(f[0]),u.appendChild(f[1]);return{container:u,spacers:m,inputs:f}},c={range:l("range"),window:l("window")};return n.appendChild(c.range.container),n.appendChild(s),n.appendChild(c.window.container),{property:t,controller:r,element:n,plotImg:s,boundElements:c,bounds:{window:[NaN,NaN],range:[NaN,NaN]},propertyHistogram:void 0,columnCheckbox:a,sortIcon:o}}updateNumericalPropertySummary(e,t,n){const s=t.bounds.window,r=this.bounds.window.value[e],o=t.bounds.range,a=this.bounds.range.value[e],{property:l}=t,c=this.queryResult.value,d=Ca(c?.query,l.id);if(t.columnCheckbox.checked=d,t.columnCheckbox.title=d?"Remove column from result table":"Add column to result table",yy(c,t.sortIcon,l.id),t.propertyHistogram===n&&O(l.dataType,s,r)&&O(l.dataType,o,a))return;const{histogram:u}=n,h="http://www.w3.org/2000/svg",f=document.createElementNS(h,"svg");f.setAttribute("width","1"),f.setAttribute("height","1"),f.setAttribute("preserveAspectRatio","none");const m=document.createElementNS(h,"rect"),g=se(r,a[0]),v=se(r,a[1]);m.setAttribute("x",`${g}`),m.setAttribute("y","0"),m.setAttribute("width",`${v-g}`),m.setAttribute("height","1"),m.setAttribute("fill","#4f4f4f"),f.appendChild(m);const y=u.length,S=(L,_,R)=>{const P=document.createElementNS(h,"polyline");let V="",$=0;for(let fe=L;fe<R;++fe)$+=u[fe];if($===0)return;const Q=se(r,n.window[0]),K=se(r,n.window[1]),ee=(fe,le)=>{const ve=fe/(y-2),Ie=Q*(1-ve)+K*ve;V+=` ${Ie},${1-le}`};L!==0&&ee(L,0);let ce=0;for(let fe=L;fe<_;++fe){const le=u[fe];ce+=le,ee(fe,ce/$)}return P.setAttribute("fill","none"),P.setAttribute("stroke-width","1px"),P.setAttribute("points",V),P.setAttribute("vector-effect","non-scaling-stroke"),P};{const L=S(0,y-1,y);L!==void 0&&(L.setAttribute("stroke","cyan"),f.appendChild(L))}if(!O(l.dataType,l.bounds,a)){const L=Math.floor(Math.max(0,Math.min(1,se(n.window,a[0])))*(y-2)),_=Math.ceil(Math.max(0,Math.min(1,se(n.window,a[1])))*(y-2)),R=S(L,_,_);R!==void 0&&(R.setAttribute("stroke","white"),f.appendChild(R))}const x=new XMLSerializer().serializeToString(f);t.plotImg.src=`data:image/svg+xml;base64,${btoa(x)}`,t.propertyHistogram=n;for(let L=0;L<2;++L)s[L]=r[L],Qd(t.boundElements.window.inputs[L],r[L]),o[L]=a[L],Qd(t.boundElements.range.inputs[L],a[L]);const b=t.boundElements.range.spacers,E=qe(r,a),C=Ce(l.dataType,r),k=se(r,E[0])*C,T=se(r,E[1])*C+(1-C);b[0].style.width=`${k*100}%`,b[2].style.width=`${(1-T)*100}%`}}function WR(i,e){const{tags:t}=i;if(t===void 0||t.length===0)return;const n=i.query,s=document.createElement("div");s.classList.add("neuroglancer-segment-query-result-tag-list");for(const{tag:r,count:o,desc:a}of t){const l=document.createElement("div");l.classList.add("neuroglancer-segment-query-result-tag");const c=document.createElement("span");c.classList.add("neuroglancer-segment-query-result-tag-name"),r!==a&&a!==void 0&&a!==""?c.textContent=r+" ("+a+")":c.textContent=r,s.appendChild(l);const d=n.includeTags.includes(r),u=n.excludeTags.includes(r);let h;d?h="Remove tag from required set":u?h="Remove tag from excluded set":h="Add tag to required set",c.addEventListener("click",()=>{e(tv(n,r,!0,!d&&!u))}),c.title=h;const f=d||u,m=v=>{const y=v?o:i.count-o,S=document.createElement("div");if(S.classList.add("neuroglancer-segment-query-result-tag-toggle"),S.classList.add(`neuroglancer-segment-query-result-tag-${v?"include":"exclude"}`),l.appendChild(S),!f&&y===0)return;const x=v?d:u;S.appendChild(new en({get value(){return x},set value(b){e(tv(n,r,v,b))},changed:j.$$},{text:v?"+":"-",enableTitle:`Add tag to ${v?"required":"exclusion"} set`,disableTitle:`Remove tag from ${v?"required":"exclusion"} set`,backgroundScheme:"dark"}).element)};m(!0),m(!1),l.appendChild(c);const g=document.createElement("span");g.classList.add("neuroglancer-segment-query-result-tag-count"),f||(g.textContent=o.toString()),l.appendChild(g)}return s}class Sy extends D.O8{constructor(e,t){super(),this.listSource=e,this.group=t,this.element=document.createElement("div"),this.selectionStatusContainer=document.createElement("span"),this.selectionStatusMessage=document.createElement("span"),this.statusChanged=new j.IY,this.debouncedUpdateStatus=(0,xe.A)(()=>this.updateStatus(),0);const{element:n}=this;n.style.display="contents",this.starAllButton=Lm({title:"Click to toggle star status, shift+click to unstar non-visible segments.",onClick:r=>{const o=this.starAllButton.classList.contains("neuroglancer-starred");if(r.shiftKey){const a=[];for(const l of this.group.selectedSegments)this.group.visibleSegments.has(l)||a.push(l);this.group.selectedSegments.delete(a);return}this.selectSegments(!o,!1)}}),this.copyAllSegmentsButton=zn({title:"Copy all segment IDs",onClick:()=>{this.copySegments(!1)}}),this.copyVisibleSegmentsButton=zn({title:"Copy visible segment IDs",onClick:()=>{this.copySegments(!0)}}),this.visibilityToggleAllButton=km({onClick:r=>{if(r.shiftKey){this.invertVisibility();return}this.makeSegmentsVisible(!this.visibilityToggleAllButton.classList.contains("neuroglancer-visible"))}});const{selectionStatusContainer:s}=this;this.selectionStatusMessage.classList.add("neuroglancer-segment-list-status-message"),s.classList.add("neuroglancer-segment-list-status"),s.appendChild(this.copyAllSegmentsButton),s.appendChild(this.starAllButton),s.appendChild(this.visibilityToggleAllButton),s.appendChild(this.copyVisibleSegmentsButton),s.appendChild(this.selectionStatusMessage),this.element.appendChild(s),this.registerDisposer(t.visibleSegments.changed.add(this.debouncedUpdateStatus)),this.registerDisposer(t.selectedSegments.changed.add(this.debouncedUpdateStatus)),this.registerDisposer(e.changed.add(this.debouncedUpdateStatus))}makeSegmentsVisible(e){const{visibleSegments:t}=this.group,n=Array.from(this.listSegments(!0));t.set(n,e)}invertVisibility(){const e=[],t=[],{visibleSegments:n}=this.group;for(const s of this.listSegments(!0))n.has(s)?t.push(s):e.push(s);n.set(e,!0),n.set(t,!1)}selectSegments(e,t=!1){const{selectedSegments:n,visibleSegments:s}=this.group,r=Array.from(this.listSegments(!0));(e||!t)&&n.set(r,e),t&&s.set(r,e)}copySegments(e=!1){let t=[...this.listSegments(!0)];e&&(t=t.filter(n=>this.group.visibleSegments.has(n))),t.sort(M.R.compare),ai(t.join(", "))}*listSegments(e=!1){}updateStatus(){const{listSource:e,group:t,starAllButton:n,selectionStatusMessage:s,copyAllSegmentsButton:r,copyVisibleSegmentsButton:o,visibilityToggleAllButton:a}=this;e.debouncedUpdate.flush();const{visibleSegments:l,selectedSegments:c}=t;let d=0,u=0,h=0,f="";const m=c.size,g=l.size;e instanceof fy?(h=e.numMatches,d=e.visibleMatches,u=e.selectedMatches,f=e.statusText.value):f=`${g}/${m} visible`;const v=h?d:g,y=h?u:m,S=h||m;n.classList.toggle("neuroglancer-starred",y===S),n.classList.toggle("neuroglancer-indeterminate",y>0&&y!==S),s.textContent=f,r.title=`Copy all ${S} ${h?"matching":"starred"} segment(s)`,o.title=`Copy ${v} ${h?"visible matching":"visible"} segment(s)`,r.style.visibility=S?"visible":"hidden",o.style.visibility=v?"visible":"hidden",n.style.visibility=S?"visible":"hidden",a.style.visibility=S?"visible":"hidden";const x=v===S;a.classList.toggle("neuroglancer-visible",x);const b=v>0&&v!==S;a.classList.toggle("neuroglancer-indeterminate",b);let E;x?E=`Click to hide ${S} segment ID(s).`:E=`Click to show ${S-v} segment ID(s).`,b&&(E+="  Shift+click to invert visibility."),a.title=E,this.statusChanged.dispatch()}}class HR extends Sy{constructor(e,t){super(e,t),this.listSource=e,this.group=t}listSegments(e=!1){return this.group.selectedSegments[Symbol.iterator]()}}class JR extends Sy{constructor(e,t,n,s,r,o,a){super(t,n),this.listSource=t,this.segmentPropertyMap=s,this.debouncedUpdateQueryModel=a;const l=g=>{o.focus(),o.select();const v=oI(s,g);document.execCommand("insertText",!1,v),r.value=v,o.select()},c=document.createElement("div");c.classList.add("neuroglancer-segment-query-result-statistics");const d=document.createElement("div");d.classList.add("neuroglancer-segment-query-result-statistics-separator");const u=document.createElement("ul");u.classList.add("neuroglancer-segment-query-errors"),this.element.prepend(u,c,d),this.registerEventListener(o,"input",()=>{a()}),this.registerDisposer(X(o,"cancel",()=>{o.focus(),o.select(),document.execCommand("delete"),o.blur(),o.value="",r.value=""})),this.registerDisposer(X(o,"toggle-listed",()=>{this.toggleMatches()})),this.registerDisposer(X(o,"hide-all",()=>{n.visibleSegments.clear()})),this.registerDisposer(X(o,"hide-listed",()=>{a(),a.flush(),t.debouncedUpdate.flush();const{visibleSegments:g}=n;this.listSource instanceof py?g.clear():g.delete(Array.from(this.listSegments()))}));const h=this.registerDisposer(new zR(s,t.queryResult,l));{const{listElement:g}=h;g!==void 0&&c.appendChild(g)}const f=g=>{const v=g?.errors;if(Ae(u),v!==void 0)for(const y of v){const S=document.createElement("li");S.textContent=y.message,u.appendChild(S)}};let m;(0,A.W1)(g=>{if(t.segmentWidgetFactory=new Om(t.segmentationDisplayState,t.parentElement,y=>Ca(g?.query,y.id)),e.scrollToTop(),Ae(e.header),s!==void 0){const y=t.segmentWidgetFactory.getHeader();y.container.classList.add("neuroglancer-segment-list-header");for(const S of y.propertyLabels){const{label:x,sortIcon:b,id:E}=S;x.addEventListener("click",()=>{vy(t.queryResult.value,l,E)}),yy(g,b,E)}e.header.appendChild(y.container)}if(f(g),d.style.display="none",m?.remove(),g===void 0)return;const{query:v}=g;v.errors!==void 0||v.ids!==void 0||(m=WR(g,l),m!==void 0&&c.appendChild(m),(h.properties.length>0||m!==void 0)&&(d.style.display=""))},t.queryResult)}updateQuery(){const{listSource:e,debouncedUpdateQueryModel:t}=this;t(),t.flush(),e.debouncedUpdate.flush()}listSegments(e=!1){const{listSource:t,segmentPropertyMap:n}=this;this.updateQuery();const s=t.queryResult.value;return lI(n,s,e)}toggleMatches(){const{listSource:e}=this;this.updateQuery(),e.debouncedUpdate.flush();const t=e.queryResult.value;if(t===void 0)return;const{visibleMatches:n}=e,s=n!==t.count;return this.selectSegments(s,!0),!0}}class jR extends Gt{constructor(e){super(),this.layer=e;const{element:t}=this;t.classList.add("neuroglancer-segment-display-tab"),t.appendChild(this.registerDisposer(new zt(e.displayState.segmentationGroupState.value.graph,(l,c,d)=>{if(l===void 0||l.tabContents)return;const u=document.createElement("div");u.className="neuroglancer-segmentation-toolbox",u.appendChild(ys(d,e.toolBinder,{toolJson:jd,label:"Merge",title:"Merge segments"})),u.appendChild(ys(d,e.toolBinder,{toolJson:Yd,label:"Split",title:"Split segments"})),c.appendChild(u)})).element);const n=document.createElement("div");n.className="neuroglancer-segmentation-toolbox",n.appendChild(ys(this,e.toolBinder,{toolJson:Hd,label:"Select",title:"Select/Deselect segments"})),t.appendChild(n);const s=document.createElement("input");s.classList.add("neuroglancer-segment-list-query"),s.addEventListener("focus",()=>{s.select()});const r=this.registerDisposer(new mn(s,gy));r.allShortcutsAreGlobal=!0;const{segmentQuery:o}=this.layer.displayState,a=this.registerCancellable((0,xe.A)(()=>{o.value=s.value},200));s.autocomplete="off",s.title=gy.describe(),s.spellcheck=!1,s.placeholder="Enter ID, name prefix or /regexp",this.registerDisposer((0,A.W1)(l=>{s.value=l},o)),this.registerDisposer((0,A.W1)(l=>{Date.now()-l<100&&(setTimeout(()=>{s.focus()},0),this.layer.segmentQueryFocusTime.value=Number.NEGATIVE_INFINITY)},this.layer.segmentQueryFocusTime)),t.appendChild(s),t.appendChild(this.registerDisposer(new zt(e.displayState.segmentPropertyMap,(l,c,d)=>{const u=d.registerDisposer(new fy(o,l,e.displayState,c)),h=d.registerDisposer(new py(e.displayState,c)),f=d.registerDisposer(new Pa({source:u,horizontalScroll:!0})),m=d.registerDisposer(new Pa({source:h,horizontalScroll:!0})),g=e.displayState.segmentationGroupState.value,v=d.registerDisposer(new JR(f,u,g,l,o,s,a));v.element.appendChild(f.element),c.appendChild(v.element);const y=d.registerDisposer(new HR(h,g));y.element.appendChild(m.element),c.appendChild(y.element);const S=()=>{const E=u.query.value!==""||u.numMatches>0,C=h.length>0||!E;v.element.style.display=E?"contents":"none",y.element.style.display=C?"contents":"none"};d.registerDisposer(v.statusChanged.add(S)),d.registerDisposer(y.statusChanged.add(S)),v.updateStatus(),y.updateStatus();const x=d.registerCancellable((0,je.t)(()=>{u.updateRenderedItems(f),h.updateRenderedItems(m)})),{displayState:b}=this.layer;Vs(b,d,x),d.registerDisposer(b.segmentationGroupState.value.selectedSegments.changed.add(x)),f.element.classList.add("neuroglancer-segment-list"),f.element.classList.add("neuroglancer-preview-list"),m.element.classList.add("neuroglancer-segment-list"),d.registerDisposer(e.bindSegmentListWidth(f.element)),d.registerDisposer(e.bindSegmentListWidth(m.element)),d.registerDisposer(new fn(f.element,Mr())),d.registerDisposer(new fn(m.element,Mr())),h.segmentWidgetFactory=new Om(h.segmentationDisplayState,h.parentElement,E=>Ca(void 0,E.id)),m.scrollToTop(),Ae(m.header)})).element)}}var $s=G(4472);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class YR{constructor(){$s.A.initializeHead(this)}}const qd=new YR,QR=window.top===window,Kd=(0,xe.A)(()=>{if(!QR)return;const{activeElement:i}=document;if(i===null||i===document.body){const e=$s.A.front(qd);e!==null&&e.element.focus({preventScroll:!0})}});window.addEventListener("focus",()=>{Kd()},!0),window.addEventListener("blur",()=>{Kd()},!0);class Na extends D.O8{constructor(e){super(),this.element=e,this.prev0=null,this.next0=null,this.lastFocusedElement=null,this.scheduleUpdateFocus=this.registerCancellable((0,xe.A)(()=>{const{activeElement:t}=document,{element:n}=this;n.contains(t)||hc(t)||(t!=null&&(t===this.lastFocusedElement||t.contains(n))&&this.element.focus({preventScroll:!0}),this.lastFocusedElement=null)},0)),e.tabIndex=-1,this.registerEventListener(e,"pointerdown",t=>{t.target===e&&(this.lastFocusedElement=null,e.focus({preventScroll:!0}))}),this.registerEventListener(e,"mouseenter",()=>{this.lastFocusedElement=document.activeElement,this.scheduleUpdateFocus()}),this.registerEventListener(e,"mouseleave",()=>{this.scheduleUpdateFocus.cancel()}),$s.A.insertBefore(qd,this),this.registerEventListener(e,"focus",()=>{$s.A.pop(this),$s.A.insertAfter(qd,this)}),Kd()}disposed(){$s.A.pop(this),super.disposed()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const F_=100;let Xd=0;const qR=Pe.fromObject({escape:{action:"close"}});class $r extends D.O8{constructor(){super(),this.keyMap=new Pe,this.keyMap.addParent(qR,Number.NEGATIVE_INFINITY),++Xd;const e=this.container=document.createElement("div");e.className="overlay";const t=this.content=document.createElement("div");this.registerDisposer(new Na(t)),t.className="overlay-content",e.appendChild(t),document.body.appendChild(e),this.registerDisposer(new mn(this.container,this.keyMap)),this.registerEventListener(e,"action:close",()=>{this.dispose()}),t.focus()}disposed(){--Xd,document.body.removeChild(this.container),super.disposed()}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Oa(i={}){return _e({text:"?",...i})}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class by extends D.O8{constructor(e){super(),this.group=e,this.element=document.createElement("div"),this.topRow=document.createElement("div"),this.label=document.createElement("label"),this.selectElement=document.createElement("select"),this.linkedLayers=document.createElement("div"),this.unlinkButton=document.createElement("button");const{element:t,label:n,topRow:s,selectElement:r,linkedLayers:o,unlinkButton:a}=this;s.appendChild(n),s.appendChild(r),s.appendChild(a),a.textContent="Unlink",a.addEventListener("click",()=>{this.group.isolate()}),t.appendChild(s),t.appendChild(o),this.updateView();const l=(0,xe.A)(()=>this.updateView(),0);this.registerEventListener(r,"change",()=>{this.updateModel(),l()}),this.registerDisposer(this.group.changed.add(l)),this.registerDisposer(this.group.linkedLayersChanged.add(l)),this.registerDisposer(this.group.layerManager.layersChanged.add(l))}updateModel(){const e=this.selectElement.value;e===""&&this.group.root.value!==this.group.layer?this.group.isolate():this.group.linkByName(e)}updateView(){const{selectElement:e,group:t}=this,{predicate:n}=t;Ae(e);const s=this.group.rootGroup.linkedLayers.size!==0;this.unlinkButton.style.display=s?"":"none";const{linkedLayers:r}=this,o=t.linkedLayers.size!==0;if(r.style.display=o?"":"none",this.unlinkButton.textContent=o?"Unlink all":"Unlink",o){this.element.style.display="",e.style.display="none",Ae(r);for(const a of t.linkedLayers){const l=document.createElement("div");l.classList.add("neuroglancer-linked-layer-widget-layer");const c=md({title:"Unlink layer",onClick:()=>{this.group.getGroup(a).isolate()}});l.appendChild(c),l.appendChild(document.createTextNode(a.managedLayer.name)),r.appendChild(l)}}else{e.style.display="";const a=document.createElement("option");e.appendChild(a);let l=0;for(const c of this.group.layerManager.managedLayers){const d=c.layer;if(d!==null&&d!==t.layer&&n(d)){++l;const u=document.createElement("option"),{name:h}=c;u.textContent=h,u.value=h,e.appendChild(u)}}e.value=t.toJSON()??"",this.element.style.display=l===0?"none":""}}}var KR=G(4138);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Va(i={}){return _e({svg:KR,...i})}var U_=G(1561),XR=G(5237),vi=G.n(XR),ZR=G(2205),ek=G.n(ZR);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ek()(vi());const tk=500;class _a extends D.O8{constructor(e){super(),this.state=e,this.changingValue=!1,this.debouncedValueUpdater=(0,xe.A)(()=>{this.changingValue=!0;try{this.state.fragmentMain.value=this.textEditor.getValue()}finally{this.changingValue=!1}},tk),this.textEditor=vi()(s=>{},{value:this.state.fragmentMain.value,mode:"glsl",gutters:["CodeMirror-lint-markers"]}),this.textEditor.on("change",()=>{this.setValidState(void 0),this.debouncedValueUpdater()}),this.registerDisposer(this.state.fragmentMain.changed.add(()=>{this.changingValue||this.textEditor.setValue(this.state.fragmentMain.value)})),this.element.classList.add("neuroglancer-shader-code-widget"),this.registerDisposer(this.state.shaderError.changed.add(()=>{this.updateErrorState()}));const{shaderControlState:t}=this.state;t!==void 0&&this.registerDisposer(t.parseErrors.changed.add(()=>{this.updateErrorState()})),this.updateErrorState();const n=new IntersectionObserver(s=>{s.some(r=>r.isIntersecting)&&this.textEditor.refresh()},{root:document.body});n.observe(this.element),this.registerDisposer(()=>n.disconnect())}get element(){return this.textEditor.getWrapperElement()}updateErrorState(){const{sourceStringNumber:e=1}=this.state,t=this.state.shaderError.value;let n;const{shaderControlState:s}=this.state;s!==void 0?n=s.parseErrors.value:n=[],t===void 0&&n.length===0?this.setValidState(void 0):t!=null||n.length!==0?(this.textEditor.setOption("lint",{getAnnotations:()=>{const r=[];for(const o of n)r.push({message:o.message,severity:"error",from:vi().Pos(o.line)});if(t!=null)if(t.name==="ShaderCompilationError")for(const o of t.errorMessages)r.push({message:o.message,severity:"error",from:vi().Pos(o.file===e&&o.line||0)});else t.name==="ShaderLinkError"?r.push({message:t.log,severity:"error",from:vi().Pos(0)}):r.push({message:t.message,severity:"error",from:vi().Pos(0)});return r}}),this.setValidState(!1)):(this.textEditor.setOption("lint",void 0),this.setValidState(!0))}setValidState(e){const{element:t}=this;t.classList.remove("invalid-input"),t.classList.remove("valid-input"),e===!0?t.classList.add("valid-input"):e===!1&&t.classList.add("invalid-input")}disposed(){this.debouncedValueUpdater.flush(),this.debouncedValueUpdater=void 0,lt(this.element),this.textEditor=void 0,super.disposed()}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function nk(i){return{makeControl:(e,t,n)=>{const{watchableValue:s,channelCoordinateSpaceCombiner:r,dataType:o,defaultChannel:a,histogramSpecifications:l,legendShaderOptions:c,histogramIndex:d}=i(e);if(r!==void 0&&a.length!==0){const h=t.registerDisposer(new oi(r.combined)),f=t.registerDisposer(new bs(h,r,{copyButton:!1}));t.registerDisposer(h.changed.add(()=>{const g=h.value,v=Array.from(g,S=>Math.floor(S)),y=s.value;(0,z.r1)(y.channel,v)||(s.value={...s.value,channel:v})}));const m=()=>{const g=h.value,v=s.value;(0,z.r1)(g,v.channel)||(g.set(v.channel),h.changed.dispatch())};m(),t.registerDisposer(s.changed.add(m)),n.labelContainer.appendChild(f.element)}const u=t.registerDisposer(new pf(n.visibility,n.display,o,s,l,d,a.length===0?c:void 0));return{control:u,controlElement:u.element}},activateTool:(e,t)=>{ff(e,t)}}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ik(i){return{makeControl:(e,t,n)=>{const{watchableValue:s,properties:r,histogramSpecifications:o,legendShaderOptions:a,histogramIndex:l}=i(e);{const h=document.createElement("select");for(const[g,v]of r){const y=document.createElement("option");y.textContent=`${g} (${I[v].toLowerCase()})`,y.value=g,h.appendChild(y)}const f=()=>{const g=h.value,v=r.get(g),{window:y,range:S}=s.value;s.value={window:y!==void 0?De(y,v):void 0,range:S!==void 0?De(S,v):void 0,property:g,dataType:v}},m=()=>{h.value=s.value.property};t.registerEventListener(h,"change",f),t.registerDisposer(s.changed.add(m)),m(),n.labelContainer.appendChild(h)}const c={changed:s.changed,get value(){let{dataType:h,window:f,range:m}=s.value;return m===void 0&&(m=ue[h]),{window:tt(f??m),range:m}},set value(h){const{window:f,range:m}=h;s.value={...s.value,window:f,range:m}}},d=(0,A.Uq)(h=>h.dataType,[s]),u=t.registerDisposer(new lx(n.visibility,n.display,d,c,o,l,a));return{control:u,controlElement:u.element}},activateTool:(e,t)=>{ff(e,t)}}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function wy(i,e){const{shaderControlState:t}=i,n=t.state.get(e);if(n===void 0)return;const{control:s}=n;switch(s.type){case"slider":return Jn(()=>({value:n.trackable,options:{min:s.min,max:s.max,step:s.step}}));case"color":return em(()=>n.trackable);case"checkbox":return kr(()=>n.trackable);case"imageInvlerp":{let r=0;for(const[o,{control:{type:a}}]of t.state){if(o===e)break;a==="imageInvlerp"&&++r}return nk(()=>({dataType:s.dataType,defaultChannel:s.default.channel,watchableValue:n.trackable,channelCoordinateSpaceCombiner:t.channelCoordinateSpaceCombiner,histogramSpecifications:t.histogramSpecifications,histogramIndex:r,legendShaderOptions:i.legendShaderOptions}))}case"propertyInvlerp":{let r=0;for(const[o,{control:{type:a}}]of t.state){if(o===e)break;a==="propertyInvlerp"&&++r}return ik(()=>({properties:s.properties,watchableValue:n.trackable,histogramSpecifications:t.histogramSpecifications,histogramIndex:r,legendShaderOptions:i.legendShaderOptions}))}case"transferFunction":return Fx(()=>({dataType:s.dataType,watchableValue:n.trackable,channelCoordinateSpaceCombiner:t.channelCoordinateSpaceCombiner,defaultChannel:s.default.channel}))}}function Cy(i,e,t){return{label:t,toolJson:sk(t,e),makeControl:(n,s,r)=>{const o=i(n);return wy(o,t).makeControl(n,s,r)},activateTool:(n,s)=>{const r=i(n.tool.layer);return wy(r,t).activateTool(n,s)}}}class Ba extends Gt{constructor(e,t,n,s={}){super(s.visibility),this.state=e,this.display=t,this.layer=n,this.options=s,this.controlDisposer=void 0;const{toolId:r=xy}=s;this.toolId=r;const{element:o}=this;o.style.display="contents";const{controls:a}=e;this.registerDisposer(a.changed.add(this.registerCancellable((0,xe.A)(()=>this.updateControls(),0)))),this.updateControls()}updateControls(){const{element:e}=this;this.controlDisposer!==void 0&&(this.controlDisposer.dispose(),Ae(e));const t=this.controlDisposer=new D.O8,n=()=>({shaderControlState:this.state,legendShaderOptions:this.options.legendShaderOptions});for(const s of this.state.state.keys())e.appendChild(rd(t,this.layer,this.visibility,Cy(n,this.toolId,s)))}disposed(){this.controlDisposer?.dispose(),super.disposed()}}const xy="shaderControl",Ey="control";function sk(i,e){return{type:e,[Ey]:i}}class rk extends Qg{constructor(e,t,n,s){super(e,Cy(()=>t,n,s)),this.layerShaderControls=t,this.control=s,this.registerDisposer(t.shaderControlState.controls.changed.add(this.registerCancellable((0,xe.A)(()=>{t.shaderControlState.state.get(s)===void 0&&this.unbind()}))))}activate(e){const{shaderControlState:t}=this.layerShaderControls;t.state.get(this.control)!==void 0&&super.activate(e)}}function Fa(i,e,t=xy){Rn(i,t,(n,s)=>{const r=(0,p.cQ)(s,Ey,p.zr);return new rk(n,e(n),t,r)})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ty(i){return new _a({fragmentMain:i.displayState.skeletonRenderingOptions.shader,shaderError:i.displayState.shaderError,shaderControlState:i.displayState.skeletonRenderingOptions.shaderControlState})}class ok extends Gt{constructor(e){super(),this.layer=e;const{element:t}=this;t.classList.add("neuroglancer-segmentation-rendering-tab");{const s=this.registerDisposer(new by(e.displayState.linkedSegmentationGroup));s.label.textContent="Linked to: ",t.appendChild(s.element)}{const s=this.registerDisposer(new by(e.displayState.linkedSegmentationColorGroup));s.label.textContent="Colors linked to: ",t.appendChild(s.element)}for(const s of nm)t.appendChild(rd(this,e,this.visibility,s));const n=this.registerDisposer(new zt(e.hasSkeletonsLayer,(s,r,o)=>{if(!s)return;const a=document.createElement("div");a.className="neuroglancer-segmentation-dropdown-skeleton-shader-header";const l=document.createElement("div");l.style.flex="1",l.textContent="Skeleton shader:",a.appendChild(l),a.appendChild(Va({title:"Show larger editor view",onClick:()=>{new ak(this.layer)}})),a.appendChild(Oa({title:"Documentation on skeleton rendering",href:"https://github.com/google/neuroglancer/blob/master/src/sliceview/image_layer_rendering.md"})),r.appendChild(a);const c=o.registerDisposer(Ty(this.layer));r.appendChild(c.element),r.appendChild(o.registerDisposer(new Ba(e.displayState.skeletonRenderingOptions.shaderControlState,this.layer.manager.root.display,this.layer,{visibility:this.visibility,toolId:jg})).element),c.textEditor.refresh()},this.visibility));t.appendChild(n.element)}}class ak extends $r{constructor(e){super(),this.layer=e,this.codeWidget=this.registerDisposer(Ty(this.layer)),this.content.classList.add("neuroglancer-segmentation-layer-skeleton-shader-overlay"),this.content.appendChild(this.codeWidget.element),this.codeWidget.textEditor.refresh()}}var lk=Object.defineProperty,ck=Object.getOwnPropertyDescriptor,dk=(i,e,t,n)=>{for(var s=n>1?void 0:n?ck(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&lk(e,t,s),s};/**
 * @license
 * This work is a derivative of the Google Neuroglancer project,
 * Copyright 2016 Google Inc.
 * The Derivative Work is covered by
 * Copyright 2019 Howard Hughes Medical Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Gr=class extends ho{constructor(){super(...arguments),this.hashTable=new ld,this.changed=new j.HN}get value(){return this}static makeWithCounterpart(i){const e=new Gr;return e.initializeCounterpart(i),e}set_(i,e){return this.hashTable.set(i,e)}set(i,e){if(this.set_(i,e)){const{rpc:t}=this;t&&t.invoke("Uint64Map.set",{id:this.rpcId,key:i,value:e}),this.changed.dispatch(i,!0)}}has(i){return this.hashTable.has(i)}get(i,e){return this.hashTable.get(i,e)}[Symbol.iterator](){return this.hashTable.entries()}unsafeEntries(){return this.hashTable.unsafeEntries()}delete_(i){return this.hashTable.delete(i)}delete(i){if(this.delete_(i)){const{rpc:e}=this;e&&e.invoke("Uint64Map.delete",{id:this.rpcId,key:i}),this.changed.dispatch(i,!1)}}get size(){return this.hashTable.size}assignFrom(i){this.clear();for(const[e,t]of i.unsafeEntries())this.set(e,t)}clear(){if(this.hashTable.clear()){const{rpc:i}=this;i&&i.invoke("Uint64Map.clear",{id:this.rpcId}),this.changed.dispatch(null,!1)}}toJSON(){const i={};for(const[e,t]of this.hashTable.unsafeEntries())i[e.toString()]=t.toString();return i}};Gr=dk([po("Uint64Map")],Gr),dt("Uint64Map.set",function(i){const e=this.get(i.id);e.set_(i.key,i.value)&&e.changed.dispatch()}),dt("Uint64Map.delete",function(i){const e=this.get(i.id);e.delete_(i.key)&&e.changed.dispatch()}),dt("Uint64Map.clear",function(i){const e=this.get(i.id);e.hashTable.clear()&&e.changed.dispatch()});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uk{constructor(){this.changed=new j.HN,this.data=new Map}dispose(){this.data.clear()}get size(){return this.data.size}get value(){return this}has(e){return this.data.has(BigInt(e.toString()))}add(e){const{data:t}=this;if(Array.isArray(e)){const n=[];for(let s of e){const r=BigInt(s.toString());t.has(r)||(s=s.clone(),n.push(s),t.set(r,s))}n.length!==0&&this.changed.dispatch(n,!0)}else{const n=BigInt(e.toString());if(t.has(n))return;t.set(n,e.clone()),this.changed.dispatch(e,!0)}}[Symbol.iterator](){return this.data.values()}delete(e){const{data:t}=this;if(Array.isArray(e)){const n=[];for(const s of e){const r=BigInt(s.toString());t.has(r)&&(t.delete(r),n.push(s))}n.length!==0&&this.changed.dispatch(n,!1)}else{const n=BigInt(e.toString());if(!t.has(n))return;t.delete(n),this.changed.dispatch(e,!1)}}set(e,t){t?this.add(e):this.delete(e)}clear(){this.data.size>0&&(this.data.clear(),this.changed.dispatch(null,!1))}toJSON(){return Array.from(this.data.keys(),e=>e.toString())}assignFrom(e){this.clear();const t=e.data,{data:n}=this,s=Array.from(t.values());for(const[r,o]of t)n.set(r,o);this.changed.dispatch(s,!0)}}var hk=Object.defineProperty,pk=Object.getOwnPropertyDescriptor,fk=(i,e,t,n)=>{for(var s=n>1?void 0:n?pk(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&hk(e,t,s),s};/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let zr=class extends ho{constructor(){super(...arguments),this.hashTable=new cm,this.changed=new j.HN}get value(){return this}static makeWithCounterpart(i){const e=new zr;return e.initializeCounterpart(i),e}set(i,e){e?this.add(i):this.delete(i)}reserve_(i){return this.hashTable.reserve(i)}reserve(i){if(this.reserve_(i)){const{rpc:e}=this;e&&e.invoke("Uint64Set.reserve",{id:this.rpcId,value:i})}}add_(i){let e=!1;for(const t of i)e=this.hashTable.add(t)||e;return e}add(i){const e=Array().concat(i);if(this.add_(e)){const{rpc:t}=this;t&&t.invoke("Uint64Set.add",{id:this.rpcId,value:e}),this.changed.dispatch(i,!0)}}has(i){return this.hashTable.has(i)}[Symbol.iterator](){return this.hashTable.keys()}unsafeKeys(){return this.hashTable.unsafeKeys()}delete_(i){let e=!1;for(const t of i)e=this.hashTable.delete(t)||e;return e}delete(i){const e=Array().concat(i);if(this.delete_(Array().concat(i))){const{rpc:t}=this;t&&t.invoke("Uint64Set.delete",{id:this.rpcId,value:e}),this.changed.dispatch(i,!1)}}get size(){return this.hashTable.size}clear(){if(this.hashTable.clear()){const{rpc:i}=this;i&&i.invoke("Uint64Set.clear",{id:this.rpcId}),this.changed.dispatch(null,!1)}}toJSON(){const i=new Array;for(const e of this.unsafeKeys())i.push(e.toString());return i.sort(),i}assignFrom(i){this.clear();for(const e of i.unsafeKeys())this.add(e)}};zr=fk([po("Uint64Set")],zr),dt("Uint64Set.reserve",function(i){const e=this.get(i.id);e.reserve_(i.value)&&e.changed.dispatch()}),dt("Uint64Set.add",function(i){const e=this.get(i.id);e.add_(i.value)&&e.changed.dispatch()}),dt("Uint64Set.delete",function(i){const e=this.get(i.id);e.delete_(i.value)&&e.changed.dispatch()}),dt("Uint64Set.clear",function(i){const e=this.get(i.id);e.hashTable.clear()&&e.changed.dispatch()});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class gk extends D.O8{constructor(e){super(),this.layer=e,this.specificationChanged=new j.HN,this.localGraph=new gI,this.visibleSegments=this.registerDisposer(zr.makeWithCounterpart(this.layer.manager.rpc)),this.selectedSegments=this.registerDisposer(new uk),this.segmentPropertyMap=new A.B0(void 0),this.graph=new A.B0(void 0),this.segmentEquivalences=this.registerDisposer(Yi.makeWithCounterpart(this.layer.manager.rpc,this.layer.registerDisposer((0,A.Uq)(r=>r?.visibleSegmentEquivalencePolicy||Tt.y6.MIN_REPRESENTATIVE,[this.graph])))),this.localSegmentEquivalences=!1,this.maxIdLength=new A.B0(1),this.hideSegmentZero=new rt(!0,!0),this.segmentQuery=new A.DN("",p.zr),this.temporaryVisibleSegments=this.layer.registerDisposer(zr.makeWithCounterpart(this.layer.manager.rpc)),this.temporarySegmentEquivalences=this.layer.registerDisposer(Yi.makeWithCounterpart(this.layer.manager.rpc,this.segmentEquivalences.disjointSets.visibleSegmentEquivalencePolicy)),this.useTemporaryVisibleSegments=this.layer.registerDisposer(ut.make(this.layer.manager.rpc,!1)),this.useTemporarySegmentEquivalences=this.layer.registerDisposer(ut.make(this.layer.manager.rpc,!1));const{specificationChanged:t}=this;this.hideSegmentZero.changed.add(t.dispatch),this.segmentQuery.changed.add(t.dispatch);const{visibleSegments:n,selectedSegments:s}=this;n.changed.add(t.dispatch),s.changed.add(t.dispatch),s.changed.add((r,o)=>{o||(r?n.delete(r):n.clear())}),n.changed.add((r,o)=>{o&&r&&s.add(r)})}restoreState(e){(0,p.MM)(e,qc,t=>this.hideSegmentZero.restoreState(t)),(0,p.MM)(e,ra,t=>{this.localGraph.restoreState(t)}),(0,p.MM)(e,Zc,t=>{const{segmentEquivalences:n,selectedSegments:s,visibleSegments:r}=this;(0,p.$v)(t,o=>{let a=String(o);const l=a.startsWith("!");l&&(a=a.substring(1));const c=M.R.parseString(a,10),d=n.get(c);s.add(d),l||r.add(d)})}),(0,p.MM)(e,zg,t=>this.segmentQuery.restoreState(t))}toJSON(){const e={};e[qc]=this.hideSegmentZero.toJSON();const{selectedSegments:t,visibleSegments:n}=this;t.size>0?e[Zc]=[...t].map(r=>n.has(r)?r.toString():"!"+r.toString()):e[Zc]=[];const{segmentEquivalences:s}=this;return this.localSegmentEquivalences&&s.size>0&&(e[ra]=s.toJSON()),e[zg]=this.segmentQuery.toJSON(),e}assignFrom(e){this.maxIdLength.value=e.maxIdLength.value,this.hideSegmentZero.value=e.hideSegmentZero.value,this.selectedSegments.assignFrom(e.selectedSegments),this.visibleSegments.assignFrom(e.visibleSegments),this.segmentEquivalences.assignFrom(e.segmentEquivalences)}}class mk extends D.O8{constructor(e){super(),this.layer=e,this.specificationChanged=new j.HN,this.segmentColorHash=cd.getDefault(),this.segmentStatedColors=this.registerDisposer(new Gr),this.tempSegmentStatedColors2d=this.registerDisposer(new Gr),this.segmentDefaultColor=new ie,this.tempSegmentDefaultColor2d=new A.B0(void 0),this.highlightColor=new A.B0(void 0);const{specificationChanged:t}=this;this.segmentColorHash.changed.add(t.dispatch),this.segmentStatedColors.changed.add(t.dispatch),this.tempSegmentStatedColors2d.changed.add(t.dispatch),this.segmentDefaultColor.changed.add(t.dispatch),this.tempSegmentDefaultColor2d.changed.add(t.dispatch),this.highlightColor.changed.add(t.dispatch)}restoreState(e){(0,p.MM)(e,ed,t=>this.segmentColorHash.restoreState(t)),(0,p.MM)(e,sd,t=>this.segmentDefaultColor.restoreState(t)),(0,p.MM)(e,Gg,t=>{const n=(0,p.vS)(t,s=>me(String(s)));for(const[s,r]of n){const o=M.R.parseString(String(s)),a=new M.R(Te(r));this.segmentStatedColors.set(o,a)}})}toJSON(){const e={};e[ed]=this.segmentColorHash.toJSON(),e[sd]=this.segmentDefaultColor.toJSON();const{segmentStatedColors:t}=this;if(t.size>0){const n=e[Gg]={};for(const[s,r]of t.unsafeEntries())n[s.toString()]=ze(Ze(r.low))}return e}assignFrom(e){this.segmentColorHash.value=e.segmentColorHash.value,this.segmentStatedColors.assignFrom(e.segmentStatedColors),this.tempSegmentStatedColors2d.assignFrom(e.tempSegmentStatedColors2d),this.segmentDefaultColor.value=e.segmentDefaultColor.value,this.highlightColor.value=e.highlightColor.value}}class Dy extends D.O8{constructor(e,t){super(),this.linkedGroup=e,this.propertyName=t,this.value}get changed(){return this.linkedGroup.root.changed}get value(){const e=this.linkedGroup.root.value;if(e!==this.curRoot){this.curRoot=e;const t=e.displayState[this.propertyName];if(e===this.linkedGroup.layer){const{curGroupState:n}=this;n!==void 0&&(t.assignFrom(n),n.dispose())}this.curGroupState=t.addRef()}return this.curGroupState}disposed(){this.curGroupState?.dispose()}}class vk{constructor(e){this.layer=e,this.segmentSelectionState=new TD,this.selectedAlpha=Fr(.5),this.saturation=Fr(1),this.notSelectedAlpha=Fr(0),this.hoverHighlight=new rt(!0,!0),this.silhouetteRendering=new A.DN(0,p.Zw,0),this.objectAlpha=Fr(1),this.ignoreNullVisibleSet=new rt(!0,!0),this.skeletonRenderingOptions=new bI,this.shaderError=ar(),this.renderScaleHistogram=new Rs,this.renderScaleTarget=_i(1),this.selectSegment=this.layer.selectSegment,this.transparentPickEnabled=this.layer.pick,this.baseSegmentColoring=new rt(!1,!1),this.baseSegmentHighlighting=new rt(!1,!1),this.useTempSegmentStatedColors2d=this.layer.registerDisposer(ut.make(this.layer.manager.rpc,!1)),this.filterBySegmentLabel=this.layer.filterBySegmentLabel,this.moveToSegment=t=>{this.layer.moveToSegment(t)},this.linkedSegmentationGroup=this.layer.registerDisposer(new kg(this.layer.manager.rootLayers,this.layer,t=>t instanceof Rt,t=>t.displayState.linkedSegmentationGroup)),this.linkedSegmentationColorGroup=this.layer.registerDisposer(new kg(this.layer.manager.rootLayers,this.layer,t=>t instanceof Rt,t=>t.displayState.linkedSegmentationColorGroup)),this.originalSegmentationGroupState=this.layer.registerDisposer(new gk(this.layer)),this.originalSegmentationColorGroupState=this.layer.registerDisposer(new mk(this.layer)),e.displayState=this,this.segmentationGroupState=this.layer.registerDisposer(new Dy(this.linkedSegmentationGroup,"originalSegmentationGroupState")),this.segmentationColorGroupState=this.layer.registerDisposer(new Dy(this.linkedSegmentationColorGroup,"originalSegmentationColorGroupState")),this.hideSegmentZero=this.layer.registerDisposer(new A.rG(this.segmentationGroupState,t=>t.hideSegmentZero)),this.segmentColorHash=this.layer.registerDisposer(new A.DY(this.segmentationColorGroupState,t=>t.segmentColorHash)),this.segmentStatedColors=this.layer.registerDisposer(new A.DY(this.segmentationColorGroupState,t=>t.segmentStatedColors)),this.tempSegmentStatedColors2d=this.layer.registerDisposer(new A.DY(this.segmentationColorGroupState,t=>t.tempSegmentStatedColors2d)),this.segmentDefaultColor=this.layer.registerDisposer(new A.DY(this.segmentationColorGroupState,t=>t.segmentDefaultColor)),this.tempSegmentDefaultColor2d=this.layer.registerDisposer(new A.DY(this.segmentationColorGroupState,t=>t.tempSegmentDefaultColor2d)),this.highlightColor=this.layer.registerDisposer(new A.DY(this.segmentationColorGroupState,t=>t.highlightColor)),this.segmentQuery=this.layer.registerDisposer(new A.rG(this.segmentationGroupState,t=>t.segmentQuery)),this.segmentPropertyMap=this.layer.registerDisposer(new A.rG(this.segmentationGroupState,t=>t.segmentPropertyMap))}}const yk=Wd(Ln);class Rt extends yk{constructor(e){super(e),this.sliceViewRenderScaleHistogram=new Rs,this.sliceViewRenderScaleTarget=_i(1),this.graphConnection=new A.B0(void 0),this.segmentQueryFocusTime=new A.B0(Number.NEGATIVE_INFINITY),this.selectSegment=(n,s)=>{this.manager.root.selectionState.captureSingleLayerState(this,r=>(r.value=n.clone(),!0),s)},this.filterBySegmentLabel=n=>{const s=ji(this.displayState,n),{label:r}=s;r&&this.filterSegments(r)},this.filterSegments=n=>{this.displayState.segmentationGroupState.value.segmentQuery.value=n,this.segmentQueryFocusTime.value=Date.now(),this.tabs.value="segments",this.manager.root.selectedLayer.layer=this.managedLayer},this.displayState=new vk(this),this.anchorSegment=new A.DN(void 0,n=>n===void 0?void 0:M.R.parseString(n)),this.has2dLayer=this.registerDisposer((0,A.ol)(n=>n.some(s=>s instanceof Iv),{changed:this.layersChanged,value:this.renderLayers})),this.has3dLayer=this.registerDisposer((0,A.ol)(n=>n.some(s=>s instanceof Sa||s instanceof xd||s instanceof Pd||s instanceof pv),{changed:this.layersChanged,value:this.renderLayers})),this.hasSkeletonsLayer=this.registerDisposer((0,A.ol)(n=>n.some(s=>s instanceof Pd),{changed:this.layersChanged,value:this.renderLayers})),this.registerDisposer((0,A.aM)((n,s)=>{n.registerDisposer(s.specificationChanged.add(this.specificationChanged.dispatch)),this.specificationChanged.dispatch()},this.displayState.segmentationGroupState)),this.registerDisposer((0,A.aM)((n,s)=>{n.registerDisposer(s.specificationChanged.add(this.specificationChanged.dispatch)),this.specificationChanged.dispatch()},this.displayState.segmentationColorGroupState)),this.displayState.segmentSelectionState.bindTo(this.manager.layerSelectedValues,this),this.displayState.selectedAlpha.changed.add(this.specificationChanged.dispatch),this.displayState.saturation.changed.add(this.specificationChanged.dispatch),this.displayState.notSelectedAlpha.changed.add(this.specificationChanged.dispatch),this.displayState.objectAlpha.changed.add(this.specificationChanged.dispatch),this.displayState.hoverHighlight.changed.add(this.specificationChanged.dispatch),this.displayState.baseSegmentColoring.changed.add(this.specificationChanged.dispatch),this.displayState.ignoreNullVisibleSet.changed.add(this.specificationChanged.dispatch),this.displayState.skeletonRenderingOptions.changed.add(this.specificationChanged.dispatch),this.displayState.renderScaleTarget.changed.add(this.specificationChanged.dispatch),this.displayState.silhouetteRendering.changed.add(this.specificationChanged.dispatch),this.anchorSegment.changed.add(this.specificationChanged.dispatch),this.sliceViewRenderScaleTarget.changed.add(this.specificationChanged.dispatch),this.displayState.originalSegmentationGroupState.localGraph.changed.add(this.specificationChanged.dispatch),this.displayState.linkedSegmentationGroup.changed.add(()=>this.updateDataSubsourceActivations()),this.tabs.add("rendering",{label:"Render",order:-100,getter:()=>new ok(this)}),this.tabs.add("segments",{label:"Seg.",order:-50,getter:()=>new jR(this)});const t=this.registerDisposer((0,A.Uq)(n=>n===void 0,[this.displayState.segmentationGroupState.value.graph]));this.tabs.add("graph",{label:"Graph",order:-25,getter:()=>new dI(this),hidden:t}),this.tabs.default="rendering"}bindSegmentListWidth(e){return Vr(this.displayState,e)}get volumeOptions(){return{volumeType:gt.SEGMENTATION}}activateDataSubsources(e){const t=[],n=this.displayState.linkedSegmentationGroup.root.value===this;let s;for(const r of e){if(this.addStaticAnnotations(r))continue;const{volume:o,mesh:a,segmentPropertyMap:l,segmentationGraph:c,local:d}=r.subsourceEntry.subsource;if(o instanceof Ht){switch(o.dataType){case I.FLOAT32:r.deactivate("Data type not compatible with segmentation layer");continue}r.activate(()=>r.addRenderLayer(new Iv(o,{...this.displayState,transform:r.getRenderLayerTransform(),renderScaleTarget:this.sliceViewRenderScaleTarget,renderScaleHistogram:this.sliceViewRenderScaleHistogram,localPosition:this.localPosition})),this.displayState.segmentationGroupState.value)}else a!==void 0?r.activate(()=>{const u={...this.displayState,transform:r.getRenderLayerTransform()};if(a instanceof pi)r.addRenderLayer(new Sa(this.manager.chunkManager,a,u));else if(a instanceof ba)r.addRenderLayer(new xd(this.manager.chunkManager,a,u));else{const h=new wI(this.manager.chunkManager,a,u);r.addRenderLayer(new Pd(h.addRef())),r.addRenderLayer(new pv(h))}},this.displayState.segmentationGroupState.value):l!==void 0?n?(r.activate(()=>{}),t.push(l)):r.deactivate("Not supported on non-root linked segmentation layers"):c!==void 0?n?s!==void 0?r.deactivate("Only one segmentation graph is supported"):(s=c,r.activate(u=>{const h=c.connect(this);u.registerDisposer(()=>{h.dispose(),this.graphConnection.value=void 0});const f={...this.displayState,transform:r.getRenderLayerTransform()},m=h.createRenderLayers(this.manager.chunkManager,f,this.localPosition);this.graphConnection.value=h;for(const g of m)r.addRenderLayer(g)})):r.deactivate("Not supported on non-root linked segmentation layers"):d===ks.equivalences?n?s!==void 0?r.deactivate("Only one segmentation graph is supported"):(s=this.displayState.originalSegmentationGroupState.localGraph,r.activate(u=>{this.graphConnection.value=u.registerDisposer(s.connect(this)),u.registerDisposer(()=>{this.graphConnection.value=void 0})})):r.deactivate("Not supported on non-root linked segmentation layers"):r.deactivate("Not compatible with segmentation layer")}this.displayState.originalSegmentationGroupState.segmentPropertyMap.value=eI(this.manager.chunkManager,t),this.displayState.originalSegmentationGroupState.graph.value=s}getLegacyDataSourceSpecifications(e,t,n,s){const r=super.getLegacyDataSourceSpecifications(e,t,n,s),o=(0,p.MM)(t,LT,l=>l===null?null:(0,p.zr)(l)),a=(0,p.MM)(t,PT,l=>l===null?null:(0,p.zr)(l));if(o!==void 0||a!==void 0)for(const l of r)l.enableDefaultSubsources=!1,l.subsources=new Map([["default",{enabled:!0}],["bounds",{enabled:!0}]]);return o!=null&&r.push(Ir(this.manager.dataSourceProviderRegistry.convertLegacyUrl({url:o,type:"mesh"}))),a!=null&&r.push(Ir(this.manager.dataSourceProviderRegistry.convertLegacyUrl({url:a,type:"skeletons"}))),t[ra]!==void 0&&s.find(l=>l.url===_c)===void 0&&r.push({url:_c,enableDefaultSubsources:!0,transform:{outputSpace:xi,sourceRank:0,transform:void 0,inputSpace:xi},subsources:new Map}),r}restoreState(e){super.restoreState(e),this.displayState.selectedAlpha.restoreState(e[Hc]),this.displayState.saturation.restoreState(e[Yc]),this.displayState.notSelectedAlpha.restoreState(e[Jc]),this.displayState.hoverHighlight.restoreState(e[Qc]),this.displayState.objectAlpha.restoreState(e[jc]),this.displayState.baseSegmentColoring.restoreState(e[Kc]),this.displayState.silhouetteRendering.restoreState(e[id]),this.displayState.ignoreNullVisibleSet.restoreState(e[Xc]);const{skeletonRenderingOptions:t}=this.displayState;t.restoreState(e[oa]);const n=e[AT];n!==void 0&&t.shader.restoreState(n),this.displayState.renderScaleTarget.restoreState(e[td]),this.anchorSegment.restoreState(e[Jg]),this.sliceViewRenderScaleTarget.restoreState(e[nd]);const s=(0,p.MM)(e,Wg,p.zr);s!==void 0&&this.displayState.linkedSegmentationGroup.linkByName(s);const r=(0,p.MM)(e,Hg,o=>o===!1?void 0:(0,p.zr)(o),s);r!==void 0&&this.displayState.linkedSegmentationColorGroup.linkByName(r),this.displayState.segmentationGroupState.value.restoreState(e),this.displayState.segmentationColorGroupState.value.restoreState(e)}toJSON(){const e=super.toJSON();e[Hc]=this.displayState.selectedAlpha.toJSON(),e[Jc]=this.displayState.notSelectedAlpha.toJSON(),e[Yc]=this.displayState.saturation.toJSON(),e[jc]=this.displayState.objectAlpha.toJSON(),e[Qc]=this.displayState.hoverHighlight.toJSON(),e[Kc]=this.displayState.baseSegmentColoring.toJSON(),e[Xc]=this.displayState.ignoreNullVisibleSet.toJSON(),e[id]=this.displayState.silhouetteRendering.toJSON(),e[Jg]=this.anchorSegment.toJSON(),e[oa]=this.displayState.skeletonRenderingOptions.toJSON(),e[td]=this.displayState.renderScaleTarget.toJSON(),e[nd]=this.sliceViewRenderScaleTarget.toJSON();const{linkedSegmentationGroup:t,linkedSegmentationColorGroup:n}=this.displayState;return e[Wg]=t.toJSON(),n.root.value!==t.root.value&&(e[Hg]=n.toJSON()??!1),e[ra]=this.displayState.originalSegmentationGroupState.localGraph.toJSON(),t.root.value===this&&Object.assign(e,this.displayState.segmentationGroupState.value.toJSON()),n.root.value===this&&Object.assign(e,this.displayState.segmentationColorGroupState.value.toJSON()),e}transformPickedValue(e){return e==null?e:Pm(this.displayState,e,!0)}handleAction(e,t){switch(e){case"recolor":{this.displayState.segmentationColorGroupState.value.segmentColorHash.randomize();break}case"clear-segments":{if(!this.pick.value)break;this.displayState.segmentationGroupState.value.visibleSegments.clear();break}case"select":case"star":{if(!this.pick.value)break;const{segmentSelectionState:n}=this.displayState;if(n.hasSelectedSegment){const s=n.selectedSegment,r=this.displayState.segmentationGroupState.value,o=e==="select"?r.visibleSegments:r.selectedSegments,a=!o.has(s);(a||t.segmentationToggleSegmentState===void 0)&&(t.segmentationToggleSegmentState=a),t.defer(()=>{t.segmentationToggleSegmentState===a&&o.set(s,a)})}break}}}selectionStateFromJson(e,t){super.selectionStateFromJson(e,t);const n=new M.R;let{value:s}=e;typeof s=="number"&&(s=s.toString()),typeof s!="string"||!n.tryParseString(s)?e.value=void 0:e.value=n}selectionStateToJson(e,t){const n=super.selectionStateToJson(e,t),{value:s}=e;return s instanceof hi?t?n.value={key:s.key.toString(),value:s.value?s.value.toString():void 0,label:s.label}:n.value=(s.value||s.key).toString():s instanceof M.R&&(n.value=s.toString()),n}displaySegmentationSelection(e,t,n){const{value:s}=e;let r;if((typeof s=="number"||typeof s=="string")&&(r=new M.R,!r.tryParseString(s.toString())))return!1;if(s instanceof M.R)r=s.clone();else if(s instanceof hi)r=s.key.clone();else return!1;const{displayState:o}=this,a=ji(o,r),{segmentEquivalences:l,segmentPropertyMap:{value:c}}=this.displayState.segmentationGroupState.value,d=l.get(r),u=yd(this.displayState,a);if(Vs(o,n,n.redraw),n.registerDisposer(Vr(o,u)),u.classList.add("neuroglancer-selection-details-segment"),t.appendChild(u),c!==void 0){const{inlineProperties:h}=c.segmentPropertyMap;if(h!==void 0){const f=c.getSegmentInlineIndex(d);if(f!==-1){for(const m of h.properties)if(m.type!=="label"){if(m.type==="description"){const g=m.values[f];if(!g)continue;const v=document.createElement("div");v.classList.add("neuroglancer-selection-details-segment-description"),v.textContent=g,t.appendChild(v)}else if(m.type==="number"||m.type==="string"){const g=m.values[f];if(m.type==="number"?Number.isNaN(g):!g)continue;const v=document.createElement("div");v.classList.add("neuroglancer-selection-details-segment-property");const y=document.createElement("div");y.classList.add("neuroglancer-selection-details-segment-property-name"),y.textContent=m.id,m.description&&(y.title=m.description);const S=document.createElement("div");S.classList.add("neuroglancer-selection-details-segment-property-value"),S.textContent=g.toString(),v.appendChild(y),v.appendChild(S),t.appendChild(v)}}}}}return!0}displaySelectionState(e,t,n){let s=this.displaySegmentationSelection(e,t,n);return super.displaySelectionState(e,t,n)&&(s=!0),s}moveToSegment(e){for(const t of this.renderLayers){if(!(t instanceof xd||t instanceof Sa))continue;const n=t.displayState.transform.value;if(n.error!==void 0)return;const{rank:s,globalToRenderLayerDimensions:r}=n,{globalPosition:o}=this.manager.root,a=new Float32Array(s),l=[];for(let d=0;d<s;d++)l[r[d]]=d;(0,z.b8)(a,o.value,l);const c=t instanceof Sa?t.getObjectPosition(e,a):t.getObjectPosition(e);if(c!==void 0){this.setLayerPosition(n,c);return}}Se.showTemporaryMessage(`No position information loaded for segment ${e}`)}}Rt.type="segmentation",Rt.typeAbbreviation="seg",Rt.supportsPickOption=!0,HT(Rt),Ui(Rt),_g(gt.SEGMENTATION,Rt),ia(i=>{if(i.mesh!==void 0)return{layerConstructor:Rt,priority:1}}),Fa(Rt,i=>({shaderControlState:i.displayState.skeletonRenderingOptions.shaderControlState}),jg),FR(Rt),NR(Rt);/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Sk extends D.O8{constructor(e){super(),this.ref=e,this.element=document.createElement("label"),this.selectElement=document.createElement("select"),this.registerDisposer(e);const{element:t,selectElement:n}=this;t.appendChild(n),this.updateView(),this.registerEventListener(n,"change",()=>this.updateModel()),this.registerDisposer(this.ref.changed.add((0,xe.A)(()=>this.updateView(),0)))}updateModel(){this.ref.layerName=this.selectElement.value||void 0}updateView(){const{selectElement:e,ref:t}=this,{filter:n}=t;Ae(e);const s=document.createElement("option");e.appendChild(s);for(const r of this.ref.layerManager.managedLayers)if(n(r)){const o=document.createElement("option"),{name:a}=r;o.textContent=a,o.value=a,e.appendChild(o)}e.value=t.layerName||""}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const bk="points",Zd="annotations",Iy="annotationProperties",Ry="annotationRelationships",ky="crossSectionAnnotationSpacing",Ly="projectionAnnotationSpacing",Py="shader",Ay="shaderControls";function wk(i,e){e!==void 0&&(0,p.$v)(e,(t,n)=>{i.add({type:Je.POINT,id:""+n,point:(0,p.f4)(t),properties:[]})})}function Ck(i){const e=i.layer;return e===null||e instanceof Rt}function xk(i){if(i===void 0)return null;const e=i.layer;return e===null||!(e instanceof Rt)?null:e.displayState}const My="linkedSegmentationLayer",Ny="filterBySegmentation",Oy="ignoreNullSegmentFilter";class Ek extends D.O8{constructor(e,t,n){super(),this.layerManager=e,this.annotationStates=t,this.annotationDisplayState=n,this.changed=new j.IY,this.curGeneration=-1,this.wasLoading=void 0,this.map=new Map,this.registerDisposer(t.changed.add(()=>this.update())),this.registerDisposer(t.isLoadingChanged.add(()=>this.update())),this.update()}update(){const e=this.annotationStates.changed.count,t=this.annotationStates.isLoading;if(this.curGeneration===e&&t===this.wasLoading)return;this.wasLoading=t,this.curGeneration=e;const{map:n}=this;let s=!1;for(const r of this.annotationStates.relationships){let o=n.get(r);o===void 0&&(o=this.addRelationship(r),s=!0),o.seenGeneration=e}if(!t){const{relationshipStates:r}=this.annotationDisplayState;for(const[o,a]of n)a.seenGeneration!==e&&(n.delete(o),r.delete(o),s=!0)}s&&this.changed.dispatch()}addRelationship(e){const t=this.annotationDisplayState.relationshipStates.get(e),n=new IT(this.layerManager.addRef(),Ck);n.registerDisposer(n.changed.add(()=>{t.segmentationState.value=n.layerName===void 0?void 0:xk(n.layer)}));const{showMatches:s}=t,r={layerRef:n,showMatches:s,seenGeneration:-1};return n.changed.add(this.changed.dispatch),s.changed.add(this.changed.dispatch),this.map.set(e,r),r}get(e){return this.update(),this.map.get(e)}unbind(e){e.layerRef.changed.remove(this.changed.dispatch),e.showMatches.changed.remove(this.changed.dispatch)}reset(){for(const e of this.map.values())e.showMatches.reset()}toJSON(){const{map:e}=this;if(e.size===0)return{};let t;const n=[];for(const[s,r]of e){r.showMatches.value&&n.push(s);const{layerName:o}=r.layerRef;o!==void 0&&((t=t||{})[s]=o)}return n.sort(),{[My]:t,[Ny]:n.length===0?void 0:n}}restoreState(e){const{isLoading:t}=this.annotationStates;(0,p.MM)(e,My,n=>{typeof n=="string"&&(n={segments:n}),(0,p.Rf)(n);for(const s of Object.keys(n)){const r=(0,p.zr)(n[s]);let o=this.map.get(s);if(o===void 0){if(!t)continue;o=this.addRelationship(s)}o.layerRef.layerName=r}for(const[s,r]of this.map)Object.prototype.hasOwnProperty.call(n,s)||(r.layerRef.layerName=void 0)}),(0,p.MM)(e,Ny,n=>{typeof n=="boolean"&&(n=n===!0?["segments"]:[]);for(const s of(0,p.si)(n)){let r=this.map.get(s);if(r===void 0){if(!t)continue;r=this.addRelationship(s)}r.showMatches.value=!0}})}disposed(){const{map:e}=this;for(const t of e.values())this.unbind(t);e.clear(),super.disposed()}}class Tk extends D.O8{constructor(e,t){super(),this.relationship=e,this.state=t,this.element=document.createElement("label"),this.seenGeneration=-1;const{element:n}=this,s=this.registerDisposer(new Un(t.showMatches)),r=new Sk(t.layerRef);n.appendChild(s.element),n.appendChild(document.createTextNode(e)),n.appendChild(r.element)}}class Dk extends D.O8{constructor(e){super(),this.linkedSegmentationLayers=e,this.widgets=new Map,this.element=document.createElement("div"),this.element.style.display="contents";const t=this.registerCancellable((0,je.t)(()=>this.updateView()));this.registerDisposer(this.linkedSegmentationLayers.annotationStates.changed.add(t)),this.updateView()}updateView(){const{linkedSegmentationLayers:e}=this,{annotationStates:t}=e,n=t.changed.count,{widgets:s}=this;function*r(){for(const o of t.relationships){let a=s.get(o);a===void 0&&(a=new Tk(o,e.get(o))),a.seenGeneration=n,yield a.element}}for(const[o,a]of s)a.seenGeneration!==n&&(a.dispose(),s.delete(o));Zt(this.element,r.call(this))}disposed(){super.disposed();for(const e of this.widgets.values())e.dispose()}}const Ik=Wd(Ln);class Qi extends Ik{constructor(e){super(e),this.localAnnotationsJson=void 0,this.pointAnnotationsJson=void 0,this.linkedSegmentationLayers=this.registerDisposer(new Ek(this.manager.rootLayers,this.annotationStates,this.annotationDisplayState)),this.linkedSegmentationLayers.changed.add(this.specificationChanged.dispatch),this.annotationDisplayState.ignoreNullSegmentFilter.changed.add(this.specificationChanged.dispatch),this.annotationCrossSectionRenderScaleTarget.changed.add(this.specificationChanged.dispatch),this.annotationProjectionRenderScaleTarget.changed.add(this.specificationChanged.dispatch),this.tabs.add("rendering",{label:"Rendering",order:-100,getter:()=>new kk(this)}),this.tabs.default="annotations"}disposed(){const{localAnnotations:e}=this;e!==void 0&&e.dispose(),super.disposed()}restoreState(e){super.restoreState(e),this.linkedSegmentationLayers.restoreState(e),this.localAnnotationsJson=e[Zd],this.localAnnotationProperties=(0,p.MM)(e,Iy,bh),this.localAnnotationRelationships=(0,p.MM)(e,Ry,p.si,["segments"]),this.pointAnnotationsJson=e[bk],this.annotationCrossSectionRenderScaleTarget.restoreState(e[ky]),this.annotationProjectionRenderScaleTarget.restoreState(e[Ly]),this.annotationDisplayState.ignoreNullSegmentFilter.restoreState(e[Oy]),this.annotationDisplayState.shader.restoreState(e[Py]),this.annotationDisplayState.shaderControls.restoreState(e[Ay])}getLegacyDataSourceSpecifications(e,t,n,s){if(Object.prototype.hasOwnProperty.call(t,"source"))return super.getLegacyDataSourceSpecifications(e,t,n,s);const r=(0,p.MM)(t,"voxelSize",a=>(0,p.Xu)(new Float64Array(3),a,l=>(0,p.Mo)(l)/1e9)),o=["m","m","m"];if(r!==void 0){const a=ke({rank:3,units:o,scales:r,names:["x","y","z"]});n===void 0?n={outputSpace:a,sourceRank:3,transform:void 0,inputSpace:a}:n={...n,inputSpace:a}}return[{url:hg,transform:n,enableDefaultSubsources:!0,subsources:new Map}]}activateDataSubsources(e){let t=!1,n;for(const r of e){const{subsourceEntry:o}=r,{local:a}=o.subsource,l=d=>n!==void 0&&(0,p.JB)(d)!==(0,p.JB)(n)?(r.deactivate("Annotation properties are not compatible"),!1):(n=d,!0);if(a===ks.annotations){if(t){r.deactivate("Only one local annotations source per layer is supported");continue}if(t=!0,!l(this.localAnnotationProperties??[]))continue;r.activate(d=>{const u=this.localAnnotations=new wh(r.loadedDataSource.transform,this.localAnnotationProperties??[],this.localAnnotationRelationships);try{u.restoreState(this.localAnnotationsJson)}catch{}d.registerDisposer(()=>{u.dispose(),this.localAnnotations=void 0}),d.registerDisposer(this.localAnnotations.changed.add(this.specificationChanged.dispatch));try{wk(this.localAnnotations,this.pointAnnotationsJson)}catch{}this.pointAnnotationsJson=void 0,this.localAnnotationsJson=void 0;const h=new Uo({localPosition:this.localPosition,transform:d.registerDisposer(Hh(this.manager.root.coordinateSpace,this.localPosition.coordinateSpace,r.loadedDataSource.transform,void 0)),source:u.addRef(),displayState:this.annotationDisplayState,dataSource:r.loadedDataSource.layerDataSource,subsourceIndex:r.subsourceIndex,subsourceId:o.id,role:si.ANNOTATION});this.addAnnotationLayerState(h,r)});continue}const{annotation:c}=o.subsource;if(c!==void 0){if(!l(c.properties))continue;r.activate(()=>{const d=new Uo({localPosition:this.localPosition,transform:r.getRenderLayerTransform(),source:c,displayState:this.annotationDisplayState,dataSource:r.loadedDataSource.layerDataSource,subsourceIndex:r.subsourceIndex,subsourceId:o.id,role:si.ANNOTATION});this.addAnnotationLayerState(d,r)});continue}r.deactivate("Not compatible with annotation layer")}const s=this.annotationDisplayState.annotationProperties.value;(0,p.JB)(s)!==(0,p.JB)(n)&&(this.annotationDisplayState.annotationProperties.value=n)}initializeAnnotationLayerViewTab(e){const t=e.registerDisposer((0,A.ol)(s=>s.some(r=>r.source instanceof Tr),this.annotationStates)),n=e.registerDisposer(new zt(t,(s,r,o)=>{if(s){{const a=o.registerDisposer(new aa(this.annotationCrossSectionRenderScaleHistogram,this.annotationCrossSectionRenderScaleTarget));a.label.textContent="Spacing (cross section)",r.appendChild(a.element)}{const a=o.registerDisposer(new aa(this.annotationProjectionRenderScaleHistogram,this.annotationProjectionRenderScaleTarget));a.label.textContent="Spacing (projection)",r.appendChild(a.element)}}}));e.element.insertBefore(n.element,e.element.firstChild);{const s=e.registerDisposer(new Un(this.annotationDisplayState.ignoreNullSegmentFilter)),r=document.createElement("label");r.appendChild(document.createTextNode("Ignore null related segment filter")),r.title="Display all annotations if filtering by related segments is enabled but no segments are selected",r.appendChild(s.element),e.element.appendChild(r)}e.element.appendChild(e.registerDisposer(new Dk(this.linkedSegmentationLayers)).element)}toJSON(){const e=super.toJSON();e[ky]=this.annotationCrossSectionRenderScaleTarget.toJSON(),e[Ly]=this.annotationProjectionRenderScaleTarget.toJSON(),this.localAnnotations!==void 0?e[Zd]=this.localAnnotations.toJSON():this.localAnnotationsJson!==void 0&&(e[Zd]=this.localAnnotationsJson),e[Iy]=Gb(this.localAnnotationProperties);const{localAnnotationRelationships:t}=this;return e[Ry]=t.length===1&&t[0]==="segments"?void 0:t,e[Oy]=this.annotationDisplayState.ignoreNullSegmentFilter.toJSON(),e[Py]=this.annotationDisplayState.shader.toJSON(),e[Ay]=this.annotationDisplayState.shaderControls.toJSON(),Object.assign(e,this.linkedSegmentationLayers.toJSON()),e}}Qi.type="annotation",Qi.typeAbbreviation="ann";function Vy(i){return new _a({shaderError:i.annotationDisplayState.shaderError,fragmentMain:i.annotationDisplayState.shader,shaderControlState:i.annotationDisplayState.shaderControls})}class Rk extends $r{constructor(e){super(),this.layer=e,this.codeWidget=this.registerDisposer(Vy(this.layer)),this.content.appendChild(this.codeWidget.element),this.codeWidget.textEditor.refresh()}}class kk extends Gt{constructor(e){super(),this.layer=e,this.codeWidget=this.registerDisposer(Vy(this.layer));const{element:t}=this;t.classList.add("neuroglancer-annotation-rendering-tab"),t.appendChild(this.registerDisposer(new zt(e.annotationDisplayState.annotationProperties,(r,o)=>{if(r===void 0||r.length===0)return;const a=document.createElement("div");o.appendChild(a),a.classList.add("neuroglancer-annotation-shader-property-list");for(const l of r){const c=document.createElement("div");c.classList.add("neuroglancer-annotation-shader-property");const d=document.createElement("span");d.classList.add("neuroglancer-annotation-shader-property-type"),d.textContent=l.type;const u=document.createElement("span");u.classList.add("neuroglancer-annotation-shader-property-identifier"),u.textContent=`prop_${l.identifier}`,c.appendChild(d),c.appendChild(u);const{description:h}=l;h!==void 0&&(c.title=h),a.appendChild(c)}})).element);const n=document.createElement("div");n.className="neuroglancer-segmentation-dropdown-skeleton-shader-header";const s=document.createElement("div");s.style.flex="1",s.textContent="Annotation shader:",n.appendChild(s),n.appendChild(Va({title:"Show larger editor view",onClick:()=>{new Rk(this.layer)}})),n.appendChild(Oa({title:"Documentation on annotation rendering",href:"https://github.com/google/neuroglancer/blob/master/src/annotation/rendering.md"})),t.appendChild(n),t.appendChild(this.codeWidget.element),t.appendChild(this.registerDisposer(new Ba(e.annotationDisplayState.shaderControls,this.layer.manager.root.display,this.layer,{visibility:this.visibility})).element)}}Ui(Qi),Ui(Qi,"pointAnnotation"),ia(i=>{if(i.local===ks.annotations)return{layerConstructor:Qi,priority:100};if(i.annotation!==void 0)return{layerConstructor:Qi,priority:1}}),Fa(Qi,i=>({shaderControlState:i.annotationDisplayState.shaderControls}));/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var eu=(i=>(i[i.DEFAULT=0]="DEFAULT",i[i.ADDITIVE=1]="ADDITIVE",i))(eu||{});const Lk=new Map([[0,i=>{i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA)}],[1,i=>{i.blendFunc(i.SRC_ALPHA,i.ONE)}]]);function Pk(i=0){return new Mi.F(eu,i)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const _y=`#uicontrol invlerp normalized
void main() {
  emitGrayscale(normalized());
}
`;function Ak(i=_y){return mo(i)}function By(i,e){i.addFragmentCode(`
#define VOLUME_RENDERING false

void emitRGBA(vec4 rgba) {
  emit(vec4(rgba.rgb, rgba.a * uOpacity));
}
void emitRGB(vec3 rgb) {
  emit(vec4(rgb, uOpacity));
}
void emitGrayscale(float value) {
  emit(vec4(value, value, value, uOpacity));
}
void emitTransparent() {
  emit(vec4(0.0, 0.0, 0.0, 0.0));
}
void emitIntensity(float value) {
}
`),i.addFragmentCode(Es),Cs(e,i),i.setFragmentMainFunction(ls(e.parseResult.code))}class Mk extends Vd{constructor(e,t){const{opacity:n,blendMode:s,shaderControlState:r}=t;super(e,{...t,fallbackShaderParameters:new A.B0(Bo(br(_y,{imageData:{dataType:e.dataType,channelRank:t.channelCoordinateSpace?.value?.rank??0}}))),encodeShaderParameters:o=>o.key,shaderParameters:r.builderState,dataHistogramSpecifications:r.histogramSpecifications}),this.shaderControlState=r,this.opacity=n,this.blendMode=s,this.registerDisposer(n.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(s.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(r.changed.add(this.redrawNeeded.dispatch))}defineShader(e,t){if(t.parseResult.errors.length!==0)throw new Error("Invalid UI control specification");e.addUniform("highp float","uOpacity"),By(e,t)}initializeShader(e,t,n){const{gl:s}=this;s.uniform1f(t.uniform("uOpacity"),this.opacity.value),Oi(s,t,this.shaderControlState,n.parseResult.controls)}setGLBlendMode(e,t){const n=this.blendMode.value;n===eu.ADDITIVE||t>0?(e.enable(e.BLEND),Lk.get(n)(e)):e.disable(WebGL2RenderingContext.BLEND)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Nk(i=1){return new A.DN(i,p.zo)}var yi=(i=>(i[i.OFF=0]="OFF",i[i.ON=1]="ON",i[i.MAX=2]="MAX",i[i.MIN=3]="MIN",i))(yi||{});function Ok(i=0){return new Mi.F(yi,i)}function Wr(i){return i===2||i===3}function Fy(i){return Wr(i.mode.value)}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Vk="volume_rendering/VolumeRenderingRenderLayer",_k="volume_rendering/VolumeRenderingRenderLayer/update",Bk=!1,Fk=w.w0.create();function Uk(i,e,t){let n=0,s=0;for(let c=0;c<3;++c){const d=i[16+c],u=d*e[c],h=d*t[c];n+=Math.min(u,h),s+=Math.max(u,h)}const r=-i[19],o=Math.max(r,n),a=i[23],l=Math.min(a,s);return{near:r,far:a,adjustedNear:o,adjustedFar:l}}function Uy(i,e,t,n,s,r){if(n.length===0)return;const{viewMatrix:o,projectionMat:a,displayDimensionRenderInfo:l}=i,{voxelPhysicalScales:c}=l,d=(0,w.xK)(c),u=(0,w.sJ)(a),f=(u/t)**3,m=w.w0.determinant((0,w._A)(Fk,o)),g={spatialScales:new Map,activeIndex:-1},v=k=>{const T=n[k];return Math.abs(T.chunkLayout.detTransform*m)};let y=n.length-1,S=v(y);for(let k=y;k>=0;--k){const T=v(k),L=Math.cbrt(T*d/m),_=u/Math.cbrt(T);g.spatialScales.set(L,_),T-f>=0&&(S=T,y=k),g.activeIndex=y}if(Bk){console.log(n);for(let k=0;k<n.length;++k){const T=v(k),L=u/Math.cbrt(T);console.log(`scaleIndex=${k} viewVolume=${T} bestScaleIndex=${y} actualViewVolume=${f}, desiredSamples=${L}, difference=${T-f}`)}}const x=Math.cbrt(S*d/m),b=u/Math.cbrt(S);let E=!0;const C=n[y];Yf(i,e,C,(k,T)=>{E&&(s(C,y,x,b,T,g),E=!1),r(C,y,k)})}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const $k=64,$y=1,Gk=10,tu=256,zk=2**14,Wk=!1,nu=Symbol("depthSamplerTextureUnit"),Hk=`
void emitRGBA(vec4 rgba) {
  float correctedAlpha = clamp(rgba.a * uBrightnessFactor * uGain, 0.0, 1.0);
  float weightedAlpha = correctedAlpha * computeOITWeight(correctedAlpha, depthAtRayPosition);
  outputColor += vec4(rgba.rgb * weightedAlpha, weightedAlpha);
  revealage *= 1.0 - correctedAlpha;
}
`,Jk=w.pB.create(),jk=new Float32Array(24);function Gy(){const i=Math.round($y+ft*xr);return[$y,i]}function zy(i){const e=Gy(),t=[2**e[0],2**e[1]-1];return Le(t,Math.round(i))}class Yk extends $i{get gl(){return this.multiscaleSource.chunkManager.gl}get isTransparent(){return!0}get isVolumeRendering(){return!0}getDataHistogramCount(){return this.dataHistogramSpecifications.visibleHistograms}constructor(e){super(),this.gain=e.gain,this.multiscaleSource=e.multiscaleSource,this.transform=e.transform,this.channelCoordinateSpace=e.channelCoordinateSpace,this.shaderControlState=e.shaderControlState,this.localPosition=e.localPosition,this.depthSamplesTarget=e.depthSamplesTarget,this.chunkResolutionHistogram=e.chunkResolutionHistogram,this.mode=e.mode,this.dataHistogramSpecifications=this.shaderControlState.histogramSpecifications,this.histogramIndexBuffer=this.registerDisposer(Ri(this.gl,WebGL2RenderingContext.ARRAY_BUFFER,()=>new Uint8Array(tu))),this.registerDisposer(this.chunkResolutionHistogram.visibility.add(this.visibility)),this.registerDisposer(this.dataHistogramSpecifications.producerVisibility.add(this.visibility));const t=this.registerDisposer((0,A.Uq)((o,a,l)=>({numChannelDimensions:o.rank,mode:a,dataHistogramChannelSpecifications:l}),[this.channelCoordinateSpace,this.mode,this.dataHistogramSpecifications.channels]));this.shaderGetter=vo(this,this.gl,{memoizeKey:"VolumeRenderingRenderLayer",parameters:e.shaderControlState.builderState,getContextKey:({emitter:o,chunkFormat:a,wireFrame:l})=>`${St(o)}:${a.shaderKey}:${l}`,shaderError:e.shaderError,extraParameters:t,defineShader:(o,{emitter:a,chunkFormat:l,wireFrame:c},d,u)=>{if(d.parseResult.errors.length!==0)throw new Error("Invalid UI control specification");fi(o),o.addFragmentCode(`
#define VOLUME_RENDERING true
`);let h=Hk,f=`
  emitAccumAndRevealage(outputColor, 1.0 - revealage, 0u);
`,m=`
void emitIntensity(float value) {
}
`,g="";if(Wr(u.mode)){const v=u.mode===yi.MIN?"1.0 - value":"value";o.addFragmentCode(`
float savedDepth = 0.0;
float savedIntensity = 0.0;
vec4 newColor = vec4(0.0);
float userEmittedIntensity = -100.0;
`),m=`
float convertIntensity(float value) {
  return clamp(${v}, 0.0, 1.0);
}
void emitIntensity(float value) {
  userEmittedIntensity = value;
}
float getIntensity() {
  float intensity = userEmittedIntensity > -100.0 ? userEmittedIntensity : defaultMaxProjectionIntensity;
  return convertIntensity(intensity);
}
`,h=`
void emitRGBA(vec4 rgba) {
  float alpha = clamp(rgba.a, 0.0, 1.0);
  newColor = vec4(rgba.rgb * alpha, alpha);
}
`,f=`
  gl_FragDepth = savedIntensity;
`,g=`
  float newIntensity = getIntensity();
  bool intensityChanged = newIntensity > savedIntensity;
  savedIntensity = intensityChanged ? newIntensity : savedIntensity; 
  savedDepth = intensityChanged ? depthAtRayPosition : savedDepth;
  outputColor = intensityChanged ? newColor : outputColor;
  emit(outputColor, savedDepth, savedIntensity, uPickId);
  defaultMaxProjectionIntensity = 0.0;
  userEmittedIntensity = -100.0;
`}if(a(o),o.addUniform("highp float","uNearLimitFraction"),o.addUniform("highp float","uFarLimitFraction"),o.addUniform("highp int","uMaxSteps"),o.addUniform("highp vec3","uTranslation"),o.addUniform("highp mat4","uModelViewProjectionMatrix"),o.addUniform("highp mat4","uInvModelViewProjectionMatrix"),o.addUniform("highp vec3","uChunkDataSize"),o.addUniform("highp float","uChunkNumber"),o.addUniform("highp vec3","uLowerClipBound"),o.addUniform("highp vec3","uUpperClipBound"),o.addUniform("highp float","uBrightnessFactor"),o.addUniform("highp float","uGain"),o.addUniform("highp uint","uPickId"),o.addVarying("highp vec4","vNormalizedPosition"),o.addTextureSampler("sampler2D","uDepthSampler",nu),o.addVertexCode($I),o.setVertexMain(`
vec3 boxVertex = getBoxFaceVertexPosition(gl_VertexID);
vec3 position = max(uLowerClipBound, min(uUpperClipBound, uTranslation + boxVertex * uChunkDataSize));
vNormalizedPosition = gl_Position = uModelViewProjectionMatrix * vec4(position, 1.0);
gl_Position.z = 0.0;
`),o.addFragmentCode(`
vec3 curChunkPosition;
float depthAtRayPosition;
vec4 outputColor;
float revealage;
void userMain();
`),gv(o,l,u.numChannelDimensions,"curChunkPosition"),o.addFragmentCode([m,h,`
void emitRGB(vec3 rgb) {
  emitRGBA(vec4(rgb, 1.0));
}
void emitGrayscale(float value) {
  emitRGBA(vec4(value, value, value, value));
}
void emitTransparent() {
  emitIntensity(0.0);
  emitRGBA(vec4(0.0, 0.0, 0.0, 0.0));
}
float computeDepthFromClipSpace(vec4 clipSpacePosition) {
  float NDCDepthCoord = clipSpacePosition.z / clipSpacePosition.w;
  return (NDCDepthCoord + 1.0) * 0.5;
}
vec2 computeUVFromClipSpace(vec4 clipSpacePosition) {
  vec2 NDCPosition = clipSpacePosition.xy / clipSpacePosition.w;
  return (NDCPosition + 1.0) * 0.5;
}
`]),c){let v=`
  emit(outputColor, 0u);
`;Wr(u.mode)&&(v=`
  emit(outputColor, 1.0, uChunkNumber, uPickId);
            `),o.setFragmentMainFunction(`
void main() {
  outputColor = vec4(uChunkNumber, uChunkNumber, uChunkNumber, 1.0);
  emitIntensity(uChunkNumber);
  ${v}
}
`)}else o.setFragmentMainFunction(`
void main() {
  vec2 normalizedPosition = vNormalizedPosition.xy / vNormalizedPosition.w;
  vec4 nearPointH = uInvModelViewProjectionMatrix * vec4(normalizedPosition, -1.0, 1.0);
  vec4 farPointH = uInvModelViewProjectionMatrix * vec4(normalizedPosition, 1.0, 1.0);
  vec3 nearPoint = nearPointH.xyz / nearPointH.w;
  vec3 farPoint = farPointH.xyz / farPointH.w;
  vec3 rayVector = farPoint - nearPoint;
  vec3 boxStart = max(uLowerClipBound, uTranslation);
  vec3 boxEnd = min(boxStart + uChunkDataSize, uUpperClipBound);
  float intersectStart = uNearLimitFraction;
  float intersectEnd = uFarLimitFraction;
  for (int i = 0; i < 3; ++i) {
    float startPt = nearPoint[i];
    float endPt = farPoint[i];
    float boxLower = boxStart[i];
    float boxUpper = boxEnd[i];
    float r = rayVector[i];
    float startFraction;
    float endFraction;
    if (startPt >= boxLower && startPt <= boxUpper) {
      startFraction = 0.0;
    } else {
      startFraction = min((boxLower - startPt) / r, (boxUpper - startPt) / r);
    }
    if (endPt >= boxLower && endPt <= boxUpper) {
      endFraction = 1.0;
    } else {
      endFraction = max((boxLower - startPt) / r, (boxUpper - startPt) / r);
    }
    intersectStart = max(intersectStart, startFraction);
    intersectEnd = min(intersectEnd, endFraction);
  }
  float stepSize = (uFarLimitFraction - uNearLimitFraction) / float(uMaxSteps - 1);
  int startStep = int(floor((intersectStart - uNearLimitFraction) / stepSize));
  int endStep = min(uMaxSteps, int(floor((intersectEnd - uNearLimitFraction) / stepSize)) + 1);
  outputColor = vec4(0, 0, 0, 0);
  revealage = 1.0;
  for (int rayStep = startStep; rayStep < endStep; ++rayStep) {
    vec3 position = mix(nearPoint, farPoint, uNearLimitFraction + float(rayStep) * stepSize);
    vec4 clipSpacePosition = uModelViewProjectionMatrix * vec4(position, 1.0);
    depthAtRayPosition = computeDepthFromClipSpace(clipSpacePosition);
    vec2 uv = computeUVFromClipSpace(clipSpacePosition);
    float depthInBuffer = texture(uDepthSampler, uv).r;
    bool rayPositionBehindOpaqueObject = (1.0 - depthAtRayPosition) < depthInBuffer;
    if (rayPositionBehindOpaqueObject) {
      break;
    }
    curChunkPosition = position - uTranslation;
    userMain();
    ${g}
  }
  ${f}
}
`);o.addFragmentCode(Es),Cs(d,o),o.addFragmentCode(`
#define main userMain
`+ls(d.parseResult.code)+`
#undef main
`)}}),this.histogramShaderGetter=vo(this,this.gl,{memoizeKey:"VolumeRenderingRenderLayerHistogram",parameters:e.shaderControlState.builderState,getContextKey:({chunkFormat:o})=>`${o.shaderKey}`,shaderError:e.shaderError,extraParameters:t,defineShader:(o,{chunkFormat:a},l,c)=>{o.addOutputBuffer("vec4","outputValue",null),o.addUniform("highp vec3","uChunkDataSize"),o.addUniform("highp int","uHistogramIndex"),o.addAttribute("float","aInput1"),o.addVertexCode(`
vec3 chunkSamplePosition;
          `);const d=c.numChannelDimensions;a.defineShader(o,d,!0);const{dataType:u}=a;let h="",f="";if(d===0)h+="highp int ignoredChannelIndex";else for(let S=0;S<d;++S)S!==0&&(h+=", "),h+=`highp int channelIndex${S}`,f+=`, channelIndex${S}`;const m=`
${vt(u)} getDataValue(${h}) {
  highp ivec3 p = ivec3(max(vec3(0.0, 0.0, 0.0), min(floor(chunkSamplePosition), uChunkDataSize - 1.0)));
  return getDataValueAt(p${f});
}`;o.addVertexCode(m),d<=1&&o.addVertexCode(`
${vt(u)} getDataValue() { return getDataValue(0); }
`);const g=c.dataHistogramChannelSpecifications,v=g.length;let y=`
  float x;
  switch (uHistogramIndex) {`;for(let S=0;S<v;++S){const{channel:x}=g[S],b=`getDataValue(${x.join(",")})`,E=`invlerpForHistogram${S}`;o.addVertexCode(us(o,E,u,!1)),o.addVertexCode(`
float getHistogramValue${S}() {
  return invlerpForHistogram${S}(${b});
}
`),y+=`
  case ${S}:
    x = getHistogramValue${S}();
    break;`}y+=`
  }
`,o.addVertexCode(Ip),o.setVertexMain(`
  vec3 rand3val = vec3(
    simpleFloatHash(vec2(aInput1 + float(gl_VertexID), float(gl_InstanceID))),
    simpleFloatHash(vec2(aInput1 + float(gl_VertexID) + 10.0, 5.0 + float(gl_InstanceID))),
    simpleFloatHash(vec2(aInput1 + float(gl_VertexID) + 20.0, 15.0 + float(gl_InstanceID))));
  chunkSamplePosition = rand3val * (uChunkDataSize - 1.0);
${y}
  if (x == 0.0) {
    gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
  }
  else {
    if (x < 0.0) x = 0.0;
    else if (x > 1.0) x = 1.0;
    else x = (1.0 + x * 253.0) / 255.0;
    gl_Position = vec4(2.0 * (x * 255.0 + 0.5) / 256.0 - 1.0, 0.0, 0.0, 1.0);
  }
  gl_PointSize = 1.0;`),o.setFragmentMain(`
outputValue = vec4(1.0, 1.0, 1.0, 1.0);
          `)}}),this.vertexIdHelper=this.registerDisposer(jn.get(this.gl)),this.registerDisposer(this.depthSamplesTarget.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.gain.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.shaderControlState.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.localPosition.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.transform.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.mode.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(this.shaderControlState.fragmentMain.changed.add(this.redrawNeeded.dispatch));const{chunkManager:n}=this.multiscaleSource,s=this.registerDisposer(new Cr(this.layerChunkProgressInfo)),r=n.rpc;s.RPC_TYPE_ID=Vk,s.initializeCounterpart(r,{chunkManager:n.rpcId,localPosition:this.registerDisposer(ut.makeFromExisting(r,this.localPosition)).rpcId,renderScaleTarget:this.registerDisposer(ut.makeFromExisting(r,this.depthSamplesTarget)).rpcId}),this.backend=s}get dataType(){return this.multiscaleSource.dataType}attach(e){super.attach(e),e.state={sources:e.registerDisposer((0,A.no)((t,n,s)=>{const r=Ko(s,n,o=>this.multiscaleSource.getSources(o),e.messages,this);for(const o of r)for(const a of o)t.registerDisposer(a.source);return e.view.flushBackendProjectionParameters(),this.backend.rpc.invoke(_k,{layer:this.backend.rpcId,view:e.view.rpcId,sources:Yo(r),displayDimensionRenderInfo:s}),this.redrawNeeded.dispatch(),r},this.transform,e.view.displayDimensionRenderInfo))}}get chunkManager(){return this.multiscaleSource.chunkManager}draw(e,t){if(!e.emitColor)return;const n=t.state.sources.value;if(n.length===0)return;let s=0,r=0,o={spatialScales:new Map,activeIndex:0},a=null,l,c;const d=w.eR.create(),{gl:u}=this;this.vertexIdHelper.enable();const{chunkResolutionHistogram:h}=this;h.begin(this.chunkManager.chunkQueueManager.frameNumberCounter.frameNumber);const f=()=>{if(Wr(this.mode.value))if(u.disable(WebGL2RenderingContext.BLEND),e.bindMaxProjectionBuffer!==void 0)e.bindMaxProjectionBuffer();else throw new Error("bindMaxProjectionBuffer is undefined in VolumeRenderingRenderLayer");else e.bindFramebuffer();u.enable(WebGL2RenderingContext.DEPTH_TEST)},m=()=>{if(a===null)return;a.unbindTransferFunctionTextures(),l!==null&&l.endDrawing(u,a);const R=a.textureUnit(nu);if(u.activeTexture(WebGL2RenderingContext.TEXTURE0+R),u.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null),S!==0||x!==0){let P=o.spatialScales.size-1;const V=new Set([zy(r)]);o.spatialScales.forEach(($,Q)=>{const K=zy($);P!==o.activeIndex&&!V.has(K)&&(h.add(Q,$,0,Gk,!0),V.add(K)),P--}),h.add(s,r,S,x)}};let g=!0;const{projectionParameters:v}=e;let y,S=0,x=0,b,E=1;const C=this.multiscaleSource.rank,k=w.eR.create(),T=this.getDataHistogramCount()>0&&!e.wireFrame&&!e.sliceViewsPresent&&!e.isContinuousCameraMotionInProgress;u.enable(WebGL2RenderingContext.CULL_FACE),u.cullFace(WebGL2RenderingContext.FRONT);const L=[],_=Wr(this.mode.value)?e.pickIDs.register(this):0;if(Uy(e.projectionParameters,this.localPosition.value,this.depthSamplesTarget.value,n[0],(R,P,V,$,Q,K)=>{s=V,r=$,o=K;const ee=Cc(v,R.chunkLayout),ce=R.source,{fixedPositionWithinChunk:fe,chunkDisplayDimensionIndices:le}=R;for(const eo of le)fe[eo]=0;const ve=ce.chunkFormat;if(ve!==l&&(l=ve,m(),c=this.shaderGetter({emitter:e.emitter,chunkFormat:ve,wireFrame:e.wireFrame}),a=c.shader,a!==null&&(a.bind(),ve!==null))){if(Oi(u,a,this.shaderControlState,c.parameters.parseResult.controls),e.depthBufferTexture!==void 0&&e.depthBufferTexture!==null){const eo=a.textureUnit(nu);u.activeTexture(WebGL2RenderingContext.TEXTURE0+eo),u.bindTexture(WebGL2RenderingContext.TEXTURE_2D,e.depthBufferTexture)}else throw new Error("Depth buffer texture ID for volume rendering is undefined or null");ve.beginDrawing(u,a),ve.beginSource(u,a)}if(b=void 0,a===null)return;y=ce.chunks,d.fill(1);const Ie=w.pB.multiply(Jk,v.viewProjectionMat,ee.transform);u.uniformMatrix4fv(a.uniform("uModelViewProjectionMatrix"),!1,Ie);const mt=jk;(0,w._S)(mt,Ie),w.pB.invert(Ie,Ie),u.uniformMatrix4fv(a.uniform("uInvModelViewProjectionMatrix"),!1,Ie);const{near:Fe,far:Ct,adjustedNear:ln,adjustedFar:kt}=Uk(mt,R.lowerClipDisplayBound,R.upperClipDisplayBound),Ue=$,et=this.depthSamplesTarget.value,Lt=Ue/et;u.uniform1f(a.uniform("uBrightnessFactor"),Lt);const Xn=(ln-Fe)/(Ct-Fe),Zr=(kt-Fe)/(Ct-Fe);u.uniform1f(a.uniform("uNearLimitFraction"),Xn),u.uniform1f(a.uniform("uFarLimitFraction"),Zr),u.uniform1f(a.uniform("uGain"),Math.exp(this.gain.value)),u.uniform1i(a.uniform("uMaxSteps"),this.depthSamplesTarget.value),u.uniform3fv(a.uniform("uLowerClipBound"),R.lowerClipDisplayBound),u.uniform3fv(a.uniform("uUpperClipBound"),R.upperClipDisplayBound)},R=>{if(a===null)return;const P=R.curPositionInChunks.join(),V=y.get(P);if(V!==void 0&&V.state===Be.GPU_MEMORY){const $=R.chunkLayout.size,Q=V.chunkDataSize,{chunkDisplayDimensionIndices:K,fixedPositionWithinChunk:ee,chunkTransform:{channelToChunkDimensionIndices:ce}}=R;if(e.wireFrame){const le=E/y.size;u.uniform1f(a.uniform("uChunkNumber"),le),++E}if(Q!==b){b=Q;for(let le=0;le<3;++le){const ve=K[le];d[le]=ve===-1||ve>=C?1:b[ve]}u.uniform3fv(a.uniform("uChunkDataSize"),d)}const{chunkGridPosition:fe}=V;for(let le=0;le<3;++le){const ve=K[le];k[le]=ve===-1||ve>=C?0:$[le]*fe[ve]}l!=null&&(l.bindChunk(u,a,V,ee,K,ce,g),T&&L.push({chunk:V,fixedPositionWithinChunk:ee,chunkDisplayDimensionIndices:K,channelToChunkDimensionIndices:ce,chunkDataDisplaySize:d,chunkFormat:l})),u.uniform3fv(a.uniform("uTranslation"),k),u.uniform1ui(a.uniform("uPickId"),_),GI(u,1,1),g=!1,++S}else++x}),u.disable(WebGL2RenderingContext.CULL_FACE),m(),this.vertexIdHelper.disable(),T){let R=null,P;const V=()=>{R!==null&&(R.unbindTransferFunctionTextures(),l!==null&&l.endDrawing(u,R))},$=(le,ve)=>{const Ie=Math.ceil(le.reduce((Ct,ln)=>Ct*ln,1)/2),mt=zk/ve,Fe=Math.min(Ie,mt);return Math.max(Math.round(Fe/tu),1)};l=null;const{dataType:Q,dataHistogramSpecifications:K}=this,ee=K.getFramebuffers(u),ce=this.getDataHistogramCount();for(let le=0;le<ce;++le)ee[le].bind(256,1),u.clearColor(0,0,0,1),u.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT);const fe=this.dataHistogramSpecifications.bounds.value;u.enable(WebGL2RenderingContext.BLEND),u.disable(WebGL2RenderingContext.DEPTH_TEST);for(let le=0;le<S;++le){g=!0;const ve=L[le],Ie=ve.chunkFormat;if(Ie!==l)if(l=Ie,V(),P=this.histogramShaderGetter({chunkFormat:Ie}),R=P.shader,R!==null)Ie!==null&&(Ie.beginDrawing(u,R),Ie.beginSource(u,R)),R.bind();else break;if(R===null)break;u.uniform3fv(R.uniform("uChunkDataSize"),ve.chunkDataDisplaySize),l?.bindChunk(u,R,ve.chunk,ve.fixedPositionWithinChunk,ve.chunkDisplayDimensionIndices,ve.channelToChunkDimensionIndices,g),this.histogramIndexBuffer.value.bindToVertexAttrib(R.attribute("aInput1"),1,WebGL2RenderingContext.UNSIGNED_BYTE,!0);const mt=$(ve.chunkDataDisplaySize,S);for(let Fe=0;Fe<ce;++Fe)ee[Fe].bind(256,1),Pi(R,`invlerpForHistogram${Fe}`,Q,fe[Fe]),u.uniform1i(R.uniform("uHistogramIndex"),Fe),u.drawArraysInstanced(WebGL2RenderingContext.POINTS,0,tu,mt);g=!1}if(T&&Wk){const le=this.dataHistogramSpecifications.getFramebuffers(u);for(let ve=0;ve<ce;++ve){le[ve].bind(256,1);const Ie=new Float32Array(256*4);u.readPixels(0,0,256,1,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.FLOAT,Ie);const mt=new Float32Array(256);for(let Fe=0;Fe<256;++Fe)mt[Fe]=Ie[Fe*4];console.log("histogram%d",ve,mt.join(" "))}}V(),f()}}isReady(e,t){const n=t.state.sources.value;if(n.length===0)return!0;let s=!1;return Uy(e.projectionParameters,this.localPosition.value,this.depthSamplesTarget.value,n[0],()=>{},r=>{const o=r.source.chunks.get(r.curPositionInChunks.join());(o===void 0||o.state!==Be.GPU_MEMORY)&&(s=!0)}),!s}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Qk=Pe.fromObject({arrowup:{action:"tab-backward"},arrowdown:{action:"tab-forward"},tab:{action:"tab-forward"},"shift+tab":{action:"tab-backward"},enter:{action:"commit"},escape:{action:"cancel"}});class qk{constructor(e){this.id=e,this.element=document.createElement("div"),this.nameContainer=document.createElement("div"),this.nameElement=document.createElement("input"),this.lowerElement=document.createElement("div"),this.upperElement=document.createElement("div");const{element:t,nameContainer:n,nameElement:s,lowerElement:r,upperElement:o}=this;t.classList.add("neuroglancer-channel-dimensions-widget-dim"),n.classList.add("neuroglancer-channel-dimensions-widget-name-container"),s.classList.add("neuroglancer-channel-dimensions-widget-name"),n.appendChild(s),r.classList.add("neuroglancer-channel-dimensions-widget-lower"),o.classList.add("neuroglancer-channel-dimensions-widget-upper"),t.appendChild(n),t.appendChild(r),t.appendChild(o),n.draggable=!0,s.disabled=!0,s.spellcheck=!1,s.autocomplete="off",s.required=!0,s.placeholder=" ",n.title="Drag to reorder, double click to rename.  Names ending in ' or ^ indicate dimensions local to the layer; names ending in ^ indicate channel dimensions (image layers only).",n.addEventListener("dblclick",()=>{s.disabled=!1,s.focus(),s.select()}),s.addEventListener("focus",()=>{s.select()})}}class Kk extends D.O8{constructor(e){super(),this.combiner=e,this.element=document.createElement("div"),this.dimensionWidgets=[],this.curCoordinateSpace=void 0,this.dragSource=void 0,this.coordinateSpace=this.combiner.combined;const{element:t}=this;t.classList.add("neuroglancer-channel-dimensions-widget");const n=this.registerCancellable((0,je.t)(()=>this.updateView()));this.registerDisposer(e.combined.changed.add(n));const s=this.registerDisposer(new mn(t,Qk));s.allShortcutsAreGlobal=!0,this.registerDisposer(X(t,"cancel",r=>{this.forceUpdateView();const{target:o}=r;o instanceof HTMLElement&&o.blur()})),this.updateView()}reorderDimensionTo(e,t){if(e===t)return;const{coordinateSpace:n}=this;n.value=Gh(n.value,e,t)}makeNewDimensionWidget(e){const t=new qk(e);return t.nameContainer.addEventListener("dragstart",n=>{this.dragSource=t,n.stopPropagation(),n.dataTransfer.setData("neuroglancer-dimension","")}),t.nameContainer.addEventListener("dragenter",n=>{const{dragSource:s}=this;if(s===void 0||s===t)return;const{dimensionWidgets:r}=this,o=r.indexOf(s),a=r.indexOf(t);o===-1||a===-1||(n.preventDefault(),this.reorderDimensionTo(a,o))}),t.nameContainer.addEventListener("dragend",n=>{this.dragSource===t&&(this.dragSource=void 0)}),t.nameElement.addEventListener("blur",n=>{t.nameElement.disabled=!0;const{relatedTarget:s}=n;this.dimensionWidgets.some(r=>r.nameElement===s)||this.updateNames()||this.forceUpdateView()}),t.nameElement.addEventListener("input",()=>{const{nameElement:n}=t;Ft(n),this.updateNameValidity()}),X(t.nameElement,"commit",()=>{this.updateNames()}),X(t.nameElement,"tab-forward",n=>this.selectAdjacentField(n,t,1)),X(t.nameElement,"tab-backward",n=>this.selectAdjacentField(n,t,-1)),t}selectAdjacentField(e,t,n){e.stopPropagation();const{dimensionWidgets:s}=this,r=s.indexOf(t);if(r===-1)return;const o=r+n;if(o<0||o>=s.length)return;const a=s[o];a.nameElement.disabled=!1,a.nameElement.focus(),e.preventDefault()}updateNames(){const{dimensionWidgets:e,coordinateSpace:t}=this,n=t.value,s=e.map(l=>l.nameElement.value);if(this.combiner.getRenameValidity(s).includes(!1))return!1;const r=n.names;if((0,z.r1)(r,s))return!1;const o=n.timestamps.map((l,c)=>r[c]===s[c]?l:Date.now()),a={...n,names:s,timestamps:o};return t.value=a,!0}updateNameValidity(){const{dimensionWidgets:e}=this,t=e.map(r=>r.nameElement.value),n=t.length,s=this.combiner.getRenameValidity(t);for(let r=0;r<n;++r)e[r].nameElement.dataset.isValid=s[r]===!1?"false":"true"}forceUpdateView(){this.curCoordinateSpace=void 0,this.updateView()}updateView(){const{coordinateSpace:{value:e}}=this;if(this.curCoordinateSpace===e)return;this.curCoordinateSpace=e;const{element:t}=this,n=this.dimensionWidgets,s=this.dimensionWidgets=e.ids.map(o=>n.find(a=>a.id===o)||this.makeNewDimensionWidget(o));function*r(){const{names:o,rank:a,bounds:l}=e;for(let c=0;c<a;++c){const d=s[c];d.nameElement.value=o[c],d.nameElement.dataset.isValid=void 0,Ft(d.nameElement);const[u,h]=kh(l,c);d.lowerElement.textContent=u.toString(),d.upperElement.textContent=h.toString(),yield d.element}}Zt(t,r.call(this))}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const iu="opacity",su="blend",Wy="shader",Hy="shaderControls",ru="crossSectionRenderScale",Jy="channelDimensions",ou="volumeRendering",au="volumeRenderingGain",lu="volumeRenderingDepthSamples",Xk=Wd(Ln),[jy,Zk]=Gy();class Si extends Xk{constructor(e){super(e),this.opacity=Fr(.5),this.blendMode=Pk(),this.fragmentMain=Ak(),this.shaderError=ar(),this.dataType=new A.B0(void 0),this.sliceViewRenderScaleHistogram=new Rs,this.sliceViewRenderScaleTarget=_i(1),this.volumeRenderingGain=Nk(0),this.volumeRenderingChunkResolutionHistogram=new Rs(jy),this.volumeRenderingDepthSamplesTarget=_i($k,2**jy,2**Zk-1),this.channelCoordinateSpace=new Ml,this.channelCoordinateSpaceCombiner=new Fl(this.channelCoordinateSpace,hw),this.channelSpace=this.registerDisposer((0,A.ol)(t=>go(()=>bw(t)),this.channelCoordinateSpace)),this.volumeRenderingMode=Ok(),this.shaderControlState=this.registerDisposer(new Fo(this.fragmentMain,this.registerDisposer((0,A.Uq)((t,n)=>t===void 0?null:{imageData:{dataType:t,channelRank:n.rank}},[this.dataType,this.channelCoordinateSpace],(t,n)=>JSON.stringify(t)===JSON.stringify(n))),this.channelCoordinateSpaceCombiner)),this.localCoordinateSpaceCombiner.includeDimensionPredicate=tr,this.blendMode.changed.add(this.specificationChanged.dispatch),this.opacity.changed.add(this.specificationChanged.dispatch),this.volumeRenderingGain.changed.add(this.specificationChanged.dispatch),this.fragmentMain.changed.add(this.specificationChanged.dispatch),this.shaderControlState.changed.add(this.specificationChanged.dispatch),this.sliceViewRenderScaleTarget.changed.add(this.specificationChanged.dispatch),this.volumeRenderingMode.changed.add(this.specificationChanged.dispatch),this.volumeRenderingDepthSamplesTarget.changed.add(this.specificationChanged.dispatch),this.tabs.add("rendering",{label:"Rendering",order:-100,getter:()=>new eL(this)}),this.tabs.default="rendering"}markLoading(){const e=super.markLoading(),t=this.channelCoordinateSpaceCombiner.retain();return()=>{e(),t()}}addCoordinateSpace(e){const t=super.addCoordinateSpace(e),n=this.channelCoordinateSpaceCombiner.bind(e);return()=>{t(),n()}}activateDataSubsources(e){let t;for(const n of e){if(this.addStaticAnnotations(n))continue;const{subsourceEntry:s}=n,{subsource:r}=s,{volume:o}=r;if(!(o instanceof Ht)){n.deactivate("Not compatible with image layer");continue}if(t&&o.dataType!==t){n.deactivate(`Data type must be ${I[o.dataType].toLowerCase()}`);continue}t=o.dataType,n.activate(a=>{n.addRenderLayer(new Mk(o,{opacity:this.opacity,blendMode:this.blendMode,shaderControlState:this.shaderControlState,shaderError:this.shaderError,transform:n.getRenderLayerTransform(this.channelCoordinateSpace),renderScaleTarget:this.sliceViewRenderScaleTarget,renderScaleHistogram:this.sliceViewRenderScaleHistogram,localPosition:this.localPosition,channelCoordinateSpace:this.channelCoordinateSpace}));const l=a.registerDisposer(new Yk({gain:this.volumeRenderingGain,multiscaleSource:o,shaderControlState:this.shaderControlState,shaderError:this.shaderError,transform:n.getRenderLayerTransform(this.channelCoordinateSpace),depthSamplesTarget:this.volumeRenderingDepthSamplesTarget,chunkResolutionHistogram:this.volumeRenderingChunkResolutionHistogram,localPosition:this.localPosition,channelCoordinateSpace:this.channelCoordinateSpace,mode:this.volumeRenderingMode}));a.registerDisposer(n.messages.addChild(l.messages)),a.registerDisposer((0,A.no)((c,d)=>{d!==yi.OFF&&c.registerDisposer(this.addRenderLayer(l.addRef()))},this.volumeRenderingMode)),this.shaderError.changed.dispatch()})}this.dataType.value=t}restoreState(e){super.restoreState(e),this.opacity.restoreState(e[iu]),(0,p.MM)(e,su,t=>this.blendMode.restoreState(t)),this.fragmentMain.restoreState(e[Wy]),this.shaderControlState.restoreState(e[Hy]),this.sliceViewRenderScaleTarget.restoreState(e[ru]),this.channelCoordinateSpace.restoreState(e[Jy]),(0,p.MM)(e,ou,t=>{typeof t=="boolean"?this.volumeRenderingMode.value=t?yi.ON:yi.OFF:this.volumeRenderingMode.restoreState(t)}),(0,p.MM)(e,au,t=>this.volumeRenderingGain.restoreState(t)),(0,p.MM)(e,lu,t=>this.volumeRenderingDepthSamplesTarget.restoreState(t))}toJSON(){const e=super.toJSON();return e[iu]=this.opacity.toJSON(),e[su]=this.blendMode.toJSON(),e[Wy]=this.fragmentMain.toJSON(),e[Hy]=this.shaderControlState.toJSON(),e[ru]=this.sliceViewRenderScaleTarget.toJSON(),e[Jy]=this.channelCoordinateSpace.toJSON(),e[ou]=this.volumeRenderingMode.toJSON(),e[au]=this.volumeRenderingGain.toJSON(),e[lu]=this.volumeRenderingDepthSamplesTarget.toJSON(),e}displayImageSelectionState(e,t){const{value:n}=e;if(n==null)return!1;const s=this.channelSpace.value;if(s.error!==void 0)return!1;const{numChannels:r,coordinates:o,channelCoordinateSpace:{names:a,rank:l}}=s,c=document.createElement("div");c.classList.add("neuroglancer-selection-details-value-grid");let d="[copy] 0fr ";l!==0&&(d+=`repeat(${l}, [dim] 0fr [coord] 0fr) `),d+="[value] 1fr",c.style.gridTemplateColumns=d;for(let u=0;u<r;++u){const h=l===0?n:n[u],f=h==null?"":h.toString(),m=zn({title:"Copy value",onClick:()=>{ai(f)}});c.appendChild(m);for(let v=0;v<l;++v){const y=document.createElement("div");y.classList.add("neuroglancer-selection-details-value-grid-dim"),y.textContent=a[v],c.appendChild(y);const S=document.createElement("div");S.classList.add("neuroglancer-selection-details-value-grid-coord"),S.textContent=o[u*l+v].toString(),c.appendChild(S)}const g=document.createElement("div");g.classList.add("neuroglancer-selection-details-value-grid-value"),g.textContent=f,c.appendChild(g)}return t.appendChild(c),!0}displaySelectionState(e,t,n){let s=this.displayImageSelectionState(e,t);return super.displaySelectionState(e,t,n)&&(s=!0),s}getLegendShaderOptions(){return{memoizeKey:"ImageUserLayer",parameters:this.shaderControlState.builderState,encodeParameters:e=>e.key,defineShader:(e,t)=>{e.addFragmentCode(`
#define uOpacity 1.0
`),By(e,t)},initializeShader:e=>{const t=e.shader;Oi(this.manager.root.display.gl,t,this.shaderControlState,e.parameters.parseResult.controls)}}}}Si.type="image",Si.typeAbbreviation="img";function Yy(i){return new _a({shaderError:i.shaderError,fragmentMain:i.fragmentMain,shaderControlState:i.shaderControlState})}const Qy=[{label:"Resolution (slice)",toolJson:ru,...la(i=>({histogram:i.sliceViewRenderScaleHistogram,target:i.sliceViewRenderScaleTarget}))},{label:"Blending (slice)",toolJson:su,...od(i=>i.blendMode)},{label:"Opacity (slice)",toolJson:iu,...Jn(i=>({value:i.opacity}))},{label:"Volume rendering (experimental)",toolJson:ou,...od(i=>i.volumeRenderingMode)},{label:"Gain (3D)",toolJson:au,isValid:i=>(0,A.Uq)(e=>e===yi.ON,[i.volumeRenderingMode]),...Jn(i=>({value:i.volumeRenderingGain,options:{min:-10,max:10,step:.1}}))},{label:"Resolution (3D)",toolJson:lu,isValid:i=>(0,A.Uq)(e=>e!==yi.OFF,[i.volumeRenderingMode]),...la(i=>({histogram:i.volumeRenderingChunkResolutionHistogram,target:i.volumeRenderingDepthSamplesTarget}),BT)}];for(const i of Qy)Kg(Si,i);class eL extends Gt{constructor(e){super(),this.layer=e,this.codeWidget=this.registerDisposer(Yy(this.layer));const{element:t}=this;t.classList.add("neuroglancer-image-dropdown");for(const r of Qy)t.appendChild(rd(this,e,this.visibility,r));const n=document.createElement("div");n.style.flex="1";const s=document.createElement("div");s.className="neuroglancer-image-dropdown-top-row",s.appendChild(document.createTextNode("Shader")),s.appendChild(n),s.appendChild(Va({title:"Show larger editor view",onClick:()=>{new tL(this.layer)}})),s.appendChild(Oa({title:"Documentation on image layer rendering",href:"https://github.com/google/neuroglancer/blob/master/src/sliceview/image_layer_rendering.md"})),t.appendChild(s),t.appendChild(this.registerDisposer(new Kk(e.channelCoordinateSpaceCombiner)).element),t.appendChild(this.codeWidget.element),t.appendChild(this.registerDisposer(new Ba(e.shaderControlState,this.layer.manager.root.display,this.layer,{visibility:this.visibility,legendShaderOptions:this.layer.getLegendShaderOptions()})).element)}}class tL extends $r{constructor(e){super(),this.layer=e,this.codeWidget=this.registerDisposer(Yy(this.layer)),this.content.classList.add("neuroglancer-image-layer-shader-overlay"),this.content.appendChild(this.codeWidget.element),this.codeWidget.textEditor.refresh()}}Ui(Si),_g(gt.IMAGE,Si),ia(i=>{const{volume:e}=i;if(e!==void 0&&e.volumeType===gt.UNKNOWN)return{layerConstructor:Si,priority:-100}}),Fa(Si,i=>({shaderControlState:i.shaderControlState,legendShaderOptions:i.getLegendShaderOptions()}));var qy=G(957),nL=Object.defineProperty,iL=Object.getOwnPropertyDescriptor,sL=(i,e,t,n)=>{for(var s=n>1?void 0:n?iL(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&nL(e,t,s),s};/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let cu=class extends un{constructor(i,e){super(),this.provider=i,this.registerDisposer(i),this.initializeCounterpart(e)}get(i,e){return this.provider.get(i,e)}};cu=sL([Kt(qy.P)],cu),ap(qy.y,function(i,e){return this.get(i.providerId).get(i.invalidCredentials,e).then(n=>({value:n}))});/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function du(i,e){if(e===void 0)return;const t=i.memoize.get({type:"getSharedCredentialsProvider",credentialsProvider:St(e)},()=>new cu(e.addRef(),i.rpc)),n=t.addCounterpartRef();return t.dispose(),n}function st(){return i=>{class e extends i{constructor(...n){super(...n);const s=n[1];this.credentialsProvider=s.credentialsProvider?.addRef()}initializeCounterpart(n,s){const{credentialsProvider:r}=this;s.credentialsProvider=du(this.chunkManager,r),super.initializeCounterpart(n,s)}static encodeOptions(n){const s=i.encodeOptions(n),{credentialsProvider:r}=n;return s.credentialsProvider=r===void 0?void 0:St(r),s}}return e}}var Gs=G(6015);const Ky=!0;var zs=G(3551),Me=G(9808);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function rL(i,e,t,n,s){const r=await(0,zs.Y)(i,`${e}?prefix=${encodeURIComponent(t)}&delimiter=${encodeURIComponent(n)}`,{},d=>d.text(),s),o=new DOMParser().parseFromString(r,"application/xml"),a=o.evaluate('//*[name()="CommonPrefixes"]/*[name()="Prefix"]',o,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null),l=[];for(let d=0,u=a.snapshotLength;d<u;++d)l.push(a.snapshotItem(d).textContent||"");const c=o.evaluate('//*[name()="Contents"]/*[name()="Key"]',o,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);for(let d=0,u=c.snapshotLength;d<u;++d)l.push(c.snapshotItem(d).textContent||"");return l}async function uu(i,e,t,n,s){if(!n.startsWith("/"))throw null;const o=await rL(i,t,n.substring(1),"/",s),a=n.lastIndexOf("/");return{offset:a+e.length+1,completions:o.map(l=>({value:l.substring(a)}))}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function oL(i,e,t,n,s=at.fx){return await(0,Me.Bk)(`https://${i}.s3.amazonaws.com${e}`,t,n,s)}async function aL(i,e,t){return await uu(void 0,`s3://${i}`,`https://${i}.s3.amazonaws.com`,e,t)}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function lL(i,e){return i.getCredentialsProvider("middleauthapp",new URL(e).origin)}function Ua(i,e,t){const n=/^\/([^/]+)/,s=t.match(n);if(s!==null)return Ky?i.getCredentialsProvider("gcs",{bucket:s[1]}):i.getCredentialsProvider("ngauth_gcs",{authServer:e,bucket:s[1]})}function bn(i,e){const t=(0,Me.Dl)(i);switch(t.protocol){case"gs":case"gs+xml":return{credentialsProvider:Ky?e.getCredentialsProvider("gcs",{bucket:t.host}):void 0,url:i};case"gs+ngauth+http":return{credentialsProvider:Ua(e,`http://${t.host}`,t.path),url:"gs:/"+t.path};case"gs+ngauth+https":return{credentialsProvider:Ua(e,`https://${t.host}`,t.path),url:"gs:/"+t.path};case"gs+xml+ngauth+http":return{credentialsProvider:Ua(e,`http://${t.host}`,t.path),url:"gs+xml:/"+t.path};case"gs+xml+ngauth+https":return{credentialsProvider:Ua(e,`https://${t.host}`,t.path),url:"gs+xml:/"+t.path};case"middleauth+https":return i=i.substr(11),{credentialsProvider:lL(e,i),url:i};case"s3":return{credentialsProvider:void 0,url:i};default:return{credentialsProvider:void 0,url:i}}}async function rn(i,e,t,n,s=at.fx){const r=(0,Me.Dl)(e);switch(r.protocol){case"gs":return(0,zs.Y)(i,`https://www.googleapis.com/storage/v1/b/${r.host}/o/${encodeURIComponent(r.path.substring(1))}?alt=media&neuroglancer=${it()}`,t,n,s);case"gs+xml":return(0,zs.Y)(i,`https://storage.googleapis.com/${r.host}${r.path}?neuroglancer=${it()}`,t,n,s);case"s3":return oL(r.host,r.path,t,n,s);default:return(0,zs.Y)(i,e,t,n,s)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cL extends D.O8{constructor(e){super(),this.gl=e,this.buffer=this.registerDisposer(new At(e))}resize(e){let t;if(e<256){const n=t=new Uint8Array(e);for(let s=0;s<e;++s)n[s]=s;this.webglType=WebGL2RenderingContext.UNSIGNED_BYTE}else if(e<65536){const n=t=new Uint16Array(e);for(let s=0;s<e;++s)n[s]=s;this.webglType=WebGL2RenderingContext.UNSIGNED_SHORT}else{const n=t=new Uint32Array(e);for(let s=0;s<e;++s)n[s]=s;this.webglType=WebGL2RenderingContext.UNSIGNED_INT}this.buffer.setData(t),this.length=e}ensure(e){return(this.length===void 0||this.length<e)&&this.resize(e),this}bindToVertexAttrib(e){this.buffer.bindToVertexAttribI(e,1,this.webglType)}bind(e,t=0){const n=e.attribute("aIndexRaw");n>=0&&(this.bindToVertexAttrib(n),t!==0&&this.gl.vertexAttribDivisor(n,t))}}function dL(i,e,t=!1){const n=e.attribute("aIndexRaw");n>=0&&(t&&i.vertexAttribDivisor(n,0),i.disableVertexAttribArray(n))}function uL(i){return i.memoize.get("IndexBuffer",()=>new cL(i))}function hL(i){i.addAttribute("highp uint","aIndexRaw"),i.addVertexCode(bo),i.addVertexCode(`
uint getPrimitiveIndex() {
  return aIndexRaw;
}
`)}class pL{constructor(e){this.name=e}defineShader(e){e.addAttribute("highp uint",this.name)}bind(e,t){const n=t.attribute(this.name);e.bindToVertexAttribI(n,1,WebGL2RenderingContext.UNSIGNED_INT)}disable(e){e.gl.disableVertexAttribArray(e.attribute(this.name))}}function fL(i,e){return At.fromData(i,e,WebGL2RenderingContext.ARRAY_BUFFER,WebGL2RenderingContext.STATIC_DRAW)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Xy=`void main() {
  emitGray();
}
`;class gL{constructor(){this.shaderError=ar(),this.fragmentMain=mo(Xy),this.shaderControlState=new Fo(this.fragmentMain)}}function Zy(i){return vt(i.dataType,i.numComponents)}const qi=[],eS=zi(new As,I.FLOAT32,3),mL=eS;function vL(i){return i.split(/[^a-zA-Z0-9]+/).filter(e=>e).join("_")}function tS(i){const e=new Set,t=[];for(const n of i){const s=vL(n);let r="",o=0;for(;e.has(s+r);)r=""+ ++o;t.push(s+r)}return t}class yL{constructor(e,t){this.attributeNames=e,this.attributeInfo=t,this.tempLightVec=new Float32Array(4),this.textureAccessHelper=new ga("vertexData"),this.indexBufferHelper=new pL("vertexIndex")}defineAttributeAccess(e,t){const{textureAccessHelper:n}=this;n.defineShader(e);const{attributeNames:s}=this;let r=2+s.length;for(let a=qi.length;a<r;++a)qi[a]=Symbol(`SingleMeshShaderManager.vertexAttributeTextureUnit${a}`);r=0,e.addTextureSampler("sampler2D","uVertexAttributeSampler0",qi[r++]),e.addTextureSampler("sampler2D","uVertexAttributeSampler1",qi[r++]),e.addVertexCode(n.getAccessor("readVertexPosition","uVertexAttributeSampler0",I.FLOAT32,3)),e.addVertexCode(n.getAccessor("readVertexNormal","uVertexAttributeSampler1",I.FLOAT32,3));let o=`
vec3 vertexPosition = readVertexPosition(${t});
vec3 vertexNormal = readVertexNormal(${t});
`;this.attributeInfo.forEach((a,l)=>{e.addTextureSampler(`${pa(a.dataType)}sampler2D`,`uVertexAttributeSampler${r}`,qi[r]);const c=Zy(a);e.addVarying(`highp ${c}`,`vCustom${l}`),e.addFragmentCode(`
#define ${s[l]} vCustom${l}
`),e.addVertexCode(n.getAccessor(`readAttribute${l}`,`uVertexAttributeSampler${r}`,a.dataType,a.numComponents)),o+=`vCustom${l} = readAttribute${l}(${t});
`,++r}),e.addVertexMain(o)}defineShader(e){e.require(hL),this.indexBufferHelper.defineShader(e),e.addVarying("highp float","vLightingFactor"),e.addUniform("highp vec4","uLightDirection"),e.addUniform("highp vec4","uColor"),e.addUniform("highp mat4","uModelMatrix"),e.addUniform("highp mat4","uProjection"),e.addUniform("highp uint","uPickID"),e.addVarying("highp uint","vPickID","flat"),e.addVertexMain(`
uint triangleIndex = getPrimitiveIndex() / 3u;
vPickID = uPickID + triangleIndex;
`),e.addFragmentCode(`
void emitPremultipliedRGBA(vec4 color) {
  emit(vec4(color.rgb * vLightingFactor, color.a), vPickID);
}
void emitRGBA(vec4 color) {
  color = clamp(color, 0.0, 1.0);
  color.xyz *= color.a;
  emitPremultipliedRGBA(color);
}
void emitRGB(vec3 color) {
  emitRGBA(vec4(color, 1.0));
}
void emitGray() {
  emitRGB(vec3(1.0, 1.0, 1.0));
}
`),e.addFragmentCode(Es),this.defineAttributeAccess(e,"vertexIndex"),e.addVertexMain(`
gl_Position = uProjection * (uModelMatrix * vec4(vertexPosition, 1.0));
vec3 normal = normalize((uModelMatrix * vec4(vertexNormal, 0.0)).xyz);
vLightingFactor = abs(dot(normal, uLightDirection.xyz)) + uLightDirection.w;
`)}beginLayer(e,t,n){const{lightDirection:s,ambientLighting:r,directionalLighting:o,projectionParameters:a}=n,{viewProjectionMat:l}=a;e.uniformMatrix4fv(t.uniform("uProjection"),!1,l);const c=this.tempLightVec;w.eR.scale(c,s,o),c[3]=r,e.uniform4fv(t.uniform("uLightDirection"),c)}setPickID(e,t,n){e.uniform1ui(t.uniform("uPickID"),n)}beginObject(e,t,n){e.uniformMatrix4fv(t.uniform("uModelMatrix"),!1,n)}bindVertexData(e,t,n){let s=0;const r=a=>{const l=WebGL2RenderingContext.TEXTURE0+t.textureUnit(qi[s]);e.activeTexture(l),e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,a),++s};r(n.vertexTexture),r(n.normalTexture);const{attributeNames:o}=this;n.vertexAttributeTextures.forEach((a,l)=>{o[l]!==void 0&&r(a)})}disableVertexData(e,t){let n=2;const s=this.attributeInfo.length,{attributeNames:r}=this;for(let o=0;o<s;++o)r[o]!==void 0&&++n;for(let o=0;o<n;++o){const a=t.textureUnit(qi[o])+WebGL2RenderingContext.TEXTURE0;e.activeTexture(a),e.bindTexture(e.TEXTURE_2D,null)}}drawFragment(e,t,n,s){s.ensure(n.numIndices).bind(t),this.bindVertexData(e,t,n.vertexData),this.indexBufferHelper.bind(n.indexBuffer,t),e.drawArrays(WebGL2RenderingContext.TRIANGLES,0,n.numIndices)}endLayer(e,t){dL(e,t),this.indexBufferHelper.disable(t),this.disableVertexData(e,t)}}class SL{copyToGPU(e,t){const n=(s,r)=>{const o=e.createTexture();return e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,o),fa(e,r,s),o};this.vertexTexture=n(this.vertexPositions,eS),this.normalTexture=n(this.vertexNormals,mL),this.vertexAttributeTextures=this.vertexAttributes.map((s,r)=>n(s,t[r])),e.bindTexture(WebGL2RenderingContext.TEXTURE_2D,null)}freeGPUMemory(e){e.deleteTexture(this.vertexTexture),e.deleteTexture(this.normalTexture);const{vertexAttributeTextures:t}=this;for(const n of t)e.deleteTexture(n);t.length=0}}class bL extends Wn{constructor(e,t){super(e);const n=this.vertexData=new SL;n.vertexPositions=t.vertexPositions,n.vertexNormals=t.vertexNormals,n.vertexAttributes=t.vertexAttributes;const s=this.indices=t.indices;this.numIndices=s.length}copyToGPU(e){super.copyToGPU(e),this.vertexData.copyToGPU(e,this.source.attributeTextureFormats),this.indexBuffer=fL(e,this.indices)}freeGPUMemory(e){super.freeGPUMemory(e),this.vertexData.freeGPUMemory(e),this.indexBuffer.dispose()}}function wL(i){return i.map(e=>zi(new As,e.dataType,e.numComponents))}class CL extends Ke(st()(tn),Gs.Fe){constructor(){super(...arguments),this.attributeTextureFormats=wL(this.info.vertexAttributes)}get info(){return this.parameters.info}getChunk(e){return new bL(this,e)}}const xL=ir(un);class EL extends xL{}class TL extends $i{constructor(e,t,n){super(),this.source=e,this.displayState=t,this.transform=n,this.shaderManager=new yL(tS(this.source.info.vertexAttributes.map(r=>r.name)),this.source.info.vertexAttributes),this.shaders=new Map,this.sharedObject=this.registerDisposer(new EL),this.shaderGetter=Ii(this,this.gl,{memoizeKey:{t:"single_mesh/RenderLayer",attributes:this.source.info.vertexAttributes},fallbackParameters:new A.B0(Bo(br(Xy))),parameters:this.displayState.shaderControlState.builderState,encodeParameters:r=>r.key,shaderError:this.displayState.shaderError,defineShader:(r,o)=>{if(o.parseResult.errors.length!==0)throw new Error("Invalid UI control specification");Cs(o,r),this.shaderManager.defineShader(r),r.setFragmentMainFunction(ls(o.parseResult.code))}}),this.countingBuffer=this.registerDisposer(uL(this.gl)),this.registerDisposer(t.shaderControlState.parseResult.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(t.shaderControlState.changed.add(this.redrawNeeded.dispatch)),this.registerDisposer(n.changed.add(this.redrawNeeded.dispatch));const{sharedObject:s}=this;s.visibility.add(this.visibility),s.RPC_TYPE_ID=Gs.nG,s.initializeCounterpart(e.chunkManager.rpc,{chunkManager:e.chunkManager.rpcId,source:e.addCounterpartRef()})}disposeShaders(){const{shaders:e}=this;for(const t of e.values())t!==null&&t.dispose();e.clear()}disposed(){this.disposeShaders(),super.disposed()}get isTransparent(){return this.displayState.fragmentMain.value.match(/emitRGBA|emitPremultipliedRGBA/)!==null}get gl(){return this.source.gl}isReady(){const e=this.source.chunks.get(Gs.b7);return!(e===void 0||e.state!==Be.GPU_MEMORY)}draw(e,t){if(!e.emitColor&&e.alreadyEmittedPickID)return;const n=sr(this.transform.value,e.projectionParameters.displayDimensionRenderInfo,t);if(n===void 0)return;const s=this.source.chunks.get(Gs.b7);if(s===void 0||s.state!==Be.GPU_MEMORY)return;const r=this.shaderGetter(e.emitter),{shader:o,parameters:a}=r;if(o===null)return;const{gl:l}=this,c=this.shaderManager;o.bind(),c.beginLayer(l,o,e),Oi(l,o,this.displayState.shaderControlState,a.parseResult.controls);const{pickIDs:d}=e;c.beginObject(l,o,n),e.emitPickID&&c.setPickID(l,o,d.register(this,s.numIndices/3)),c.drawFragment(l,o,s,this.countingBuffer),c.endLayer(l,o)}transformPickedValue(e){const{pickedOffset:t}=e,n=this.source.chunks.get(Gs.b7);if(n===void 0)return;const s=t*3,{indices:r}=n;if(s>=r.length)return;const o=r[s],a=[],{attributeNames:l}=this.shaderManager;return n.vertexData.vertexAttributes.forEach((c,d)=>{const u=l[d];u!==void 0&&a.push(`${u}=${c[o].toPrecision(6)}`)}),a.join(", ")}}function DL(i,e,t){return i.memoize.getUncounted({type:"single_mesh:getMeshInfo",url:t},async()=>{const{url:n,credentialsProvider:s}=bn(t,e);return{info:await i.rpc.promiseInvoke(Gs.N3,{chunkManager:i.addCounterpartRef(),credentialsProvider:du(i,s),parameters:{meshSourceUrl:n}}),url:n,credentialsProvider:s}})}async function nS(i,e,t){const{info:n,url:s,credentialsProvider:r}=await DL(i,e,t);return i.getChunkSource(CL,{credentialsProvider:r,parameters:{meshSourceUrl:s,info:n}})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const iS="shader",sS="shaderControls";class Hr extends Ln{constructor(e){super(e),this.managedLayer=e,this.displayState=new gL,this.vertexAttributes=new A.B0(void 0),this.registerDisposer(this.displayState.shaderControlState.changed.add(this.specificationChanged.dispatch)),this.registerDisposer(this.displayState.fragmentMain.changed.add(this.specificationChanged.dispatch)),this.tabs.add("rendering",{label:"Rendering",order:-100,getter:()=>new RL(this)}),this.tabs.default="rendering"}restoreState(e){super.restoreState(e),this.displayState.fragmentMain.restoreState(e[iS]),this.displayState.shaderControlState.restoreState(e[sS])}activateDataSubsources(e){let t=!1;for(const n of e){const{subsourceEntry:s}=n,{subsource:r}=s,{singleMesh:o}=r;if(o!==void 0){if(t){n.deactivate("Only one single-mesh source supported");continue}t=!0,n.activate(a=>{n.addRenderLayer(new TL(o,this.displayState,n.getRenderLayerTransform())),this.vertexAttributes.value=o.info.vertexAttributes,a.registerDisposer(()=>{this.vertexAttributes.value=void 0})});continue}n.deactivate("Not compatible with image layer")}}toJSON(){const e=super.toJSON();return e[iS]=this.displayState.fragmentMain.toJSON(),e[sS]=this.displayState.shaderControlState.toJSON(),e}}Hr.type="mesh",Hr.typeAbbreviation="mesh";function rS(i){return new _a({fragmentMain:i.displayState.fragmentMain,shaderError:i.displayState.shaderError,shaderControlState:i.displayState.shaderControlState})}class IL extends D.O8{constructor(e){super(),this.attributes=e,this.element=document.createElement("div"),this.element.className="neuroglancer-single-mesh-attribute-widget",this.updateView(),this.registerDisposer(e.changed.add(()=>{this.updateView()}))}updateView(){const{element:e}=this,t=this.attributes.value;if(t===void 0){Ae(e);return}const n=tS(t.map(r=>r.name)),s=t.length;for(let r=0;r<s;++r){const o=t[r],a=document.createElement("div");a.className="neuroglancer-single-mesh-attribute";const l=document.createElement("div");l.className="neuroglancer-single-mesh-attribute-type",l.textContent=Zy(o);const c=document.createElement("div");if(c.className="neuroglancer-single-mesh-attribute-name",c.textContent=n[r],a.appendChild(l),a.appendChild(c),o.min!==void 0&&o.max!==void 0){const d=document.createElement("neuroglancer-single-mesh-attribute-minmax");d.className="neuroglancer-single-mesh-attribute-range",d.textContent=`[${o.min.toPrecision(6)}, ${o.max.toPrecision(6)}]`,a.appendChild(d)}e.appendChild(a)}}disposed(){lt(this.element)}}function oS(i){return new IL(i.vertexAttributes)}class RL extends Gt{constructor(e){super(),this.layer=e,this.attributeWidget=this.registerDisposer(oS(this.layer)),this.codeWidget=this.registerDisposer(rS(this.layer));const{element:t}=this;t.classList.add("neuroglancer-single-mesh-dropdown");const n=document.createElement("div");n.className="neuroglancer-single-mesh-dropdown-top-row";const s=document.createElement("div");s.style.flex="1",n.appendChild(s),n.appendChild(Va({title:"Show larger editor view",onClick:()=>{new kL(this.layer)}})),n.appendChild(Oa({title:"Documentation on single mesh layer rendering",href:"https://github.com/google/neuroglancer/blob/master/src/sliceview/image_layer_rendering.md"})),t.appendChild(n),t.appendChild(this.attributeWidget.element),t.appendChild(this.codeWidget.element),t.appendChild(this.registerDisposer(new Ba(e.displayState.shaderControlState,this.layer.manager.root.display,this.layer,{visibility:this.visibility})).element)}}class kL extends $r{constructor(e){super(),this.layer=e,this.attributeWidget=this.registerDisposer(oS(this.layer)),this.codeWidget=this.registerDisposer(rS(this.layer)),this.content.classList.add("neuroglancer-single-mesh-layer-shader-overlay"),this.content.appendChild(this.attributeWidget.element),this.content.appendChild(this.codeWidget.element),this.codeWidget.textEditor.refresh()}}Ui(Hr),ia(i=>{if(i.singleMesh!==void 0)return{layerConstructor:Hr,priority:2}}),Fa(Hr,i=>({shaderControlState:i.displayState.shaderControlState}));var hu=G(2366);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const LL="boss";function Ws(i,e,t,n,s=at.fx){return(0,Me.Bk)(e,t,n,s).catch(r=>{if(r.status!==500&&r.status!==401&&r.status!==403&&r.status!==504)throw r;return(0,hu.R)(i,e,t,n,o=>{const a=new Headers(t.headers);return a.set("Authorization",`Bearer ${o}`),{...t,headers:a}},o=>{const{status:a}=o;if(a===403||a===401)return"refresh";throw o},s)})}var aS=G(6650);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class PL extends Ke(st()(Mn),aS.jj){}class AL extends Ke(st()(pi),aS.Ve){}const pu=new Map;pu.set("image",gt.IMAGE),pu.set("annotation",gt.SEGMENTATION);const ML=new Set(["npz","jpeg"]),NL=Uint32Array.of(512,512,16);var lS=(i=>(i[i.NANOMETERS=0]="NANOMETERS",i[i.MICROMETERS=1]="MICROMETERS",i[i.MILLIMETERS=2]="MILLIMETERS",i[i.CENTIMETERS=3]="CENTIMETERS",i))(lS||{});function OL(i){switch(i){case 1:return 1e6;case 2:return 1e3;case 3:return 100;case 0:return 1e9}}function VL(i,e){(0,p.Rf)(i);const t=(0,p.cQ)(i,"voxel_unit",c=>(0,p.sl)(c,lS)),n=OL(t),s=new Float32Array(3),r=new Float64Array(3),o=new Float64Array(3),a=new Float64Array(3),l=["x","y","z"];for(let c=0;c<3;++c){const d=l[c];s[c]=(0,p.cQ)(i,`${d}_voxel_size`,p.Mo),r[c]=s[c]/n,o[c]=(0,p.cQ)(i,`${d}_start`,p.bX),a[c]=(0,p.cQ)(i,`${d}_stop`,p.bX)}return e.coordFrame={voxelSizeBaseInMeters:r,voxelSizeBaseInOriginalUnits:s,voxelOffsetBase:o,imageSizeBase:a,voxelUnit:t,names:l},e}function _L(i){let e=pu.get(i);return e===void 0&&(e=gt.UNKNOWN),e}function BL(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"type",p.zr);let t=!1;return(0,p.cQ)(i,"downsample_status",p.zr)==="DOWNSAMPLED"&&(t=!0),{channelType:e,description:(0,p.cQ)(i,"description",p.zr),volumeType:_L(e),dataType:(0,p.cQ)(i,"datatype",s=>(0,p.sl)(s,I)),downsampled:t,scales:[],key:(0,p.cQ)(i,"name",p.zr),baseResolution:(0,p.cQ)(i,"base_resolution",p.bX)}}function FL(i,e,t,n,s,r){(0,p.Rf)(i);const o=(0,p.cQ)(i,"channels",a=>(0,p.$v)(a,l=>GL(e,t,n,r,s,l)));return Promise.all(o).then(a=>{const l=new Map;a.forEach(d=>{l.set(d.key,d)});const c={channels:l,scalingLevels:(0,p.cQ)(i,"num_hierarchy_levels",p.bX),coordFrameKey:(0,p.cQ)(i,"coord_frame",p.zr),coordFrame:void 0,key:(0,p.cQ)(i,"name",p.zr),collection:(0,p.cQ)(i,"collection",p.zr)};return QL(e,t,n,c)})}class UL extends Ht{constructor(e,t,n,s,r,o){if(super(e),this.baseUrl=t,this.credentialsProvider=n,this.experimentInfo=s,this.parameters=o,this.meshPath=void 0,this.meshUrl=void 0,r===void 0){const u=Array.from(s.channels.keys());if(u.length!==1)throw new Error(`Experiment contains multiple channels: ${JSON.stringify(u)}`);r=u[0]}const a=s.channels.get(r);if(a===void 0)throw new Error(`Specified channel ${JSON.stringify(r)} is not one of the supported channels ${JSON.stringify(Array.from(s.channels.keys()))}`);if(this.channel=r,this.channelInfo=a,this.scales=a.scales,s.coordFrame===void 0)throw new Error(`Specified experiment ${JSON.stringify(s.key)} does not have a valid coordinate frame`);this.coordinateFrame=s.coordFrame,this.channelInfo.downsampled===!1&&(this.scales=[a.scales[0]]),this.experiment=s.key;const l=(0,p.z$)(o.window);if(l!==void 0){const u=w.Zc.create(),h=l.split(/,/);if(h.length===2)u[0]=(0,p.zo)(h[0]),u[1]=(0,p.zo)(h[1]);else if(h.length===1)u[0]=0,u[1]=(0,p.zo)(h[1]);else throw new Error(`Invalid window. Must be either one value or two comma separated values: ${JSON.stringify(l)}`);if(this.window=u,this.window[0]===this.window[1])throw new Error(`Invalid window. First element must be different from second: ${JSON.stringify(l)}.`)}const c=(0,p.z$)(o.meshurl);c!==void 0&&(this.meshUrl=c);let d=(0,p.z$)(o.encoding);if(d===void 0)d=this.dataType===I.UINT8?"jpeg":"npz";else if(!ML.has(d))throw new Error(`Invalid encoding: ${JSON.stringify(d)}.`);this.encoding=d}get dataType(){return this.channelInfo.dataType}get volumeType(){return this.channelInfo.volumeType}get rank(){return 3}getSources(e){const t=this.scales[0].downsampleFactors,{rank:n}=this;return(0,z.RO)(this.scales.map(s=>{const r=this.coordinateFrame.voxelOffsetBase,o=w.eR.create();for(let u=0;u<3;++u)o[u]=Math.ceil(r[u]);const a=s.downsampleFactors,l=n+1,c=new Float32Array(l*l);c[c.length-1]=1;for(let u=0;u<3;++u){const h=a[u]/t[u];c[l*u+u]=h,c[l*n+u]=o[u]*h}n===4&&(c[l*3+3]=1);const d=s.imageSize;return gi({rank:3,volumeType:this.volumeType,dataType:this.dataType,chunkToMultiscaleTransform:c,chunkDataSizes:[NL],baseVoxelOffset:o,upperVoxelBound:d,volumeSourceOptions:e}).map(u=>({chunkSource:this.chunkManager.getChunkSource(PL,{credentialsProvider:this.credentialsProvider,spec:u,parameters:{baseUrl:this.baseUrl,collection:this.experimentInfo.collection,experiment:this.experimentInfo.key,channel:this.channel,resolution:s.key,encoding:this.encoding,window:this.window}}),chunkToMultiscaleTransform:c}))}))}getMeshSource(){return this.meshUrl!==void 0?this.chunkManager.getChunkSource(AL,{credentialsProvider:this.credentialsProvider,parameters:{baseUrl:this.meshUrl}}):null}}const $L=/^([^/?]+)\/([^/?]+)(?:\/([^/?]+))?(?:\?(.*))?$/;function cS(i,e,t,n,s){return i.memoize.getUncounted({hostname:e,collection:s,experiment:n,type:"boss:getExperimentInfo"},()=>Ws(t,`${e}/latest/collection/${s}/experiment/${n}/`,{},Me.cj).then(r=>FL(r,i,e,t,s,n)))}function GL(i,e,t,n,s,r){return i.memoize.getUncounted({hostname:e,collection:s,experiment:n,channel:r,type:"boss:getChannelInfo"},()=>Ws(t,`${e}/latest/collection/${s}/experiment/${n}/channel/${r}/`,{},Me.cj).then(BL))}function zL(i,e,t,n,s,r){return i.memoize.getUncounted({hostname:e,collection:n,experiment:s.key,channel:r,downsample:!0,type:"boss:getDownsampleInfoForChannel"},()=>Ws(t,`${e}/latest/downsample/${n}/${s.key}/${r}`,{},Me.cj)).then(o=>HL(o,s,r))}function WL(i,e){(0,p.Rf)(i);const t=(0,p.cQ)(i,"voxel_size",o=>(0,p.vS)(o,p.by)),n=(0,p.cQ)(i,"extent",o=>(0,p.vS)(o,p.gG)),s=(0,p.cQ)(i,"num_hierarchy_levels",p.bX),r=new Array;for(let o=0;o<s;o++){const a=String(o),l=t.get(a),c=n.get(a);if(l===void 0||c===void 0)throw new Error(`Missing voxel_size/extent for resolution ${a}.`);const d=new Float32Array(3);for(let u=0;u<3;++u)d[u]=l[u]/e[u];r[o]={downsampleFactors:d,imageSize:c,key:a}}return r}function HL(i,e,t){const n=e.coordFrame;if(n===void 0)throw new Error(`Missing coordinate frame information for experiment ${e.key}. A valid coordinate frame is required to retrieve downsampling information.`);const s=e.channels.get(t);if(s===void 0)throw new Error(`Specified channel ${JSON.stringify(t)} is not one of the supported channels ${JSON.stringify(Array.from(e.channels.keys()))}`);return s.scales=WL(i,n.voxelSizeBaseInOriginalUnits),e.channels.set(t,s),e}function JL(i,e,t,n){const s=n.match($L);if(s===null)throw new Error(`Invalid volume path ${JSON.stringify(n)}`);const r=s[1],o=s[2],a=s[3],l=(0,p.bL)(s[4]||"");return i.memoize.getUncounted({hostname:e,path:n,type:"boss:getVolume"},async()=>{const c=await cS(i,e,t,o,r),d=await zL(i,e,t,r,c,a),u=new UL(i,e,t,d,a,l),h=d.coordFrame,f={lowerBounds:h.voxelOffsetBase,upperBounds:Float64Array.from(h.imageSizeBase,(v,y)=>h.voxelOffsetBase[y]+v)},m=ke({rank:3,names:h.names,units:["m","m","m"],scales:h.voxelSizeBaseInMeters,boundingBoxes:[dn(f)]});return{modelTransform:yt(m),subsources:[{id:"default",default:!0,subsource:{volume:u}},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(f)}}]}})}const dS=/^((?:http|https):\/\/[^/?]+)\/(.*)$/;function jL(i,e,t){return i.memoize.getUncounted({hostname:e,type:"boss:getCollections"},()=>Ws(t,`${e}/latest/collection/`,{},Me.cj).then(n=>(0,p.cQ)(n,"collections",s=>(0,p.$v)(s,p.zr))))}function YL(i,e,t,n){return i.memoize.getUncounted({hostname:e,collection:n,type:"boss:getExperiments"},()=>Ws(t,`${e}/latest/collection/${n}/experiment/`,{},Me.cj).then(s=>(0,p.cQ)(s,"experiments",r=>(0,p.$v)(r,p.zr))))}function QL(i,e,t,n){const s=n.coordFrameKey;return i.memoize.getUncounted({hostname:e,coordinateframe:s,experimentInfo:n,type:"boss:getCoordinateFrame"},()=>Ws(t,`${e}/latest/coord/${s}/`,{},Me.cj).then(r=>VL(r,n)))}function qL(i,e,t,n){const s=n.match(/^(?:([^/]+)(?:\/?([^/]*)(?:\/?([^/]*)(?:\/?([^/]*)?))?)?)?$/);if(s===null||s[1]===void 0)return Promise.reject(null);if(s[2]===void 0){const r=s[1]||"";return jL(i,e,t).then(o=>({offset:0,completions:Wt(r,o,a=>a+"/",()=>{})}))}if(s[3]===void 0){const r=s[2]||"";return YL(i,e,t,s[1]).then(o=>({offset:s[1].length+1,completions:Wt(r,o,a=>a+"/",()=>{})}))}return cS(i,e,t,s[2],s[1]).then(r=>{const o=Wt(s[3],r.channels,a=>a[0],a=>`${a[1].channelType} (${I[a[1].dataType]})`);return{offset:s[1].length+s[2].length+2,completions:o}})}function KL(i){const e=i.match(/^(?:https:\/\/[^.]+([^/]+))/);if(e===null)throw new Error(`Unable to construct auth server hostname from base hostname ${i}.`);return`https://auth${e[1]}/auth`}class XL extends Ut{constructor(e){super(),this.credentialsManager=e}get description(){return"bossDB: Block & Object Storage System"}getCredentialsProvider(e){const t=KL(e);return this.credentialsManager.getCredentialsProvider(LL,t)}get(e){const t=e.providerUrl.match(dS);if(t===null)throw new Error(`Invalid boss volume path: ${JSON.stringify(e.providerUrl)}`);const n=this.getCredentialsProvider(e.providerUrl);return JL(e.chunkManager,t[1],n,t[2])}async completeUrl(e){const t=e.providerUrl.match(dS);if(t===null)throw null;const n=t[1],s=this.getCredentialsProvider(t[1]),r=t[2],o=await qL(e.chunkManager,n,s,r);return li(t[1].length+1,o)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const uS=new Map;function Nt(i,e){uS.set(i,e)}function hS(i){const e=new aT(i.credentialsManager);for(const[t,n]of uS)try{e.register(t,n(i))}catch(s){console.warn(`Skipping ${t} data source: ${s}`)}return e}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("boss",i=>new XL(i.credentialsManager));/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const pS="google-brainmaps";function Hs(i,e,t,n=at.fx){return(0,zs.Y)(e,`${i.serverUrl}${t.path}`,{method:t.method,body:t.payload},t.responseType==="json"?Me.cj:Me.Rc,n)}var Jt=G(2020);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ZL extends Ke(st()(Mn),Jt.CR){}class e1 extends Ke(st()(ba),Jt.Ip){}class t1 extends Ke(st()(pi),Jt.Ve){}class n1 extends Ke(st()(Br),Jt.NV){}class i1 extends Ke(st()(Xo),Jt.Rw){}const Jr=new Map;Jr.set("UINT8",I.UINT8),Jr.set("FLOAT",I.FLOAT32),Jr.set("UINT32",I.UINT32),Jr.set("UINT64",I.UINT64);function s1(i){(0,p.Rf)(i);try{return{corner:(0,p.cQ)(i,"corner",e=>(0,p.DW)(w.eR.create(),e,p.zo)),size:(0,p.cQ)(i,"size",e=>(0,p.DW)(w.eR.create(),e,p.Mo)),metadata:(0,p.cQ)(i,"metadata",p.z$)}}catch(e){throw new Error(`Failed to parse bounding box: ${e.message}`)}}class r1{constructor(e){try{(0,p.Rf)(e),this.numChannels=(0,p.cQ)(e,"channelCount",p.We),this.dataType=(0,p.cQ)(e,"channelType",t=>(0,p.j3)(t,Jr)),this.voxelSize=(0,p.cQ)(e,"pixelSize",t=>(0,p.DW)(w.eR.create(),t,p.Mo)),this.upperVoxelBound=(0,p.cQ)(e,"volumeSize",t=>(0,p.DW)(w.eR.create(),t,p.We)),this.boundingBoxes=(0,p.cQ)(e,"boundingBox",t=>t===void 0?[]:(0,p.$v)(t,s1))}catch(t){throw new Error(`Failed to parse BrainMaps volume geometry: ${t.message}`)}}}function o1(i){return(0,p.Rf)(i),{name:(0,p.cQ)(i,"name",p.zr),type:(0,p.cQ)(i,"type",p.zr)}}function a1(i){try{return(0,p.Rf)(i),(0,p.cQ)(i,"meshes",e=>e===void 0?[]:(0,p.$v)(e,o1))}catch(e){throw new Error(`Failed to parse BrainMaps meshes specification: ${e.message}`)}}const l1="([0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?)",fu="([0-9]+)",fS=new RegExp(`^(.*)_${fu}x${fu}x${fu}_lod([0-9]+)_${l1}$`);function c1(i,e){const t=new Map,n=i.scales[0],s=new Set;for(const o of e){if(o.type!=="TRIANGLES")continue;const a=o.name.match(fS);if(a===null)continue;const l=a[1];let c=t.get(l);c===void 0&&(c={key:l,chunkShape:w.eR.create(),lods:[]},t.set(l,c));const d=parseInt(a[5]);if(c.lods[d]!==void 0){s.add(l);continue}const u=w.eR.fromValues(parseInt(a[2],10),parseInt(a[3],10),parseInt(a[4],10)),h=new Uint32Array(3);for(let f=0;f<3;++f)h[f]=Math.ceil(n.upperVoxelBound[f]/u[f]);c.lods[d]={info:o,scale:parseFloat(a[6]),relativeBlockShape:u,gridShape:h}}const r=[];e:for(const o of t.values()){if(s.has(o.key))continue;const a=o.lods[0];if(a===void 0)continue;const l=a.relativeBlockShape;w.eR.multiply(o.chunkShape,l,n.voxelSize);for(let c=1;c<o.lods.length;++c){const d=o.lods[c];if(d===void 0)continue e;const{relativeBlockShape:u}=d;for(let h=0;h<3;++h){const f=u[h],m=l[h];if(f<m||f%m!==0)continue e;u[h]=f/m}}l.fill(1),r.push(o)}return r}function d1(i,e){const t=c1(i,e),n=[],s=o=>{n.some(a=>a.name===o.name)||n.push(o)},r=new Set;for(const o of t){s({multi:o,single:void 0,name:o.key,partOfMultiscale:!1});for(const a of o.lods)r.add(a.info)}for(const o of e)s({single:o,multi:void 0,name:o.name,partOfMultiscale:r.has(o)});return n}class u1{constructor(e){try{(0,p.Rf)(e);const t=this.scales=(0,p.cQ)(e,"geometry",o=>(0,p.$v)(o,a=>new r1(a)));if(t.length===0)throw new Error("Expected at least one scale.");const n=t[0],s=this.numChannels=n.numChannels,r=this.dataType=n.dataType;for(let o=1,a=t.length;o<a;++o){const l=t[o];if(l.dataType!==r)throw new Error(`Scale ${o} has data type ${I[l.dataType]} but scale 0 has data type ${I[r]}.`);if(l.numChannels!==s)throw new Error(`Scale ${o} has ${l.numChannels} channel(s) but scale 0 has ${s} channels.`)}this.box={lowerBounds:new Float64Array(3),upperBounds:new Float64Array(n.upperVoxelBound)}}catch(t){throw new Error(`Failed to parse BrainMaps multiscale volume specification: ${t.message}`)}}getModelSpace(e=!1){const t=this.scales[0],n=["x","y","z"],s=["m","m","m"],r=Array.from(t.voxelSize,l=>l/1e9),o=[0,0,0],a=Array.from(t.upperVoxelBound);return e&&(n.push("c^"),s.push(""),r.push(1),o.push(0),a.push(this.numChannels)),ke({names:n,units:s,scales:Float64Array.from(r),boundingBoxes:[dn({lowerBounds:new Float64Array(n.length),upperBounds:Float64Array.from(a)})]})}}class h1 extends Ht{constructor(e,t,n,s,r,o,a){super(e),this.instance=t,this.credentialsProvider=n,this.volumeId=s,this.changeSpec=r,this.multiscaleVolumeInfo=o,this.encoding=a.encoding,this.jpegQuality=a.jpegQuality,this.chunkLayoutPreference=a.chunkLayoutPreference;let l=gt.IMAGE;this.dataType===I.UINT64&&(l=gt.SEGMENTATION),this.volumeType=l}get scales(){return this.multiscaleVolumeInfo.scales}get dataType(){return this.multiscaleVolumeInfo.dataType}get rank(){return this.multiscaleVolumeInfo.numChannels!==1?4:3}getSources(e){let t=Jt.r7.RAW;(this.dataType===I.UINT64||this.dataType===I.UINT32)&&this.volumeType===gt.SEGMENTATION&&this.encoding!==Jt.r7.RAW?t=Jt.r7.COMPRESSED_SEGMENTATION:this.volumeType===gt.IMAGE&&this.dataType===I.UINT8&&this.multiscaleVolumeInfo.numChannels===1&&this.encoding!==Jt.r7.RAW&&e.discreteValues!==!0&&(t=Jt.r7.JPEG);const n=t===Jt.r7.JPEG?this.jpegQuality:void 0,s=this.scales[0],{upperVoxelBound:r}=s,o=w.eR.create(),{rank:a}=this;return(0,z.RO)(this.scales.map((l,c)=>{w.eR.divide(o,l.voxelSize,s.voxelSize);let d=l.upperVoxelBound,u;const{numChannels:h}=l,f=new Float32Array((a+1)**2);f[(a+1)*a+a]=1;const m=new Float32Array(a);h!==1&&(d=Float32Array.of(...d,h),u=Uint32Array.of(1,1,1,h),f[(a+1)*3+3]=1,m[3]=h);for(let g=0;g<3;++g)f[(a+1)*g+g]=o[g],m[g]=r[g]/o[g];return gi({rank:a,minBlockSize:u,chunkToMultiscaleTransform:f,dataType:l.dataType,upperVoxelBound:d,volumeType:this.volumeType,volumeSourceOptions:e,chunkLayoutPreference:this.chunkLayoutPreference,maxCompressedSegmentationBlockSize:w.eR.fromValues(64,64,64)}).map(g=>({chunkSource:this.chunkManager.getChunkSource(ZL,{credentialsProvider:this.credentialsProvider,spec:g,parameters:{volumeId:this.volumeId,changeSpec:this.changeSpec,scaleIndex:c,encoding:t,jpegQuality:n,instance:this.instance}}),chunkToMultiscaleTransform:f,upperClipBound:m}))}))}}function p1(i){const e=w.pB.create(),t=i.scales[0].voxelSize;for(let n=0;n<3;++n)e[5*n]=1/t[n];return e}function f1(i){const e=i.match(/^([^:?/]+:[^:?/]+:[^:?/]+)(?::([^:?/]+))?(?:\/([^?]+))?(?:\?(.*))?$/);if(e===null)throw new Error(`Invalid Brain Maps volume key: ${JSON.stringify(i)}.`);let t;e[2]!==void 0&&(t={changeStackId:e[2]});const n=(0,p.bL)(e[4]||"");return{volumeId:e[1],changeSpec:t,meshName:e[3],parameters:n}}function g1(i){try{return(0,p.Rf)(i),{id:(0,p.cQ)(i,"id",p.zr),label:(0,p.cQ)(i,"label",p.zr),description:(0,p.cQ)(i,"description",p.z$)}}catch(e){throw new Error(`Failed to parse project: ${e.message}`)}}function gS(i){try{return(0,p.Rf)(i),(0,p.cQ)(i,"project",e=>e===void 0?[]:(0,p.$v)(e,g1))}catch(e){throw new Error(`Error parsing project list: ${e.message}`)}}function mS(i,e){try{return(0,p.Rf)(i),(0,p.cQ)(i,e,t=>t===void 0?[]:(0,p.$v)(t,p.zr))}catch(t){throw new Error(`Error parsing dataset list: ${t.message}`)}}class $_{constructor(e,t){this.projects=new Map,this.hierarchicalVolumeIds=new Map;const{projects:n}=this;for(const s of gS(e))n.set(s.id,s);try{verifyObject(t);const s=this.volumeIds=verifyObjectProperty(t,"volumeId",a=>a===void 0?[]:parseArray(a,verifyString));s.sort();const r=new Map;for(const a of s){let l=0;for(;;){let c=a.indexOf(":",l);c===-1?c=void 0:++c;const d=a.substring(0,l);let u=r.get(d);if(u===void 0&&(u=new Set,r.set(d,u)),u.add(a.substring(l,c)),c===void 0)break;l=c}}const{hierarchicalVolumeIds:o}=this;for(const[a,l]of r)o.set(a,Array.from(l))}catch(s){throw new Error(`Failed to parse Brain Maps volume list reply: ${s.message}`)}}}function m1(i){return(0,p.cQ)(i,"changeStackId",e=>e===void 0?void 0:(0,p.$v)(e,p.zr))}const v1=Ke(st()(Tr),Jt.rl);class y1 extends v1{constructor(e,t){super(e,{rank:3,relationships:["segments"],properties:[],...t}),this.credentialsProvider=this.registerDisposer(t.credentialsProvider.addRef())}hasNonSerializedProperties(){return!0}getSources(){const{upperVoxelBound:e}=this.parameters,t=zo({rank:3,chunkDataSize:e,upperVoxelBound:e}),n=w.pB.create();return[[{chunkSource:this.chunkManager.getChunkSource(i1,{parent:this,spec:{limit:0,chunkToMultiscaleTransform:n,...t},parameters:this.parameters,credentialsProvider:this.credentialsProvider}),chunkToMultiscaleTransform:n}]]}}const S1=[{key:{value:"encoding",description:"Volume chunk data encoding"},values:[{value:"raw",description:""},{value:"jpeg",description:""},{value:"compressed_segmentation",description:""}]},{key:{value:"chunkLayout",description:"Volume chunk layout preference"},values:[{value:"isotropic",description:""},{value:"flat",description:""}]},{key:{value:"jpegQuality",description:"JPEG quality (1 to 100)"},values:[]}];class vS extends Ut{constructor(e,t){super(),this.instance=e,this.credentialsProvider=t}get description(){return this.instance.description}getMultiscaleInfo(e,t){return e.memoize.getUncounted({type:"brainmaps:getMultiscaleInfo",volumeId:t,instance:this.instance,credentialsProvider:St(this.credentialsProvider)},()=>Hs(this.instance,this.credentialsProvider,{method:"GET",path:`/v1beta2/volumes/${t}`,responseType:"json"}).then(n=>new u1(n)))}getMeshesInfo(e,t){return e.memoize.getUncounted({type:"brainmaps:getMeshesInfo",volumeId:t,instance:this.instance,credentialsProvider:St(this.credentialsProvider)},()=>Hs(this.instance,this.credentialsProvider,{method:"GET",path:`/v1beta2/objects/${t}/meshes`,responseType:"json"}).then(n=>a1(n)))}get(e){const{volumeId:t,changeSpec:n,meshName:s,parameters:r}=f1(e.providerUrl);(0,p.Rf)(r);const o=(0,p.MM)(r,"encoding",d=>(0,p.sl)(d,Jt.r7)),a=(0,p.MM)(r,"jpegQuality",d=>{const u=(0,p.bX)(d);if(u<1||u>100)throw new Error(`Expected integer in range [1, 100], but received: ${d}`);return u},70),l=(0,p.MM)(r,"chunkLayout",d=>(0,p.sl)(d,Vi)),c={encoding:o,chunkLayoutPreference:l,jpegQuality:a};return e.chunkManager.memoize.getUncounted({type:"brainmaps:get",instance:this.instance,volumeId:t,changeSpec:n,brainmapsOptions:c},async()=>{const[d,u]=await Promise.all([this.getMultiscaleInfo(e.chunkManager,t),this.getMeshesInfo(e.chunkManager,t)]),h=new h1(e.chunkManager,this.instance,this.credentialsProvider,t,n,d,c),f={modelTransform:yt(d.getModelSpace(d.numChannels!==1)),subsources:[{id:s===void 0?"default":"volume",subsource:{volume:h},default:s===void 0}]},m=cn(d.box);d.scales[0].boundingBoxes.forEach((S,x)=>{m.add({type:Je.AXIS_ALIGNED_BOUNDING_BOX,description:S.metadata,pointA:S.corner,pointB:w.eR.add(w.eR.create(),S.corner,S.size),id:`boundingBox${x}`,properties:[]})}),f.subsources.push({id:"bounds",subsource:{staticAnnotations:m},default:!0});const v=d1(d,u),y=(S,x)=>{let b;const{single:E}=S;if(E!==void 0)E.type==="TRIANGLES"?b=e.chunkManager.getChunkSource(t1,{credentialsProvider:this.credentialsProvider,parameters:{instance:this.instance,volumeId:t,meshName:E.name,changeSpec:n}}):b=e.chunkManager.getChunkSource(n1,{credentialsProvider:this.credentialsProvider,parameters:{instance:this.instance,volumeId:t,meshName:S.name,changeSpec:n}});else{const C=S.multi;b=e.chunkManager.getChunkSource(e1,{credentialsProvider:this.credentialsProvider,format:{fragmentRelativeVertices:!1,vertexPositionFormat:yn.Pc.float32},parameters:{instance:this.instance,volumeId:t,info:C,changeSpec:n}})}f.subsources.push({id:s===void 0?`/${S.name}`:"default",subsource:{mesh:b},subsourceToModelSubspaceTransform:p1(d),modelSubspaceDimensionIndices:[0,1,2],default:x})};if(s!==void 0){const S=v.find(x=>x.name===s);if(S===void 0)throw new Error(`Mesh/skeleton source not found: ${JSON.stringify(S)}`);y(S,!0)}else{let S=!0;for(const x of v)x.partOfMultiscale||(y(x,S),S=!1)}return n!==void 0&&f.subsources.push({id:"spatials",default:!0,modelSubspaceDimensionIndices:[0,1,2],subsource:{annotation:e.chunkManager.getChunkSource(y1,{parameters:{volumeId:t,changestack:n.changeStackId,instance:this.instance,upperVoxelBound:d.scales[0].upperVoxelBound},credentialsProvider:this.credentialsProvider})}}),f})}getProjectList(e){return e.memoize.getUncounted({instance:this.instance,type:"brainmaps:getProjectList"},()=>{const t=Hs(this.instance,this.credentialsProvider,{method:"GET",path:"/v1beta2/projects",responseType:"json"}).then(s=>gS(s)),n=`${this.instance.description} project list`;return Se.forPromise(t,{delay:!0,initialMessage:`Retrieving ${n}.`,errorPrefix:`Error retrieving ${n}: `}),t})}getDatasetList(e,t){return e.memoize.getUncounted({instance:this.instance,type:`brainmaps:${t}:getDatasetList`},()=>{const n=Hs(this.instance,this.credentialsProvider,{method:"GET",path:`/v1beta2/datasets?project_id=${t}`,responseType:"json"}).then(r=>mS(r,"datasetIds")),s=`${this.instance.description} dataset list`;return Se.forPromise(n,{delay:!0,initialMessage:`Retrieving ${s}`,errorPrefix:`Error retrieving ${s}`}),n})}getVolumeList(e,t,n){return e.memoize.getUncounted({instance:this.instance,type:`brainmaps:${t}:${n}:getVolumeList`},()=>{const s=Hs(this.instance,this.credentialsProvider,{method:"GET",path:`/v1beta2/volumes?project_id=${t}&dataset_id=${n}`,responseType:"json"}).then(o=>{const a=mS(o,"volumeId"),l=t.length+n.length+2,c=[];for(const d of a)c.push(d.substring(l));return c}),r=`${this.instance.description} volume list`;return Se.forPromise(s,{delay:!0,initialMessage:`Retrieving ${r}`,errorPrefix:`Error retrieving ${r}`}),s})}getChangeStackList(e,t){return e.memoize.getUncounted({instance:this.instance,type:"brainmaps:getChangeStackList",volumeId:t},()=>{const n=Hs(this.instance,this.credentialsProvider,{method:"GET",path:`/v1beta2/changes/${t}/change_stacks`,responseType:"json"}).then(r=>m1(r)),s=`change stacks for ${t}`;return Se.forPromise(n,{delay:!0,initialMessage:`Retrieving ${s}.`,errorPrefix:`Error retrieving ${s}: `}),n})}async completeUrl(e){const{providerUrl:t}=e,n=t.match(/^([^:/?]*)(?::([^:/?]*)(?::([^:/?]*)(?::([^:/?]*))?(?:\/([^?]*))?(?:\?(.*))?)?)?$/);if(n===null)throw null;const[,s,r,o,a,l,c]=n;if(c!==void 0)return li(t.length-c.length,await cg(c,S1));if(l!==void 0){const u=`${s}:${r}:${o}`,h=await this.getMeshesInfo(e.chunkManager,u),f=[],m=new Set;for(const g of h)if(g.name.startsWith(l))switch(g.type){case"LINE_SEGMENTS":f.push({value:g.name,description:"Skeletons"});break;case"TRIANGLES":{f.push({value:g.name,description:"Mesh (single-resolution)"});const v=g.name.match(fS);if(v!==null){const y=v[1];if(m.has(y))break;m.add(y),f.push({value:y,description:"Mesh (multi-resolution)"})}break}}return f.sort((g,v)=>(0,Dr.e)(g.value,v.value)),{offset:t.length-l.length,completions:f}}if(a!==void 0){const u=`${s}:${r}:${o}`,h=await this.getChangeStackList(e.chunkManager,u);if(h===void 0)throw null;return{offset:t.length-a.length,completions:Oc(a,h)}}if(o!==void 0)return{offset:t.length-o.length,completions:Oc(o,await this.getVolumeList(e.chunkManager,s,r))};if(r!==void 0){const u=await this.getDatasetList(e.chunkManager,s);return{offset:t.length-r.length,completions:Oc(r,u.map(h=>`${h}:`))}}const d=await this.getProjectList(e.chunkManager);return{offset:0,completions:Wt(s,d,u=>`${u.id}:`,u=>u.label)}}}const b1={description:"Google Brain Maps",serverUrl:"https://brainmaps.googleapis.com"};/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */if(Nt("brainmaps",i=>new vS(b1,i.credentialsManager.getCredentialsProvider(pS))),typeof NEUROGLANCER_BRAINMAPS_SERVERS<"u")for(const[i,e]of Object.entries(NEUROGLANCER_BRAINMAPS_SERVERS))Nt(`brainmaps-${i}`,t=>new vS(e,t.credentialsManager.getCredentialsProvider(pS)));var yS=G(5990);/**
 * @license
 * This work is a derivative of the Google Neuroglancer project,
 * Copyright 2016 Google Inc.
 * The Derivative Work is covered by
 * Copyright 2019 Howard Hughes Medical Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const SS="DVID";class G_{constructor(e,t){this.baseUrl=e,this.nodeKey=t}getNodeApiUrl(e=""){return`${this.baseUrl}/api/node/${this.nodeKey}${e}`}getRepoInfoUrl(){return`${this.baseUrl}/api/repos/info`}getKeyValueUrl(e,t){return`${this.getNodeApiUrl()}/${e}/key/${t}`}getKeyValueRangeUrl(e,t,n){return`${this.getNodeApiUrl()}/${e}/keyrange/${t}/${n}`}getKeyValuesUrl(e){return`${this.getNodeApiUrl()}/${e}/keyvalues?jsontar=false`}}function z_(i,e){return i.includes("?")?i+="&":i+="?",i+="app=Neuroglancer",e&&(i+=`&u=${e}`),i}function gu(i){return i.text()}function W_(i,e=uncancelableToken){const t=`${i.url}`,n={method:i.method,body:i.payload};return i.responseType===""?cancellableFetchOk(t,n,gu,e):cancellableFetchOk(t,n,responseJson,e)}function w1(i,e,t=at.fx){return C1(i,e.url,{method:e.method,body:e.payload},e.responseType===""?gu:e.responseType==="json"?Me.cj:Me.Rc,t)}function C1(i,e,t,n,s=at.fx){return(0,hu.R)(i,e,t,n,(r,o)=>{const a={...o};return r.token&&(a.headers={...a.headers,Authorization:`Bearer ${r}`}),a},r=>{const{status:o}=r;if(o===403||o===401)return"refresh";throw r},s)}var Vt=G(3819);/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function x1(i,e,t,n,s){const r=await(0,zs.Y)(i,`https://www.googleapis.com/storage/v1/b/${e}/o?delimiter=${encodeURIComponent(n)}&prefix=${encodeURIComponent(t)}&neuroglancerOrigin=${encodeURIComponent(location.origin)}`,{},Me.cj,s);(0,p.Rf)(r);const o=(0,p.MM)(r,"prefixes",p.si,[]),a=(0,p.MM)(r,"items",l=>(0,p.$v)(l,c=>((0,p.Rf)(c),(0,p.cQ)(c,"name",p.zr))),[]).filter(l=>!l.endsWith("_$folder$"));return[...o,...a]}async function E1(i,e,t,n,s){if(!n.startsWith("/"))throw null;const o=await x1(i,t,n.substring(1),"/",s),a=n.lastIndexOf("/");return{offset:a+e.length+1,completions:o.map(l=>({value:l.substring(a)}))}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function T1(i,e,t){const{text:n,contentType:s}=await rn(t,i,{headers:{accept:"text/html"}},async l=>({text:await l.text(),contentType:l.headers.get("content-type")}),e);if(s===null||/\btext\/html\b/i.exec(s)===null)return[];const r=new DOMParser().parseFromString(n,"text/html"),o=r.evaluate("//a/@href",r,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null),a=[];for(let l=0,c=o.snapshotLength;l<c;++l){const u=o.snapshotItem(l).textContent;u&&a.push(new URL(u,i).toString())}return a}async function D1(i,e,t){console.log("getHtmlPathCompletions");const n=i.match(/^([a-z]+:\/\/.*\/)([^/?#]*)$/);if(n===null)throw null;const s=await T1(n[1],e,t),r=n[1].length,o=[];for(const a of s)a.startsWith(i)&&o.push({value:a.substring(r)});return{offset:r,completions:o}}const I1=[{value:"gs://",description:"Google Cloud Storage (JSON API)"},{value:"gs+xml://",description:"Google Cloud Storage (XML API)"},{value:"gs+ngauth+http://",description:"Google Cloud Storage (JSON API) authenticated via ngauth"},{value:"gs+ngauth+https://",description:"Google Cloud Storage (JSON API) authenticated via ngauth"},{value:"gs+xml+ngauth+http://",description:"Google Cloud Storage (XML API) authenticated via ngauth"},{value:"gs+xml+ngauth+https://",description:"Google Cloud Storage (XML API) authenticated via ngauth"},{value:"s3://",description:"Amazon Simple Storage Service (S3)"},{value:"https://"},{value:"http://"}];async function Ki(i,e,t){if(!e.includes("://"))return{offset:0,completions:Wt(e,I1,u=>u.value,u=>u.description)};const{url:n,credentialsProvider:s}=bn(e,i),r=e.length-n.length;let o;try{o=(0,Me.Dl)(n)}catch{throw null}const{protocol:a,host:l,path:c}=o,d=await(async()=>{if(a==="gs+xml"&&c.length>0)return await uu(s,`${a}://${l}`,`https://storage.googleapis.com/${l}`,c,t);if(a==="gs"&&c.length>0)return await E1(s,`${a}://${l}`,l,c,t);if(a==="s3"&&c.length>0)return await aL(l,c,t);const u=n.match(/^((?:http|https):\/\/(?:storage\.googleapis\.com\/[^/]+|[^/]+\.storage\.googleapis\.com|[^/]+\.s3(?:[^./]+)?\.amazonaws.com))(\/.*)$/);if(u!==null)return await uu(s,u[1],u[1],u[2],t);if((a==="http"||a==="https")&&c.length>0)return await D1(n,t,s);throw null})();return{offset:r+d.offset,completions:d.completions}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class R1 extends Ke(st()(Mn),Vt.jj){}class k1 extends Ke(st()(pi),Vt.Ve){}class L1 extends Ke(st()(ba),Vt.Ip){}class P1 extends Ke(st()(Br),Vt.NV){get skeletonVertexCoordinatesInVoxels(){return!1}get vertexAttributes(){return this.parameters.metadata.vertexAttributes}}function Nn(i,e){const t=i.split("/");for(const n of e.split("/")){if(n===".."&&t.length!==0){t.length=t.length-1;continue}t.push(n)}return t.join("/")}class A1{constructor(e,t){(0,p.Rf)(e);const n=t===1?3:4,s=this.resolution=new Float64Array(n),r=this.voxelOffset=new Float32Array(n),o=this.size=new Float32Array(n);if(n===4&&(s[3]=1,o[3]=t),(0,p.cQ)(e,"resolution",l=>(0,p.Xu)(s.subarray(0,3),l,p.Mo)),(0,p.MM)(e,"voxel_offset",l=>(0,p.Xu)(r.subarray(0,3),l,p.bX)),(0,p.cQ)(e,"size",l=>(0,p.Xu)(o.subarray(0,3),l,p.We)),this.chunkSizes=(0,p.cQ)(e,"chunk_sizes",l=>(0,p.$v)(l,c=>{const d=new Uint32Array(n);return n===4&&(d[3]=t),(0,p.Xu)(d.subarray(0,3),c,p.We),d})),this.chunkSizes.length===0)throw new Error("No chunk sizes specified.");if(this.sharding=(0,p.cQ)(e,"sharding",$a),this.sharding!==void 0&&this.chunkSizes.length!==1)throw new Error("Sharding requires a single chunk size per scale");(this.encoding=(0,p.cQ)(e,"encoding",l=>(0,p.sl)(l,Vt.r7)))===Vt.r7.COMPRESSED_SEGMENTATION&&(this.compressedSegmentationBlockSize=(0,p.cQ)(e,"compressed_segmentation_block_size",l=>(0,p.Xu)(w.eR.create(),l,p.We))),this.key=(0,p.cQ)(e,"key",p.zr),this.hidden=(0,p.cQ)(e,"hidden",p.uS)??!1}}function bS(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"data_type",y=>(0,p.sl)(y,I)),t=(0,p.cQ)(i,"num_channels",p.We),n=(0,p.cQ)(i,"type",y=>(0,p.sl)(y,gt)),s=(0,p.cQ)(i,"mesh",p.z$),r=(0,p.cQ)(i,"skeletons",p.z$),o=(0,p.cQ)(i,"segment_properties",p.z$),a=(0,p.cQ)(i,"scales",y=>(0,p.$v)(y,S=>new A1(S,t)));if(a.length===0)throw new Error("Expected at least one scale");const l=a[0],c=t===1?3:4,d=new Float64Array(c),u=new Float64Array(c),h=new Float64Array(c),f=["x","y","z"],m=["m","m","m"];for(let y=0;y<3;++y)d[y]=l.resolution[y]/1e9,u[y]=l.voxelOffset[y],h[y]=u[y]+l.size[y];c===4&&(d[3]=1,h[3]=t,f[3]="c^",m[3]="");const v=ke({rank:c,names:f,units:m,scales:d,boundingBoxes:[dn({lowerBounds:u,upperBounds:h})]});return{dataType:e,volumeType:n,mesh:s,skeletons:r,segmentPropertyMap:o,scales:a,modelSpace:v}}class wS extends Ht{constructor(e,t,n,s){super(e),this.credentialsProvider=t,this.url=n,this.info=s}get dataType(){return this.info.dataType}get volumeType(){return this.info.volumeType}get rank(){return this.info.modelSpace.rank}getSources(e){const t=this.info.scales[0].resolution,{rank:n}=this;return(0,z.RO)(this.info.scales.filter(s=>!s.hidden).map(s=>{const{resolution:r}=s,o=n+1,a=new Float32Array(o*o);a[a.length-1]=1;const{lowerBounds:l,upperBounds:c}=this.info.modelSpace.boundingBoxes[0].box,d=new Float32Array(n),u=new Float32Array(n);for(let h=0;h<3;++h){const f=r[h]/t[h];a[o*h+h]=f;const m=s.voxelOffset[h];a[o*n+h]=m*f,d[h]=l[h]/f-m,u[h]=c[h]/f-m}return n===4&&(a[o*3+3]=1,d[3]=l[3],u[3]=c[3]),gi({rank:n,dataType:this.dataType,chunkToMultiscaleTransform:a,upperVoxelBound:s.size,volumeType:this.volumeType,chunkDataSizes:s.chunkSizes,baseVoxelOffset:s.voxelOffset,compressedSegmentationBlockSize:s.compressedSegmentationBlockSize,volumeSourceOptions:e}).map(h=>({chunkSource:this.chunkManager.getChunkSource(R1,{credentialsProvider:this.credentialsProvider,spec:h,parameters:{url:Nn(this.url,s.key),encoding:s.encoding,sharding:s.sharding}}),chunkToMultiscaleTransform:a,lowerClipBound:d,upperClipBound:u}))}))}}const M1=Ke(st()(Tr),Vt.rl);class N1 extends Ke(st()(Xo),Vt.Rw){}class O1 extends M1{constructor(e,t){const{parameters:n}=t;super(e,{rank:n.rank,relationships:n.relationships.map(s=>s.name),properties:n.properties,parameters:n}),this.readonly=!0,this.metadata=t.metadata,this.credentialsProvider=t.credentialsProvider}getSources(){return[this.metadata.spatialIndices.map(e=>{const{spec:t}=e;return{chunkSource:this.chunkManager.getChunkSource(N1,{credentialsProvider:this.credentialsProvider,parent:this,spec:t,parameters:e.parameters}),chunkToMultiscaleTransform:t.chunkToMultiscaleTransform}})]}}function V1(i,e,t){return i.getChunkSource(k1,{parameters:t,credentialsProvider:e})}function CS(i){return(0,p.cQ)(i,"transform",e=>{const t=w.pB.create();return e!==void 0&&(0,p.Xu)(t.subarray(0,12),e,p.zo),w.pB.transpose(t,t),t})}function _1(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"@type",p.zr);let t;if(e==="neuroglancer_legacy_mesh")t=void 0;else{if(e!=="neuroglancer_multilod_draco")throw new Error(`Unsupported mesh type: ${JSON.stringify(e)}`);{const s=(0,p.cQ)(i,"lod_scale_multiplier",p.Mo),r=(0,p.cQ)(i,"vertex_quantization_bits",p.We),o=CS(i),a=(0,p.cQ)(i,"sharding",$a);t={lodScaleMultiplier:s,transform:o,sharding:a,vertexQuantizationBits:r}}}const n=(0,p.cQ)(i,"segment_properties",p.z$);return{metadata:t,segmentPropertyMap:n}}async function B1(i,e,t){let n;try{n=await Js(i,e,t)}catch(s){if((0,Me.El)(s))return{metadata:void 0};throw s}return _1(n)}function xS(i){return i===void 0?Vt.Y1.RAW:(0,p.sl)(i,Vt.Y1)}function $a(i){if(i===void 0)return;(0,p.Rf)(i);const e=(0,p.cQ)(i,"@type",p.zr);if(e!=="neuroglancer_uint64_sharded_v1")throw new Error(`Unsupported sharding format: ${JSON.stringify(e)}`);const t=(0,p.cQ)(i,"hash",l=>(0,p.sl)(l,Vt.TV)),n=(0,p.cQ)(i,"preshift_bits",p.bX),s=(0,p.cQ)(i,"shard_bits",p.bX),r=(0,p.cQ)(i,"minishard_bits",p.bX),o=(0,p.cQ)(i,"minishard_index_encoding",xS),a=(0,p.cQ)(i,"data_encoding",xS);return{hash:t,preshiftBits:n,shardBits:s,minishardBits:r,minishardIndexEncoding:o,dataEncoding:a}}function F1(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"@type",p.zr);if(e!=="neuroglancer_skeletons")throw new Error(`Unsupported skeleton type: ${JSON.stringify(e)}`);const t=CS(i),n=new Map;(0,p.cQ)(i,"vertex_attributes",o=>{o!==void 0&&(0,p.$v)(o,a=>{(0,p.Rf)(a);const l=(0,p.cQ)(a,"id",p.zr);if(l==="")throw new Error("vertex attribute id must not be empty");if(n.has(l))throw new Error(`duplicate vertex attribute id ${JSON.stringify(l)}`);const c=(0,p.cQ)(a,"data_type",u=>(0,p.sl)(u,I)),d=(0,p.cQ)(a,"num_components",p.We);n.set(l,{dataType:c,numComponents:d})})});const s=(0,p.cQ)(i,"sharding",$a),r=(0,p.cQ)(i,"segment_properties",p.z$);return{metadata:{transform:t,vertexAttributes:n,sharding:s},segmentPropertyMap:r}}async function U1(i,e,t){const n=await Js(i,e,t);return F1(n)}function ES(){return ke({names:["x","y","z"],units:["m","m","m"],scales:Float64Array.of(1e-9,1e-9,1e-9)})}async function TS(i,e,t){const{metadata:n,segmentPropertyMap:s}=await B1(i,e,t);if(n===void 0)return{source:V1(i,e,{url:t,lod:0}),transform:w.pB.create(),segmentPropertyMap:s};let r;const{vertexQuantizationBits:o}=n;if(o===10)r=yn.Pc.uint10;else if(o===16)r=yn.Pc.uint16;else throw new Error(`Invalid vertex quantization bits: ${o}`);return{source:i.getChunkSource(L1,{credentialsProvider:e,parameters:{url:t,metadata:n},format:{fragmentRelativeVertices:!0,vertexPositionFormat:r}}),transform:n.transform,segmentPropertyMap:s}}async function DS(i,e,t){const{metadata:n,segmentPropertyMap:s}=await U1(i,e,t);return{source:i.getChunkSource(P1,{credentialsProvider:e,parameters:{url:t,metadata:n}}),transform:n.transform,segmentPropertyMap:s}}function Js(i,e,t){return i.memoize.getUncounted({type:"precomputed:metadata",url:t,credentialsProvider:St(e)},async()=>await rn(e,`${t}/info`,{},Me.cj))}function IS(i){const e=w.pB.create(),t=i.scales[0].resolution;for(let n=0;n<3;++n)e[5*n]=1/t[n];return e}async function $1(i,e,t,n){const s=bS(n),r=new wS(i.chunkManager,e,t,s),{modelSpace:o}=s,a=[{id:"default",default:!0,subsource:{volume:r}},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(o.bounds)}}];if(s.segmentPropertyMap!==void 0){const l=Nn(t,s.segmentPropertyMap),c=await Js(i.chunkManager,e,l),d=jr(i.chunkManager,e,c,l);a.push({id:"properties",default:!0,subsource:{segmentPropertyMap:d}})}if(s.mesh!==void 0){const l=Nn(t,s.mesh),{source:c,transform:d}=await TS(i.chunkManager,e,l),u=IS(s);w.pB.multiply(u,u,d),a.push({id:"mesh",default:!0,subsource:{mesh:c},subsourceToModelSubspaceTransform:u})}if(s.skeletons!==void 0){const l=Nn(t,s.skeletons),{source:c,transform:d}=await DS(i.chunkManager,e,l),u=IS(s);w.pB.multiply(u,u,d),a.push({id:"skeletons",default:!0,subsource:{mesh:c},subsourceToModelSubspaceTransform:u})}return{modelTransform:yt(o),subsources:a}}async function G1(i,e,t){const{source:n,transform:s,segmentPropertyMap:r}=await DS(i.chunkManager,e,t),o=[{id:"default",default:!0,subsource:{mesh:n},subsourceToModelSubspaceTransform:s}];if(r!==void 0){const a=Nn(t,r),l=await Js(i.chunkManager,e,a),c=jr(i.chunkManager,e,l,a);o.push({id:"properties",default:!0,subsource:{segmentPropertyMap:c}})}return{modelTransform:yt(ES()),subsources:o}}function mu(i,e){return(0,p.Rf)(e),{url:Nn(i,(0,p.cQ)(e,"key",p.zr)),sharding:(0,p.cQ)(e,"sharding",$a)}}class z1{constructor(e,t){this.url=e,(0,p.Rf)(t);const n=(0,p.cQ)(t,"dimensions",Ei),{rank:s}=n,r=(0,p.cQ)(t,"lower_bound",a=>(0,p.Xu)(new Float64Array(s),a,p.zo)),o=(0,p.cQ)(t,"upper_bound",a=>(0,p.Xu)(new Float64Array(s),a,p.zo));this.coordinateSpace=ke({rank:s,names:n.names,units:n.units,scales:n.scales,boundingBoxes:[dn({lowerBounds:r,upperBounds:o})]}),this.parameters={type:(0,p.cQ)(t,"annotation_type",a=>(0,p.sl)(a,Je)),rank:s,relationships:(0,p.cQ)(t,"relationships",a=>(0,p.$v)(a,l=>{const c=mu(e,l),d=(0,p.cQ)(l,"id",p.zr);return{...c,name:d}})),properties:(0,p.cQ)(t,"properties",bh),byId:(0,p.cQ)(t,"by_id",a=>mu(e,a))},this.spatialIndices=(0,p.cQ)(t,"spatial",a=>(0,p.$v)(a,l=>{const c=mu(e,l),d=(0,p.cQ)(l,"grid_shape",v=>(0,p.Xu)(new Float32Array(s),v,p.We)),u=(0,p.cQ)(l,"chunk_size",v=>(0,p.Xu)(new Float32Array(s),v,p.Mo)),h=(0,p.cQ)(l,"limit",p.We),f=new Float32Array(s);for(let v=0;v<s;++v)f[v]=d[v]*u[v];const m=we.DA(Float32Array,s+1);for(let v=0;v<s;++v)m[(s+1)*s+v]=r[v];const g={limit:h,chunkToMultiscaleTransform:m,...zo({rank:s,chunkDataSize:u,upperVoxelBound:f})};return g.upperChunkBound=d,{parameters:c,spec:g,limit:h}})),this.spatialIndices.reverse()}}async function W1(i,e,t,n){const s=new z1(t,n);return{modelTransform:yt(s.coordinateSpace),subsources:[{id:"default",default:!0,subsource:{annotation:i.chunkManager.getChunkSource(O1,{credentialsProvider:e,metadata:s,parameters:s.parameters})}}]}}async function RS(i,e,t){const{source:n,transform:s,segmentPropertyMap:r}=await TS(i.chunkManager,e,t),o=[{id:"default",default:!0,subsource:{mesh:n},subsourceToModelSubspaceTransform:s}];if(r!==void 0){const a=Nn(t,r),l=await Js(i.chunkManager,e,a),c=jr(i.chunkManager,e,l,a);o.push({id:"properties",default:!0,subsource:{segmentPropertyMap:c}})}return{modelTransform:yt(ES()),subsources:o}}function H1(i){(0,p.Rf)(i);const e=new M.R,t=(0,p.cQ)(i,"ids",r=>{r=(0,p.si)(r);const o=r.length,a=new Uint32Array(o*2);for(let l=0;l<o;++l){if(!e.tryParseString(r[l]))throw new Error(`Invalid uint64 id: ${JSON.stringify(r[l])}`);a[2*l]=e.low,a[2*l+1]=e.high}return a}),n=t.length/2,s=(0,p.cQ)(i,"properties",r=>(0,p.$v)(r,o=>{(0,p.Rf)(o);const a=(0,p.cQ)(o,"id",p.zr),l=(0,p.MM)(o,"description",p.zr),c=(0,p.cQ)(o,"type",u=>{if(u!=="label"&&u!=="description"&&u!=="string"&&u!=="tags"&&u!=="number")throw new Error(`Invalid property type: ${JSON.stringify(u)}`);return u});if(c==="tags"){const u=(0,p.cQ)(o,"tags",p.si);let h=(0,p.MM)(o,"tag_descriptions",p.si);if(h===void 0)h=new Array(u.length),h.fill("");else if(h.length!==u.length)throw new Error(`Expected tag_descriptions to have length: ${u.length}`);const f=(0,p.cQ)(o,"values",m=>{if(!Array.isArray(m)||m.length!==n)throw new Error(`Expected ${n} values, but received: ${m.length}`);return m.map(g=>String.fromCharCode(...g))});return{id:a,description:l,type:c,tags:u,tagDescriptions:h,values:f}}if(c==="number"){const u=(0,p.cQ)(o,"data_type",g=>(0,p.sl)(g,I));if(u===I.UINT64)throw new Error("uint64 properties not supported");const h=(0,p.cQ)(o,"values",g=>{if(!Array.isArray(g)||g.length!==n)throw new Error(`Expected ${n} values, but received: ${g.length}`);return J[u].from(g)});let f=1/0,m=-1/0;for(let g=h.length-1;g>=0;--g){const v=h[g];v<f&&(f=v),v>m&&(m=v)}return{id:a,description:l,type:c,dataType:u,values:h,bounds:[f,m]}}const d=(0,p.cQ)(o,"values",u=>{if((0,p.si)(u),u.length!==n)throw new Error(`Expected ${n} values, but received: ${u.length}`);return u});return{id:a,description:l,type:c,values:d}}));return YD({ids:t,properties:s})}const H_=Ke(st()(GD),Vt.vq);function jr(i,e,t,n){try{const s=(0,p.cQ)(t,"@type",p.zr);if(s!=="neuroglancer_segment_properties")throw new Error(`Unsupported segment property map type: ${JSON.stringify(s)}`);const r=(0,p.MM)(t,"inline",H1);return new qm({inlineProperties:r})}catch(s){throw new Error(`Error parsing segment property map: ${s.message}`)}}async function J1(i,e,t,n){return{modelTransform:yt(xi),subsources:[{id:"default",default:!0,subsource:{segmentPropertyMap:jr(i.chunkManager,e,n,t)}}]}}const j1=/^([^#]*)(?:#(.*))?$/;function Xi(i){let[,e,t]=i.match(j1);e.endsWith("/")&&(e=e.substring(0,e.length-1));const n=(0,p.bL)(t||"");return{url:e,parameters:n}}function Ga(i,e){const t=(0,p.uz)(e);return t&&(i+=`#${t}`),i}class kS extends Ut{get description(){return"Precomputed file-backed data source"}normalizeUrl(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.providerProtocol+"://"+Ga(t,n)}convertLegacyUrl(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.type==="mesh"&&(n.type="mesh"),e.providerProtocol+"://"+Ga(t,n)}get(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.chunkManager.memoize.getUncounted({type:"precomputed:get",providerUrl:t,parameters:n},async()=>{const{url:s,credentialsProvider:r}=bn(t,e.credentialsManager);let o;try{o=await Js(e.chunkManager,r,s)}catch(c){if((0,Me.El)(c)&&n.type==="mesh")return await RS(e,r,s);throw c}(0,p.Rf)(o);const a=(0,p.MM)(o,"redirect",p.zr);if(a!==void 0)throw new Vc(a);const l=(0,p.MM)(o,"@type",p.zr);switch(l){case"neuroglancer_skeletons":return await G1(e,r,s);case"neuroglancer_multilod_draco":case"neuroglancer_legacy_mesh":return await RS(e,r,s);case"neuroglancer_annotations_v1":return await W1(e,r,s,o);case"neuroglancer_segment_properties":return await J1(e,r,s,o);case"neuroglancer_multiscale_volume":case void 0:return await $1(e,r,s,o);default:throw new Error(`Invalid type: ${JSON.stringify(l)}`)}})}completeUrl(e){return Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2016 Google Inc., 2023 Gergely Csucs
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Y1 extends Ke(st()(Mn),yS.D){}function Q1(i){const{width:e,height:t,tilesize:n,overlap:s,format:r}=i,o=(0,p.sl)(r,yS.j),a=new Array;let l=e,c=t;for(;l>1||c>1;)a.push({width:l,height:c}),l=Math.ceil(l/2),c=Math.ceil(c/2);a.push({width:l,height:c});const d=3,u=Float64Array.of(1/1e9,1/1e9,1),h=new Float64Array(d),f=Float64Array.of(e,t,3),y=ke({rank:d,names:["x","y","c^"],units:["m","m",""],scales:u,boundingBoxes:[dn({lowerBounds:h,upperBounds:f})]});return{levels:a,modelSpace:y,overlap:s,tilesize:n,format:r,encoding:o}}class q1 extends Ht{constructor(e,t,n,s){super(e),this.credentialsProvider=t,this.info=s,this.url=n.substring(0,n.lastIndexOf("."))+"_files"}get dataType(){return I.UINT8}get volumeType(){return gt.IMAGE}get rank(){return this.info.modelSpace.rank}getSources(e){const{rank:t}=this,n=[Uint32Array.of(this.info.tilesize,this.info.tilesize,3)];return(0,z.RO)(this.info.levels.map((s,r,o)=>{const a=1<<r,l=t+1,c=new Float32Array(l*l);c[c.length-1]=1;const{upperBounds:d}=this.info.modelSpace.boundingBoxes[0].box,u=new Float32Array(t);for(let h=0;h<2;++h)c[l*h+h]=a,u[h]=d[h]/a;return c[l*2+2]=1,u[2]=d[2],gi({rank:t,dataType:this.dataType,chunkToMultiscaleTransform:c,upperVoxelBound:Float32Array.of(s.width,s.height,3),volumeType:this.volumeType,chunkDataSizes:n,volumeSourceOptions:e}).map(h=>({chunkSource:this.chunkManager.getChunkSource(Y1,{credentialsProvider:this.credentialsProvider,spec:h,parameters:{url:Nn(this.url,(o.length-1-r).toString()),encoding:this.info.encoding,format:this.info.format,overlap:this.info.overlap,tilesize:this.info.tilesize}}),chunkToMultiscaleTransform:c,upperClipBound:u}))}))}}function K1(i,e,t){if(t.endsWith(".json")||t.includes(".json?"))throw new Error("DZI-JSON: OpenSeadragon hack not supported yet.");return i.memoize.getUncounted({type:"deepzoom:metadata",url:t,credentialsProvider:St(e)},async()=>{const n=await rn(e,t,{},gu),r=new DOMParser().parseFromString(n,"text/xml").documentElement,o=(0,p.Rf)(r.getElementsByTagName("Size").item(0));return{width:(0,p.We)(o.getAttribute("Width")),height:(0,p.We)(o.getAttribute("Height")),tilesize:(0,p.We)((0,p.zr)(r.getAttribute("TileSize"))),overlap:(0,p.bX)((0,p.zr)(r.getAttribute("Overlap"))),format:(0,p.zr)(r.getAttribute("Format"))}})}async function X1(i,e,t,n){const s=Q1(n),r=new q1(i.chunkManager,e,t,s),{modelSpace:o}=s,a=[{id:"default",default:!0,subsource:{volume:r}},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(o.bounds)}}];return{modelTransform:yt(o),subsources:a}}class Z1 extends Ut{get description(){return"Deep Zoom file-backed data source"}normalizeUrl(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.providerProtocol+"://"+Ga(t,n)}convertLegacyUrl(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.providerProtocol+"://"+Ga(t,n)}get(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.chunkManager.memoize.getUncounted({type:"deepzoom:get",providerUrl:t,parameters:n},async()=>{const{url:s,credentialsProvider:r}=bn(t,e.credentialsManager),o=await K1(e.chunkManager,r,s);return X1(e,r,s,o)})}completeUrl(e){return Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2017 Google Inc., 2023 Gergely Csucs
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("deepzoom",()=>new Z1);var jt=G(8820);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const za=new Map;za.set("uint8",I.UINT8),za.set("uint32",I.UINT32),za.set("uint64",I.UINT64);class eP{constructor(e){this.obj=e,(0,p.Rf)(e),(0,p.cQ)(e,"TypeName",p.zr)}get typeName(){return this.obj.TypeName}get compressionName(){return this.obj.Compression}}class tP{constructor(e,t,n){this.obj=e,this.name=t,this.base=n}}class nP extends Ke(st()(Mn),jt.jj){}class iP extends Ke(st()(Br),jt.NV){}class sP extends Ke(st()(pi),jt.Ve){}class Wa extends tP{constructor(e,t,n,s,r){super(e,t,n),this.encoding=s;const o=(0,p.cQ)(e,"Extended",p.Rf),a=(0,p.cQ)(o,"Values",c=>(0,p.$v)(c,p.Rf));if(a.length<1)throw new Error("Expected Extended.Values property to have length >= 1, but received: ${JSON.stringify(extendedValues)}.");this.numLevels=1;const l=new Set(r);if(s===jt.r7.COMPRESSED_SEGMENTATIONARRAY){const c=(0,p.cQ)(o,"MaxDownresLevel",p.We);this.numLevels=c+1}else for(;l.has(t+"_"+this.numLevels.toString());)this.numLevels+=1;l.has(t+"_meshes")?this.meshSrc=t+"_meshes":this.meshSrc="",l.has(t+"_skeletons")?this.skeletonSrc=t+"_skeletons":this.skeletonSrc="",this.dataType=(0,p.cQ)(a[0],"DataType",c=>(0,p.j3)(c,za)),this.voxelSize=(0,p.cQ)(o,"VoxelSize",c=>(0,p.Xu)(w.eR.create(),c,p.Mo)),this.blockSize=(0,p.cQ)(o,"BlockSize",c=>(0,p.Xu)(w.eR.create(),c,p.Mo)),this.lowerVoxelBound=(0,p.cQ)(o,"MinPoint",c=>(0,p.vp)(w.eR.create(),c)),this.upperVoxelBoundInclusive=(0,p.cQ)(o,"MaxPoint",c=>(0,p.vp)(w.eR.create(),c))}get volumeType(){return this.encoding===jt.r7.COMPRESSED_SEGMENTATION||this.encoding===jt.r7.COMPRESSED_SEGMENTATIONARRAY?gt.SEGMENTATION:gt.IMAGE}getSources(e,t,n,s){const{encoding:r}=this,o=[],a=64;for(let l=0;l<this.numLevels;++l){const c=2**l,d=2**-l,u=w.eR.create(),h=w.eR.create();for(let y=0;y<3;++y){const S=Math.floor(this.lowerVoxelBound[y]*d);u[y]=S-S%a;const x=Math.ceil((this.upperVoxelBoundInclusive[y]+1)*d);h[y]=x,x%a!==0&&(h[y]+=a-x%a)}let f=t.dataInstanceKey;r!==jt.r7.COMPRESSED_SEGMENTATIONARRAY&&l>0&&(f+="_"+l.toString());const m={baseUrl:t.baseUrl,nodeKey:t.nodeKey,dataInstanceKey:f,dataScale:l.toString(),encoding:r},g=w.pB.create();for(let y=0;y<3;++y)g[5*y]=c,g[12+y]=u[y]*c;const v=gi({rank:3,chunkToMultiscaleTransform:g,dataType:this.dataType,baseVoxelOffset:u,upperVoxelBound:w.eR.subtract(w.eR.create(),h,u),volumeType:this.volumeType,volumeSourceOptions:n,compressedSegmentationBlockSize:r===jt.r7.COMPRESSED_SEGMENTATION||r===jt.r7.COMPRESSED_SEGMENTATIONARRAY?w.eR.fromValues(8,8,8):void 0}).map(y=>({chunkSource:e.getChunkSource(nP,{spec:y,parameters:m,credentialsProvider:s}),chunkToMultiscaleTransform:g}));o.push(v)}return(0,z.RO)(o)}}function rP(i,e,t){(0,p.Rf)(i);const n=(0,p.cQ)(i,"Base",s=>new eP(s));switch(n.typeName){case"uint8blk":case"grayscale8":{const s=n.compressionName.indexOf("jpeg")!==-1;return new Wa(i,e,n,s?jt.r7.JPEG:jt.r7.RAW,t)}case"labels64":case"labelblk":return new Wa(i,e,n,jt.r7.COMPRESSED_SEGMENTATION,t);case"labelarray":case"labelmap":return new Wa(i,e,n,jt.r7.COMPRESSED_SEGMENTATIONARRAY,t);default:throw new Error(`DVID data type ${JSON.stringify(n.typeName)} is not supported.`)}}class Ha{constructor(e){if(this.errors=[],this.dataInstances=new Map,this.vnodes=new Set,e instanceof Ha){this.alias=e.alias,this.description=e.description,this.errors=e.errors,this.dataInstances=e.dataInstances;return}(0,p.Rf)(e),this.alias=(0,p.cQ)(e,"Alias",p.zr),this.description=(0,p.cQ)(e,"Description",p.zr);const t=(0,p.cQ)(e,"DataInstances",p.Rf),n=Object.keys(t);for(const o of n)try{this.dataInstances.set(o,rP(t[o],o,n))}catch(a){const l=`Failed to parse data instance ${JSON.stringify(o)}: ${a.message}`;console.log(l),this.errors.push(l)}const s=(0,p.cQ)(e,"DAG",p.Rf),r=(0,p.cQ)(s,"Nodes",p.Rf);for(const o of Object.keys(r))this.vnodes.add(o)}}function oP(i){try{const e=(0,p.vS)(i,n=>new Ha(n)),t=new Map;for(const[n,s]of e){t.set(n,s);for(const r of s.vnodes)if(r!==n){const o=new Ha(s);t.set(r,o)}}for(const[n,s]of t)s.uuid=n;return t}catch(e){throw new Error(`Failed to parse DVID repositories info: ${e.message}`)}}class aP{constructor(e){this.repositories=oP(e)}getNode(e){const t=[];for(const n of this.repositories.keys())n.startsWith(e)&&t.push(n);if(t.length!==1)throw new Error(`Node key ${JSON.stringify(e)} matches ${JSON.stringify(t)} nodes.`);return this.repositories.get(t[0])}}function LS(i,e,t){return i.memoize.getUncounted({type:"dvid:getServerInfo",baseUrl:e},()=>{const n=w1(t,{url:`${e}/api/repos/info`,method:"GET",responseType:"json"}).then(r=>new aP(r)),s=`repository info for DVID server ${e}`;return Se.forPromise(n,{initialMessage:`Retrieving ${s}.`,delay:!0,errorPrefix:`Error retrieving ${s}: `}),n})}class lP extends Ht{constructor(e,t,n,s,r,o){super(e),this.baseUrl=t,this.nodeKey=n,this.dataInstanceKey=s,this.info=r,this.credentialsProvider=o}get dataType(){return this.info.dataType}get volumeType(){return this.info.volumeType}get rank(){return 3}getSources(e){return this.info.getSources(this.chunkManager,{baseUrl:this.baseUrl,nodeKey:this.nodeKey,dataInstanceKey:this.dataInstanceKey},e,this.credentialsProvider)}}const cP=/^((?:http|https):\/\/[^/]+)\/([^/]+)\/([^/]+)(\?.*)?$/;function PS(i){if(i.startsWith("https"))return i+"/api/server/token"}function dP(i){const e=i.match(cP);if(e===null)throw new Error(`Invalid DVID URL: ${JSON.stringify(i)}.`);const t={baseUrl:e[1],nodeKey:e[2],dataInstanceKey:e[3]},n=e[4];if(n&&n.length>1){const s=(0,p.bL)(n.substring(1));s.user&&(t.user=s.user)}return t.authServer=PS(t.baseUrl),t}function uP(i,e,t,n){const s=e.baseUrl,r=e.nodeKey,o=e.dataInstanceKey,a=t,l={lowerBounds:new Float64Array(a.lowerVoxelBound),upperBounds:Float64Array.from(a.upperVoxelBoundInclusive,h=>h+1)},c=ke({rank:3,names:["x","y","z"],units:["m","m","m"],scales:Float64Array.from(a.voxelSize,h=>h/1e9),boundingBoxes:[dn(l)]}),d=new lP(i.chunkManager,s,r,o,a,n),u={modelTransform:yt(c),subsources:[{id:"default",subsource:{volume:d},default:!0}]};if(a.meshSrc){const h=w.pB.create();for(let f=0;f<3;++f)h[5*f]=1/a.voxelSize[f];u.subsources.push({id:"meshes",default:!0,subsource:{mesh:i.chunkManager.getChunkSource(sP,{parameters:{...e,dataInstanceKey:a.meshSrc},credentialsProvider:n})},subsourceToModelSubspaceTransform:h})}return a.skeletonSrc&&u.subsources.push({id:"skeletons",default:!0,subsource:{mesh:i.chunkManager.getChunkSource(iP,{parameters:{...e,dataInstanceKey:a.skeletonSrc},credentialsProvider:n})}}),u.subsources.push({id:"bounds",subsource:{staticAnnotations:cn(l)},default:!0}),u}function hP(i){const e=dP(i.providerUrl),{baseUrl:t,nodeKey:n,dataInstanceKey:s}=e;return i.chunkManager.memoize.getUncounted({type:"dvid:MultiscaleVolumeChunkSource",baseUrl:t,nodeKey:n,dataInstanceKey:s},async()=>{const r=i.credentialsManager.getCredentialsProvider(SS,{dvidServer:e.baseUrl,authServer:e.authServer}),a=(await LS(i.chunkManager,t,r)).getNode(n);if(a===void 0)throw new Error(`Invalid node: ${JSON.stringify(n)}.`);const l=a.dataInstances.get(s);if(!(l instanceof Wa))throw new Error(`Invalid data instance ${s}.`);return uP(i,e,l,r)})}function pP(i,e){return{offset:0,completions:Wt(e,i.dataInstances.values(),t=>t.name,t=>`${t.base.typeName}`)}}function fP(i,e){const t=e.match(/^(?:([^/]+)(?:\/([^/]*))?)?$/);if(t===null)throw new Error("Invalid DVID URL syntax.");if(t[2]===void 0)return{offset:0,completions:Wt(e,i.repositories.values(),r=>r.uuid+"/",r=>`${r.alias}: ${r.description}`)};const n=t[1],s=i.getNode(n);return li(n.length+1,pP(s,t[2]))}async function gP(i){const e=/^((?:http|https):\/\/[^/]+)\/([^?]*).*$/,n=i.providerUrl.match(e);if(n===null)throw null;const s=n[1],r=n[2],o=PS(s),a=await LS(i.chunkManager,s,i.credentialsManager.getCredentialsProvider(SS,{dvidServer:s,authServer:o}));return li(s.length+1,fP(a,r))}class mP extends Ut{constructor(e){super(),this.credentialsManager=e}get description(){return"DVID"}get(e){return hP(e)}completeUrl(e){return gP(e)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("dvid",i=>new mP(i.credentialsManager));/**
 * @license
 * Copyright 2019 The Neuroglancer Authors
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Ja=1,vP="GrapheneMeshSource:NewSegment";var yP=(i=>(i[i.RAW=0]="RAW",i[i.JPEG=1]="JPEG",i[i.COMPRESSED_SEGMENTATION=2]="COMPRESSED_SEGMENTATION",i))(yP||{});class SP{}SP.RPC_ID="graphene/VolumeChunkSource";class AS{}AS.RPC_ID="graphene/ChunkedGraphSource";class MS{}MS.RPC_ID="graphene/MeshSource";class J_{}const ja=async i=>i;function bP(i,e){const t=M.R.rshift(new M.R,i,64-e);return M.R.equal(t,M.R.ONE)}function wP(i){if(i.charAt(0)==="~"){const t=i.substring(1).split(/:(.+)/);return{key:t[0],fragmentId:t[1]}}return{key:i,fragmentId:i}}const CP="ChunkedGraphLayer",xP="ChunkedGraphLayer:updateSources",j_=5;function EP(i){const{rank:e,dataType:t}=i,{baseVoxelOffset:n=new Float32Array(e)}=i;return{...zo(i),baseVoxelOffset:n,dataType:t}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ya(i,e=0){const t=w.ln.clone([...i]);return t[3]=e,t}const Qa=w.eR.fromValues(1,0,0),vu=w.eR.fromValues(0,0,1),TP=Ya(Qa,.5),DP=Ya(vu,.5),IP=Ya(Qa,.25),RP=Ya(vu,.25),kP=w.ln.fromValues(.5,.5,.5,.01),LP=new M.R(Te(TP)),PP=new M.R(Te(DP)),AP=new M.R(Te(kP)),MP=w.ln.fromValues(0,0,0,.5);class NP extends Ke(st()(pi),MS){getFragmentKey(e,t){return wP(t)}}class OP{constructor(e,t){const n=/^(https?:\/\/[.\w:\-/]+)\/segmentation\/(?:1\.0|table)\/([^/]+)\/?$/,s=e.match(n);if(s===null)throw Error(`Graph URL invalid: ${e}`);this.segmentationUrl=`${s[1]}/segmentation/api/v${Ja}/table/${s[2]}`,this.meshingUrl=`${s[1]}/meshing/api/v${Ja}/table/${s[2]}`;try{(0,p.Rf)(t),this.supported_api_versions=(0,p.cQ)(t,"supported_api_versions",r=>(0,p.$v)(r,p.B8))}catch{this.supported_api_versions=[0]}if(!(Ja in this.supported_api_versions)){const r=`This Neuroglancer branch requires Graph Server version ${Ja}, but the server only supports version(s) ${this.supported_api_versions}.`;throw new Error(r)}}}const VP=8;class _P{constructor(e){(0,p.Rf)(e),this.chunkSize=(0,p.cQ)(e,"chunk_size",t=>(0,p.Xu)(w.eR.create(),t,p.We)),this.nBitsForLayerId=(0,p.MM)(e,"n_bits_for_layer_id",p.We,VP)}}function BP(i,e,t){const n=bS(i),s=(0,p.cQ)(i,"data_dir",a=>bn(a,t)).url,r=(0,p.cQ)(i,"app",a=>new OP(e,a)),o=(0,p.cQ)(i,"graph",a=>new _P(a));return{...n,app:r,graph:o,dataUrl:s}}class FP extends wS{constructor(e,t,n){super(e,void 0,n.dataUrl,n),this.chunkedGraphCredentialsProvider=t,this.info=n}getChunkedGraphSource(){const{rank:e}=this,t=this.info.scales[0],n=EP({rank:e,dataType:this.info.dataType,upperVoxelBound:t.size,chunkDataSize:Uint32Array.from(this.info.graph.chunkSize),baseVoxelOffset:t.voxelOffset}),s=e+1,r=new Float32Array(s*s);r[r.length-1]=1;const{lowerBounds:o,upperBounds:a}=this.info.modelSpace.boundingBoxes[0].box,l=new Float32Array(e),c=new Float32Array(e);for(let d=0;d<3;++d)r[s*d+d]=1,r[s*e+d]=t.voxelOffset[d],l[d]=o[d],c[d]=a[d];return{chunkSource:this.chunkManager.getChunkSource(nA,{spec:n,credentialsProvider:this.chunkedGraphCredentialsProvider,parameters:{url:`${this.info.app.segmentationUrl}/node`}}),chunkToMultiscaleTransform:r,lowerClipBound:l,upperClipBound:c}}}function NS(i){return(0,p.cQ)(i,"transform",e=>{const t=w.pB.create();return e!==void 0&&(0,p.Xu)(t.subarray(0,12),e,p.zo),w.pB.transpose(t,t),t})}function UP(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"@type",p.zr);let t;if(e==="neuroglancer_legacy_mesh"){const s=(0,p.cQ)(i,"sharding",VS);s===void 0?t=void 0:t={lodScaleMultiplier:0,transform:NS(i),sharding:s,vertexQuantizationBits:10}}else{if(e!=="neuroglancer_multilod_draco")throw new Error(`Unsupported mesh type: ${JSON.stringify(e)}`);{const s=(0,p.cQ)(i,"lod_scale_multiplier",p.Mo),r=(0,p.cQ)(i,"vertex_quantization_bits",p.We),o=NS(i),a=(0,p.cQ)(i,"sharding",VS);t={lodScaleMultiplier:s,transform:o,sharding:a,vertexQuantizationBits:r}}}const n=(0,p.cQ)(i,"segment_properties",p.z$);return{metadata:t,segmentPropertyMap:n}}async function $P(i,e,t){let n;try{n=await yu(i,e,t)}catch(s){if((0,Me.El)(s))return{metadata:void 0};throw s}return UP(n)}function OS(i){return i===void 0?Vt.Y1.RAW:(0,p.sl)(i,Vt.Y1)}function GP(i){if(i===void 0)return;(0,p.Rf)(i);const e=(0,p.cQ)(i,"@type",p.zr);if(e!=="neuroglancer_uint64_sharded_v1")throw new Error(`Unsupported sharding format: ${JSON.stringify(e)}`);const t=(0,p.cQ)(i,"hash",l=>(0,p.sl)(l,Vt.TV)),n=(0,p.cQ)(i,"preshift_bits",p.bX),s=(0,p.cQ)(i,"shard_bits",p.bX),r=(0,p.cQ)(i,"minishard_bits",p.bX),o=(0,p.cQ)(i,"minishard_index_encoding",OS),a=(0,p.cQ)(i,"data_encoding",OS);return{hash:t,preshiftBits:n,shardBits:s,minishardBits:r,minishardIndexEncoding:o,dataEncoding:a}}function VS(i){if(i===void 0)return;(0,p.Rf)(i);const e=new Array;for(const t in i){const n=Number(t);e[n]=GP(i[n])}return e}function zP(i,e,t){return i.getChunkSource(NP,{parameters:e,credentialsProvider:t})}async function WP(i,e,t,n,s){const{metadata:r,segmentPropertyMap:o}=await $P(i,void 0,n),a={manifestUrl:t,fragmentUrl:n,lod:0,sharding:r?.sharding,nBitsForLayerId:s},l=r?.transform||w.pB.create();return{source:zP(i,a,e),transform:l,segmentPropertyMap:o}}function yu(i,e,t){return i.memoize.getUncounted({type:"graphene:metadata",url:t,credentialsProvider:St(e)},async()=>await rn(e,`${t}/info`,{},Me.cj))}function HP(i){const e=w.pB.create(),t=i.scales[0].resolution;for(let n=0;n<3;++n)e[5*n]=1/t[n];return e}async function JP(i,e,t,n){const s=BP(n,t,i.credentialsManager),r=new FP(i.chunkManager,e,s),o=new qP;i.state&&o.restoreState(i.state);const a=new eA(s,e,r,o),{modelSpace:l}=s,c=[{id:"default",default:!0,subsource:{volume:r}},{id:"graph",default:!0,subsource:{segmentationGraph:a}},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(l.bounds)}}];if(s.segmentPropertyMap!==void 0){const d=Nn(t,s.segmentPropertyMap),u=await yu(i.chunkManager,e,d),h=jr(i.chunkManager,e,u,d);c.push({id:"properties",default:!0,subsource:{segmentPropertyMap:h}})}if(s.mesh!==void 0){const{source:d,transform:u}=await WP(i.chunkManager,e,s.app.meshingUrl,Nn(s.dataUrl,s.mesh),s.graph.nBitsForLayerId),h=HP(s);w.pB.multiply(h,h,u),c.push({id:"mesh",default:!0,subsource:{mesh:d},subsourceToModelSubspaceTransform:h})}return{modelTransform:yt(l),subsources:c,state:o}}class jP extends kS{get description(){return"Graphene file-backed data source"}get(e){const{url:t,parameters:n}=Xi(e.providerUrl);return e.chunkManager.memoize.getUncounted({type:"graphene:get",providerUrl:t,parameters:n},async()=>{const{url:s,credentialsProvider:r}=bn(t,e.credentialsManager);let o;try{o=await yu(e.chunkManager,r,s)}catch(c){throw(0,Me.El)(c)&&n.type==="mesh"&&console.log("does this happen?"),c}(0,p.Rf)(o);const a=(0,p.MM)(o,"redirect",p.zr);if(a!==void 0)throw new Vc(a);const l=(0,p.MM)(o,"@type",p.zr);switch(l){case"neuroglancer_multiscale_volume":case void 0:return await JP(e,r,s,o);default:throw new Error(`Invalid type: ${JSON.stringify(l)}`)}})}}function qa(i){for(const e of i.dataSources){const{loadState:t}=e;if(!(t===void 0||t.error!==void 0)){for(const n of t.subsources)if(n.enabled&&n.subsourceEntry.id==="graph")return n}}}function Su(i,e,t,n){const{subsourceEntry:s}=e,r=new wh(e.loadedDataSource.transform,[],["associated segments"]),o=new $f;o.color.value.set(n),o.relationshipStates.set("associated segments",{segmentationState:new A.B0(i.displayState),showMatches:new rt(!1)});const a=new Uo({localPosition:i.localPosition,transform:e.getRenderLayerTransform(),source:r,displayState:o,dataSource:e.loadedDataSource.layerDataSource,subsourceIndex:e.subsourceIndex,subsourceId:s.id,subsubsourceId:t,role:si.ANNOTATION});return i.addAnnotationLayerState(a,e),a}function YP(i,e){return(0,p.MM)(i,e,t=>M.R.parseString(String(t)))}function _S(i,e){return(0,p.cQ)(i,e,t=>M.R.parseString(String(t)))}function bu(i){const e=_S(i,wu),t=_S(i,Cu),n=(0,p.cQ)(i,xu,s=>(0,p.f4)(s));return{segmentId:e,rootId:t,position:n}}const BS="id",FS="error",US="multicut",$S="focusSegment",GS="sinks",zS="sources",wu="segmentId",Cu="rootId",xu="position",WS="merge",HS="merges",JS="autosubmit",jS="sink",YS="source",QS="mergedRoot",QP="locked";class qP{constructor(){this.changed=new j.IY,this.multicutState=new XP,this.mergeState=new KP,this.multicutState.changed.add(()=>{this.changed.dispatch()}),this.mergeState.changed.add(()=>{this.changed.dispatch()})}reset(){this.multicutState.reset(),this.mergeState.reset()}toJSON(){return{[US]:this.multicutState.toJSON(),[WS]:this.mergeState.toJSON()}}restoreState(e){(0,p.MM)(e,US,t=>{this.multicutState.restoreState(t)}),(0,p.MM)(e,WS,t=>{this.mergeState.restoreState(t)})}}class KP extends D.O8{constructor(){super(),this.changed=new j.IY,this.merges=new A.B0([]),this.autoSubmit=new rt(!1),this.registerDisposer(this.merges.changed.add(this.changed.dispatch))}reset(){this.merges.value=[],this.autoSubmit.reset()}toJSON(){const{merges:e,autoSubmit:t}=this,n=r=>({[wu]:r.segmentId.toJSON(),[Cu]:r.rootId.toJSON(),[xu]:[...r.position]}),s=r=>{const o={[BS]:r.id,[QP]:r.locked,[jS]:n(r.sink),[YS]:n(r.source)};return r.mergedRoot&&(o[QS]=r.mergedRoot.toJSON()),r.error&&(o[FS]=r.error),o};return{[HS]:e.value.filter(r=>r.source).map(s),[JS]:t.toJSON()}}restoreState(e){function t(s){const r=YP(s,QS),o=(0,p.cQ)(s,BS,p.zr),a=(0,p.MM)(s,FS,p.zr),l=!1,c=bu(s[jS]),d=bu(s[YS]);return{id:o,locked:l,sink:c,source:d,mergedRoot:r,error:a}}const n=s=>(0,p.$v)(s,r=>t(r));this.merges.value=(0,p.cQ)(e,HS,n),this.autoSubmit.restoreState((0,p.MM)(e,JS,p.aO))}}class XP extends D.O8{constructor(e=new A.DN(void 0,n=>n),t=new A.B0(!1)){super(),this.focusSegment=e,this.blueGroup=t,this.changed=new j.IY,this.sinks=new A._Y,this.sources=new A._Y;const n=()=>{this.sinks.size===0&&this.sources.size===0&&(this.focusSegment.value=void 0)};this.registerDisposer(e.changed.add(this.changed.dispatch)),this.registerDisposer(this.sinks.changed.add(n)),this.registerDisposer(this.sources.changed.add(n)),this.registerDisposer(this.blueGroup.changed.add(this.changed.dispatch)),this.registerDisposer(this.sinks.changed.add(this.changed.dispatch)),this.registerDisposer(this.sources.changed.add(this.changed.dispatch))}reset(){this.focusSegment.value=void 0,this.blueGroup.value=!1,this.sinks.clear(),this.sources.clear()}toJSON(){const{focusSegment:e,sinks:t,sources:n}=this,s=r=>({[wu]:r.segmentId.toJSON(),[Cu]:r.rootId.toJSON(),[xu]:[...r.position]});return{[$S]:e.toJSON(),[GS]:[...t].map(s),[zS]:[...n].map(s)}}restoreState(e){const t=r=>(0,p.$v)(r,o=>bu(o));(0,p.MM)(e,$S,r=>{this.focusSegment.restoreState(M.R.parseString(String(r)))});const n=(0,p.cQ)(e,GS,t),s=(0,p.cQ)(e,zS,t);for(const r of n)this.sinks.add(r);for(const r of s)this.sources.add(r)}swapGroup(){this.blueGroup.value=!this.blueGroup.value}get activeGroup(){return this.blueGroup.value?this.sources:this.sinks}get segments(){return[...this.redSegments,...this.blueSegments]}get redSegments(){return[...this.sinks].filter(e=>!M.R.equal(e.segmentId,e.rootId)).map(e=>e.segmentId)}get blueSegments(){return[...this.sources].filter(e=>!M.R.equal(e.segmentId,e.rootId)).map(e=>e.segmentId)}}class Ka extends Id{constructor(e,t,n,s){super(e,t.displayState.segmentationGroupState.value),this.graph=e,this.layer=t,this.chunkSource=n,this.state=s,this.annotationLayerStates=[],this.lastDeselectionMessageExists=!1,this.deleteMergeSubmission=u=>{const{mergeAnnotationState:h}=this;u.locked=!1,h.source.delete(h.source.getReference(u.id))},this.submitMerge=async(u,h=1)=>{this.graph;const m=qa(this.layer).loadedDataSource.transform.inputSpace.value.scales.map(g=>g/1e-9);u.error=void 0;for(let g=1;g<=h;g++)try{return await this.graph.graphServer.mergeSegments(u.sink,u.source,m)}catch(v){if(g===h)throw u.error=v.message||"unknown",v}return M.R.ZERO};const r=t.displayState.segmentationGroupState.value;r.selectedSegments.changed.add((u,h)=>{u!==null&&(u=Array().concat(u)),this.selectedSegmentsChanged(u,h)}),r.visibleSegments.changed.add((u,h)=>{u!==null&&(u=Array().concat(u)),this.visibleSegmentsChanged(u,h)});const{annotationLayerStates:o,state:{multicutState:a}}=this,l=qa(t),c=Su(t,l,"sinks",Qa),d=Su(t,l,"sources",vu);XS(a.sinks,c),XS(a.sources,d),o.push(c,d),t.tool.value instanceof Yr&&(t.tool.value=void 0),this.mergeAnnotationState=Su(t,l,"grapheneMerge",Qa);{const{mergeState:u}=s,{merges:h,autoSubmit:f}=u,{mergeAnnotationState:m}=this,{visibleSegments:g}=r;for(const v of h.value)m.source.add(uA(v));m.source.childAdded.add(v=>{const y=v;y.relatedSegments[0].map(b=>g.has(b))[0]===!1?(setTimeout(()=>{const{tool:b}=t;b.value instanceof Yr&&b.value.deactivate()},0),Se.showTemporaryMessage("Cannot merge a hidden segment.")):h.value.length<e0?h.value=[...h.value,ZS(y,!0)]:(setTimeout(()=>{const{tool:b}=t;b.value instanceof Yr&&b.value.deactivate()},0),Se.showTemporaryMessage(`Maximum of ${e0} simultanous merges allowed.`))}),m.source.childCommitted.add(v=>{const y=m.source.getReference(v),S=y.value;if(S){const x=S.relatedSegments[0],b=x.map(C=>g.has(C));x.length<4&&(m.source.delete(y),Se.showTemporaryMessage("Cannot merge segment with itself.")),b[2]===!1&&(m.source.delete(y),Se.showTemporaryMessage("Cannot merge a hidden segment."));const E=h.value.find(C=>C.id===y.id);if(E&&!E?.locked){const C=ZS(S,!1);E.sink=C.sink,E.source=C.source,h.changed.dispatch(),f.value&&this.bulkMerge([E])}}y.dispose()}),m.source.childDeleted.add(v=>{let y=!1;const S=h.value.filter(x=>{const b=x.id!==v||x.locked;return b||(y=!0),b});y&&(h.value=S)})}}createRenderLayers(e,t,n){return[new iA(e,this.chunkSource.getChunkedGraphSource(),t,n,this.graph.info.graph.nBitsForLayerId)]}visibleSegmentsChanged(e,t){const{segmentsState:n}=this,{focusSegment:{value:s}}=this.graph.state.multicutState;if(s&&!n.visibleSegments.has(s)&&(n.selectedSegments.has(s)?Se.showTemporaryMessage("Can't hide active multicut segment.",3e3):Se.showTemporaryMessage("Can't deselect active multicut segment.",3e3),n.selectedSegments.add(s),n.visibleSegments.add(s),e&&(e=e.filter(r=>!M.R.equal(r,s)))),e===null){const r=this.segmentsState.selectedSegments.size;this.segmentsState.segmentEquivalences.clear(),Se.showTemporaryMessage(`Hid all ${r} segments.`,3e3);return}for(const r of e)if(!t){const o=[...n.segmentEquivalences.setElements(r)].length;n.segmentEquivalences.deleteSet(r),this.lastDeselectionMessage&&this.lastDeselectionMessageExists&&(this.lastDeselectionMessage.dispose(),this.lastDeselectionMessageExists=!1),this.lastDeselectionMessage=Se.showMessage(`Hid ${o} segments.`),this.lastDeselectionMessageExists=!0,setTimeout(()=>{this.lastDeselectionMessageExists&&(this.lastDeselectionMessage.dispose(),this.lastDeselectionMessageExists=!1)},2e3)}}selectedSegmentsChanged(e,t){const{segmentsState:n}=this;if(e===null){const s=this.segmentsState.selectedSegments.size;Se.showTemporaryMessage(`Deselected all ${s} segments.`,3e3);return}for(const s of e){const r=bP(s,this.graph.info.graph.nBitsForLayerId),o=s.clone();t&&r&&this.graph.getRoot(o).then(a=>{n.visibleSegments.has(o)&&n.visibleSegments.add(a),n.selectedSegments.delete(o),n.selectedSegments.add(a)})}}computeSplit(e,t){}getMeshSource(){const{layer:e}=this;for(const t of e.dataSources){const{loadState:n}=t;if(n instanceof Bc){const{subsources:s}=n.dataSource,r=s.filter(a=>a.id==="graph")[0];if(r?.subsource.segmentationGraph&&r.subsource.segmentationGraph!==this.graph)continue;const o=s.filter(a=>a.id==="mesh")[0];if(o)return o.subsource.mesh}}}meshAddNewSegments(e){const t=this.getMeshSource();if(t)for(const n of e)t.rpc.invoke(vP,{rpcId:t.rpcId,segment:n.toString()})}async submitMulticut(e){const{state:{multicutState:t}}=this,{sinks:n,sources:s}=t;if(n.size===0||s.size===0)return Se.showTemporaryMessage("Must select both red and blue groups to perform a multi-cut.",7e3),!1;const r=await this.graph.graphServer.splitSegments([...n],[...s],e);if(r.length===0)return Se.showTemporaryMessage("No split found.",3e3),!1;const o=t.focusSegment.value;t.reset();const{segmentsState:a}=this;a.selectedSegments.delete(o);for(const l of[...n,...s])a.selectedSegments.delete(l.rootId);return this.meshAddNewSegments(r),a.selectedSegments.add(r),a.visibleSegments.add(r),!0}async bulkMerge(e){const{merges:t}=this.state.mergeState,n=d=>new Promise(u=>{if(d.length===0){u([]);return}const h=[],f=(y,S)=>{h.push(y);for(const x of d)x.source&&M.R.equal(x.source.rootId,y)&&(x.source.rootId=S),M.R.equal(x.sink.rootId,y)&&(x.sink.rootId=S)};let m=0,g=0;const v=(y,S)=>{if(m===d.length||S.length===0)return;g++;let x=[];const b=()=>{E++,E===S.length&&(g-=1),g===0&&u(h)};let E=0;for(const C of S)C.locked=!0,C.status="trying...",t.changed.dispatch(),this.submitMerge(C,3).then(k=>{f(C.source.rootId,k),f(C.sink.rootId,k),C.status="done",C.mergedRoot=k,t.changed.dispatch(),m+=1,v(m,x),x=[],b(),dA(5e3).then(()=>{this.deleteMergeSubmission(C)})}).catch(()=>{t.changed.dispatch(),x.push(C),m>y&&(v(m,x),x=[]),b()})};v(m,d)});e=e.filter(d=>!d.locked&&d.source);const s=await n(e),r=[];for(const d of e)d.error?(d.locked=!1,d.status=d.error):d.mergedRoot&&r.push(d.mergedRoot);const o=await this.graph.graphServer.filterLatestRoots(r),a=this.layer.displayState.segmentationGroupState.value,{visibleSegments:l,selectedSegments:c}=a;c.delete(s),this.meshAddNewSegments(o),c.add(o),l.add(o),t.changed.dispatch()}}async function qS(i){if(i.response){let e;return i.response.headers.get("content-type")==="application/json"?e=(await i.response.json()).message:e=await i.response.text(),e}}async function Eu(i,e){let t,n=()=>{};e.initialMessage&&(t=new Se(!0),t.setText(e.initialMessage),n=t.dispose.bind(t));try{const s=await i;return n(),s}catch(s){if(s instanceof Me.j$&&s.response){const{errorPrefix:r=""}=e,o=await qS(s);if(o)throw t||(t=new Se(!0)),t.setErrorMessage(r+o),t.setVisible(!0),new Error(`[${s.response.status}] ${r}${o}`)}throw s}}const KS=Symbol("Graph Server Not Specified.");class ZP{constructor(e,t){this.url=e,this.credentialsProvider=t}async getRoot(e,t=""){const n=new Date(t).valueOf()/1e3,s=`${this.url}/node/${String(e)}/root?int64_as_str=1${Number.isNaN(n)?"":`&timestamp=${n}`}`,r=rn(this.credentialsProvider,s,{},ja),a=await(await Eu(r,{initialMessage:`Retrieving root for segment ${e}`,errorPrefix:"Could not fetch root: "})).json();return M.R.parseString(a.root_id)}async mergeSegments(e,t,n){const{url:s}=this;if(s==="")return Promise.reject(KS);const r=rn(this.credentialsProvider,`${s}/merge?int64_as_str=1`,{method:"POST",body:JSON.stringify([[String(e.segmentId),...e.position.map((o,a)=>o*n[a])],[String(t.segmentId),...t.position.map((o,a)=>o*n[a])]])},ja);try{const a=await(await r).json();return M.R.parseString(a.new_root_ids[0])}catch(o){if(o instanceof Me.j$){const a=await qS(o);throw new Error(a)}throw o}}async splitSegments(e,t,n){const{url:s}=this;if(s==="")return Promise.reject(KS);const r=rn(this.credentialsProvider,`${s}/split?int64_as_str=1`,{method:"POST",body:JSON.stringify({sources:e.map(c=>[String(c.segmentId),...c.position.map((d,u)=>d*n[u])]),sinks:t.map(c=>[String(c.segmentId),...c.position.map((d,u)=>d*n[u])])})},ja),a=await(await Eu(r,{initialMessage:`Splitting ${e.length} sources from ${t.length} sinks`,errorPrefix:"Split failed: "})).json(),l=new Array(a.new_root_ids.length);for(let c=0;c<l.length;++c)l[c]=M.R.parseString(a.new_root_ids[c]);return l}async filterLatestRoots(e){const t=`${this.url}/is_latest_roots`,n=rn(this.credentialsProvider,t,{method:"POST",body:JSON.stringify({node_ids:e.map(a=>a.toJSON())})},ja),r=await(await Eu(n,{errorPrefix:"Could not check latest: "})).json(),o=[];for(const[a,l]of r.is_latest.entries())l&&o.push(e[a]);return o}}class eA extends Dd{constructor(e,t,n,s){super(),this.info=e,this.chunkSource=n,this.state=s,this.connections=new Set,this.graphServer=new ZP(e.app.segmentationUrl,t)}connect(e){const t=new Ka(this,e,this.chunkSource,this.state);return this.connections.add(t),t.registerDisposer(()=>{this.connections.delete(t)}),t}get visibleSegmentEquivalencePolicy(){return Tt.y6.MAX_REPRESENTATIVE|Tt.y6.NONREPRESENTATIVE_EXCLUDED}getRoot(e){return this.graphServer.getRoot(e)}tabContents(e,t,n){const s=document.createElement("div");s.style.display="contents";const r=document.createElement("div");r.className="neuroglancer-segmentation-toolbox",r.appendChild(ys(t,e.toolBinder,{toolJson:Tu,label:"Multicut",title:"Multicut segments"})),r.appendChild(ys(t,e.toolBinder,{toolJson:Du,label:"Merge",title:"Merge segments"})),s.appendChild(r),s.appendChild(t.registerDisposer(new sA(e,e.annotationDisplayState)).element);const o=n.element;return o.classList.add("neuroglancer-annotations-tab"),o.classList.add("neuroglancer-graphene-tab"),s}async merge(e,t){return new M.R}async split(e,t){return{include:e,exclude:t}}trackSegment(e,t){return()=>{console.log("trackSegment... do nothing",e,t)}}}class tA extends Er{}class nA extends Ke(st()(tA),AS){}class iA extends Bi{constructor(e,t,n,s,r){super(),this.chunkManager=e,this.source=t,this.displayState=n,this.localPosition=s,this.layerChunkProgressInfo=new lo,this.leafRequestsActive=this.registerDisposer(ut.make(e.rpc,!0)),this.chunkTransform=this.registerDisposer((0,A.ol)(a=>go(()=>ao(rr(a))),this.displayState.transform));const o=this.sharedObject=this.backend=this.registerDisposer(new ya(e,n,this.layerChunkProgressInfo));o.RPC_TYPE_ID=CP,o.initializeCounterpartWithChunkManager({source:t.chunkSource.addCounterpartRef(),localPosition:this.registerDisposer(ut.makeFromExisting(e.rpc,this.localPosition)).rpcId,leafRequestsActive:this.leafRequestsActive.rpcId,nBitsForLayerId:this.registerDisposer(ut.make(e.rpc,r)).rpcId}),this.registerDisposer(o.visibility.add(this.visibility)),this.registerDisposer(this.leafRequestsActive.changed.add(()=>{this.showOrHideMessage(this.leafRequestsActive.value)}))}attach(e){super.attach(e);const t=this.chunkTransform.value,n=e.view.displayDimensionRenderInfo.value;e.state={chunkTransform:t,displayDimensionRenderInfo:n},e.state.source=e.registerDisposer((0,A.no)((s,r,o)=>{const a=Ko(o,r,l=>[[this.source]],e.messages,this);return e.view.flushBackendProjectionParameters(),this.sharedObject.rpc.invoke(xP,{layer:this.sharedObject.rpcId,view:e.view.rpcId,displayDimensionRenderInfo:o,sources:Yo(a)}),a[0][0]},this.displayState.transform,e.view.displayDimensionRenderInfo))}isReady(){return!0}showOrHideMessage(e){this.leafRequestsStatusMessage&&e?(this.leafRequestsStatusMessage.dispose(),this.leafRequestsStatusMessage=void 0,Se.showTemporaryMessage("Loading chunked graph segmentation...",3e3)):!this.leafRequestsStatusMessage&&!e&&(this.leafRequestsStatusMessage=Se.showMessage("At this zoom level, chunked graph segmentation will not be loaded. Please zoom in if you wish to load it."))}}const Tu="grapheneMulticutSegments",Du="grapheneMergeSegments";class sA extends ty{constructor(e,t){super(e,t),this.layer=e,this.displayState=t;const{graphConnection:{value:n}}=e;if(n instanceof Ka)for(const s of n.annotationLayerStates)this.annotationStates.add(s)}get annotationStates(){return this._annotationStates===void 0&&(this._annotationStates=this.registerDisposer(new Xv)),this._annotationStates}}const XS=(i,e)=>{const t=e.source;t.childDeleted.add(s=>{const r=[...i].find(o=>o.annotationReference?.id===s);r&&i.delete(r)});const n=s=>{const r={id:"",point:s.position,type:Je.POINT,properties:[],relatedSegments:[[s.segmentId,s.rootId]]},o=t.add(r);s.annotationReference=o};i.changed.add((s,r)=>{if(s===null){for(const o of t)t.delete(t.getReference(o.id));return}r?n(s):s.annotationReference&&t.delete(s.annotationReference)});for(const s of i)n(s)};function rA(i,e){const n=qa(e).getRenderLayerTransform(),s=go(()=>ao(rr(n.value)));if(s.error!==void 0)return;const r=new Float32Array(s.modelTransform.unpaddedRank);if(as(r,i,e.localPosition.value,s.layerRank,s.combinedGlobalLocalToChunkTransform))return r}const oA=(i,e)=>{if(e.updateUnconditionally())return rA(e.unsnappedPosition,i)},aA=Pe.fromObject({"at:shift?+control+mousedown0":{action:"set-anchor"},"at:shift?+keyg":{action:"swap-group"},"at:shift?+enter":{action:"submit"}});class lA extends vs{toJSON(){return Tu}activate(e){const{layer:t}=this,{graphConnection:{value:n}}=t;if(!n||!(n instanceof Ka))return;const{state:{multicutState:s},segmentsState:r}=n;if(s===void 0)return;const{body:o,header:a}=Ss(e);a.textContent="Multicut segments",o.classList.add("graphene-multicut-status"),o.appendChild(_e({text:"Swap",title:"Swap group",onClick:()=>{s.swapGroup()}})),o.appendChild(_e({text:"Clear",title:"Clear multicut",onClick:()=>{s.reset()}}));const l=async()=>{c.classList.toggle("disabled",!0);const S=qa(this.layer).loadedDataSource.transform.inputSpace.value.scales.map(x=>x/1e-9);n.submitMulticut(S).then(x=>{c.classList.toggle("disabled",!1),x&&e.cancel()})},c=_e({text:"Submit",title:"Submit multicut",onClick:()=>{l()}});o.appendChild(c);const d=document.createElement("div");d.className="activeGroupIndicator",d.innerHTML="Active Group: ",o.appendChild(d);const{displayState:u}=this.layer,h=u.segmentationGroupState.value,f=u.baseSegmentHighlighting.value,m=u.highlightColor.value;e.bindInputEventMap(aA),e.registerDisposer(()=>{g(),u.baseSegmentHighlighting.value=f,u.highlightColor.value=m});const g=()=>{Or(h),u.useTempSegmentStatedColors2d.value=!1,u.tempSegmentStatedColors2d.value.clear(),u.tempSegmentDefaultColor2d.value=void 0,u.highlightColor.value=void 0},v=()=>{g(),d.classList.toggle("blueGroup",s.blueGroup.value);const y=s.focusSegment.value;if(y!==void 0){u.baseSegmentHighlighting.value=!0,u.highlightColor.value=s.blueGroup.value?RP:IP,r.useTemporaryVisibleSegments.value=!0,r.useTemporarySegmentEquivalences.value=!0,r.temporaryVisibleSegments.add(y);for(const S of s.segments)r.temporaryVisibleSegments.add(S);for(const S of r.segmentEquivalences.setElements(y))r.temporaryVisibleSegments.has(S)||r.temporarySegmentEquivalences.link(y,S);u.tempSegmentDefaultColor2d.value=MP,u.tempSegmentStatedColors2d.value.set(y,AP);for(const S of s.redSegments)u.tempSegmentStatedColors2d.value.set(S,LP);for(const S of s.blueSegments)u.tempSegmentStatedColors2d.value.set(S,PP);u.useTempSegmentStatedColors2d.value=!0}};v(),e.registerDisposer(s.changed.add(v)),e.registerDisposer(h.segmentEquivalences.changed.add((0,xe.A)(()=>v(),0))),e.bindAction("swap-group",y=>{y.stopPropagation(),s.swapGroup()}),e.bindAction("set-anchor",y=>{y.stopPropagation();const S=cA(this,h.visibleSegments);if(!S)return;const{rootId:x,segmentId:b}=S,{focusSegment:E,segments:C}=s;if(E.value===void 0&&(E.value=x.clone()),!M.R.equal(E.value,x)){Se.showTemporaryMessage(`The selected supervoxel has root segment ${x.toString()}, but the supervoxels already selected have root ${E.value.toString()}`,12e3);return}if(!M.R.equal(x,b)){for(const T of C)if(M.R.equal(T,b)){Se.showTemporaryMessage(`Supervoxel ${b.toString()} has already been selected`,7e3);return}}s.activeGroup.add(S)}),e.bindAction("submit",y=>{y.stopPropagation(),l()})}get description(){return"multicut"}}const cA=(i,e)=>{const{layer:t,mouseState:n}=i,{segmentSelectionState:{value:s,baseValue:r}}=t.displayState;if(!r||!s)return;if(!e.has(s)){Se.showTemporaryMessage("The selected supervoxel is of an unselected segment",7e3);return}const o=oA(t,n);if(o!==void 0)return{rootId:s.clone(),segmentId:r.clone(),position:o}},dA=i=>new Promise((e,t)=>{setTimeout(e,i)});class Yr extends Ma{constructor(e,t){super(e,{}),this.annotationState=t,this.getBaseSegment=!0;const{inProgressAnnotation:n}=this,{displayState:s}=t;if(!s)return;const{disablePicking:r}=s;this.registerDisposer(n.changed.add(()=>{r.value=n.value!==void 0}))}get annotationLayer(){return this.annotationState}get description(){return"merge line"}toJSON(){return t0}}function ZS(i,e){const t=i.relatedSegments[0],n={id:i.id,locked:!1,sink:{position:i.pointA.slice(),rootId:t[0].clone(),segmentId:t[1].clone()}};return e||(n.source={position:i.pointB.slice(),rootId:t[2].clone(),segmentId:t[3].clone()}),n}function uA(i){const{sink:e,source:t}=i;return{id:i.id,type:Je.LINE,pointA:e.position.slice(),pointB:t.position.slice(),relatedSegments:[[e.rootId.clone(),e.segmentId.clone(),t.rootId.clone(),t.segmentId.clone()]],properties:[]}}const e0=10,hA=Pe.fromObject({"at:shift?+enter":{action:"submit"}});class pA extends vs{activate(e){const{graphConnection:{value:t},tool:n}=this.layer;if(!t||!(t instanceof Ka))return;const{state:{mergeState:s}}=t;if(s===void 0)return;const{merges:r,autoSubmit:o}=s,a=new Yr(this.layer,t.mergeAnnotationState);n.value=a,e.registerDisposer(()=>{n.value=void 0});const{body:l,header:c}=Ss(e);c.textContent="Merge segments",l.classList.add("graphene-merge-segments-status"),e.bindInputEventMap(hA);const d=async()=>{r.value.filter(b=>b.locked).length||(u.classList.toggle("disabled",!0),await t.bulkMerge(r.value),u.classList.toggle("disabled",!1))},u=_e({text:"Submit",title:"Submit merge",onClick:async()=>{d()}});l.appendChild(u),e.bindAction("submit",async b=>{b.stopPropagation(),d()}),l.appendChild(_e({text:"Clear",title:"Clear pending merges",onClick:()=>{a.deactivate();for(const b of r.value)b.locked||t.deleteMergeSubmission(b)}}));const h=e.registerDisposer(new Un(o)),f=document.createElement("label");f.appendChild(document.createTextNode("auto-submit")),f.title="auto-submit merges",f.appendChild(h.element),l.appendChild(f);const m=document.createElement("div");m.classList.add("graphene-merge-segments-merges"),l.appendChild(m);const g=Os.make(this.layer.displayState,!0),v=b=>{const E=g.getWithNormalizedId(b);return E.classList.add("neuroglancer-segment-list-entry-double-line"),E},y=b=>{const E=document.createElement("div");E.classList.add("graphene-merge-segments-point");const C=v(ji(this.layer.displayState,b));return E.appendChild(C),E},S=b=>{const E=document.createElement("div");if(E.classList.add("graphene-merge-segments-submission"),E.appendChild(y(b.sink.rootId)),b.source&&(E.appendChild(document.createElement("div")).textContent="\uA579",E.appendChild(y(b.source.rootId))),b.locked||E.appendChild(Yn({title:"Delete merge",onClick:C=>{C.stopPropagation(),C.preventDefault(),t.deleteMergeSubmission(b)}})),b.status){const C=document.createElement("div");C.classList.add("graphene-merge-segments-submission-status"),C.textContent=b.status,E.appendChild(C)}return E},x=()=>{for(;m.firstChild;)m.removeChild(m.firstChild);for(const b of r.value)m.appendChild(S(b))};e.registerDisposer(r.changed.add(x)),x()}toJSON(){return Du}get description(){return"merge segments"}}Rn(Rt,Tu,i=>new lA(i,!0)),Rn(Rt,Du,i=>new pA(i,!0));const t0="annotateMergeLine";vr(t0,(i,e)=>new Yr(i,e));/**
 * @license
 * Copyright 2018 The Neuroglancer Authors
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("graphene",()=>new jP);var Iu=G(5926);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class fA extends Ke(st()(Mn),Iu.j){}class gA extends Ht{constructor(e,t,n,s){super(e),this.credentialsProvider=t,this.multiscaleMetadata=n,this.scales=s;let r,o;if(s.forEach((u,h)=>{if(u!==void 0){if(o===void 0&&(o=h),r!==void 0&&u.dataType!==r)throw new Error(`Scale s${h} has data type ${I[u.dataType]} but expected ${I[r]}.`);r=u.dataType}}),r===void 0)throw new Error("At least one scale must be specified.");const a=n.scales[o],l=s[o];this.dataType=r,this.volumeType=gt.IMAGE,this.baseScaleIndex=o;const c=n.modelSpace,{rank:d}=c;this.modelSpace=ke({names:c.names,scales:c.scales,units:c.units,boundingBoxes:[{transform:(0,we.nx)(Float64Array,a.downsamplingFactor,!1),box:{lowerBounds:new Float64Array(d),upperBounds:new Float64Array(l.size)}}],coordinateArrays:c.coordinateArrays})}get rank(){return this.modelSpace.rank}getSources(e){const{scales:t,rank:n}=this,s=this.multiscaleMetadata.scales;return(0,z.RO)(t.filter(r=>r!==void 0).map((r,o)=>{const a=s[o],l=(0,we.nx)(Float32Array,a.downsamplingFactor);return gi({rank:n,chunkToMultiscaleTransform:l,dataType:r.dataType,upperVoxelBound:r.size,volumeType:this.volumeType,chunkDataSizes:[r.chunkSize],volumeSourceOptions:e}).map(c=>({chunkSource:this.chunkManager.getChunkSource(fA,{credentialsProvider:this.credentialsProvider,spec:c,parameters:{url:a.url,encoding:r.encoding}}),chunkToMultiscaleTransform:l}))}))}}class mA{constructor(e){(0,p.Rf)(e),this.dataType=(0,p.cQ)(e,"dataType",n=>(0,p.sl)(n,I)),this.size=Float32Array.from((0,p.cQ)(e,"dimensions",n=>(0,p.$v)(n,p.We))),this.chunkSize=(0,p.cQ)(e,"blockSize",n=>(0,p.Xu)(new Uint32Array(this.size.length),n,p.We));let t;(0,p.MM)(e,"compression",n=>{t=(0,p.cQ)(n,"type",s=>(0,p.sl)(s,Iu.r))}),t===void 0&&(t=(0,p.cQ)(e,"compressionType",n=>(0,p.sl)(n,Iu.r))),this.encoding=t}}function vA(i,e,t){return Promise.all(t.scales.map(async n=>{const s=await n0(i,e,n.url,!0);if(s!==void 0)return new mA(s)}))}function yA(i){let{protocol:e,host:t,path:n}=(0,Me.Dl)(i);n.endsWith("/")&&(n=n.substring(0,n.length-1));const s=[];for(;;){s.push(`${e}://${t}${n}/attributes.json`);const r=n.lastIndexOf("/");if(r===-1)break;n=n.substring(0,r)}return s}function SA(i,e,t,n){return i.memoize.getUncounted({type:"n5:attributes.json",url:t,credentialsProvider:St(e)},()=>rn(e,t,{},Me.cj).then(s=>{try{return(0,p.Rf)(s)}catch(r){throw new Error(`Error reading attributes from ${t}: ${r.message}`)}}).catch(s=>{if((0,Me.El)(s))return n?void 0:{};throw s}))}async function n0(i,e,t,n){const s=yA(t),r=await Promise.all(s.map((o,a)=>SA(i,e,o,n&&a===s.length-1)));if(r.indexOf(void 0)===-1)return r.reverse(),Object.assign({},...r)}function bi(i,e){if(i!==-1&&e!==i)throw new Error(`Rank mismatch, received ${e} but expected ${i}`);return e}function i0(i){return Float64Array.from((0,p.$v)(i,p.Mo))}function s0(i){const e=(0,p.J6)(i);if(e.length===0)throw new Error("Expected non-empty array");let t=-1;return{all:(0,p.$v)(e,s=>{const r=i0(s);return t=bi(t,r.length),r}),single:void 0,rank:t}}function bA(i){const e=(0,p.J6)(i);if(e.length===0)throw new Error("Expected non-empty array");if(Array.isArray(e[0]))return s0(e);const t=i0(i);return{all:void 0,single:t,rank:t.length}}const wA=["x","y","z","t","c"];function CA(i){const e=wA.slice(0,i);for(;e.length<i;)e.push(`d${e.length+1}`);return e}function xA(i,e){(0,p.Rf)(e);let t=-1,n=(0,p.MM)(e,"resolution",h=>{const f=Float64Array.from((0,p.$v)(h,p.Mo));return t=bi(t,f.length),f}),s=(0,p.MM)(e,"axes",h=>{const f=(0,p.$v)(h,p.zr);return t=bi(t,f.length),f}),r=(0,p.MM)(e,"units",h=>{const f=(0,p.$v)(h,Th);return t=bi(t,f.length),f}),o={unit:"m",exponent:-9},a,l;(0,p.MM)(e,"downsamplingFactors",h=>{const{single:f,all:m,rank:g}=bA(h);t=bi(t,g),f!==void 0&&(a=f),m!==void 0&&(l=m)}),(0,p.MM)(e,"pixelResolution",h=>{o=(0,p.cQ)(h,"unit",Th),(0,p.MM)(h,"dimensions",f=>{n=Float64Array.from((0,p.$v)(f,p.Mo)),t=bi(t,n.length)})}),(0,p.MM)(e,"scales",h=>{const{all:f,rank:m}=s0(h);t=bi(t,m),l=f});const c=(0,p.MM)(e,"dimensions",h=>{const f=(0,p.$v)(h,p.We);return t=bi(t,f.length),f});if(t===-1)throw new Error("Unable to determine rank of dataset");r===void 0&&(r=new Array(t),r.fill(o)),n===void 0&&(n=new Float64Array(t),n.fill(1));for(let h=0;h<t;++h)n[h]=kl(n[h],r[h].exponent);const d=new Array(t);s!==void 0&&(0,p.MM)(e,"coordinateArrays",h=>{(0,p.Rf)(h);for(let f=0;f<t;++f){const m=s[f];if(Object.prototype.hasOwnProperty.call(h,m)){const g=(0,p.si)(h[m]);d[f]={explicit:!1,labels:g,coordinates:Array.from(g,(v,y)=>y)},r[f]={unit:"",exponent:0},n[f]=1}}}),s===void 0&&(s=CA(t));const u=ke({rank:t,valid:!0,names:s,scales:n,units:r.map(h=>h.unit),coordinateArrays:d});if(c===void 0){if(l===void 0)throw new Error("Not valid single-resolution or multi-resolution dataset");return{modelSpace:u,url:i,attributes:e,scales:l.map((h,f)=>({url:`${i}/s${f}`,downsamplingFactor:h}))}}return a===void 0&&(a=new Float64Array(t),a.fill(1)),{modelSpace:u,url:i,attributes:e,scales:[{url:i,downsamplingFactor:a}]}}class EA extends Ut{get description(){return"N5 data source"}get(e){let{providerUrl:t}=e;return t.endsWith("/")&&(t=t.substring(0,t.length-1)),e.chunkManager.memoize.getUncounted({type:"n5:MultiscaleVolumeChunkSource",providerUrl:t},async()=>{const{url:n,credentialsProvider:s}=bn(t,e.credentialsManager),r=await n0(e.chunkManager,s,n,!1),o=xA(n,r),a=await vA(e.chunkManager,s,o),l=new gA(e.chunkManager,s,o,a);return{modelTransform:yt(l.modelSpace),subsources:[{id:"default",default:!0,url:void 0,subsource:{volume:l}},{id:"bounds",default:!0,url:void 0,subsource:{staticAnnotations:cn(l.modelSpace.bounds)}}]}})}completeUrl(e){return Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("n5",()=>new EA);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Xa extends D.O8{}function Ru(i){let e,t,n;return(s,r)=>t!==void 0&&(e===void 0||s===void 0||e.generation!==s.generation)?(e===void 0&&n.addConsumer(r),t):(e=void 0,n=new at.y3,t=i(s,n).then(o=>(e=o,n=void 0,o),o=>{throw n.isCanceled&&(n=void 0,t=void 0),o}),t)}function r0(i){let e=0;return Ru((t,n)=>i(n).then(s=>({generation:++e,credentials:s})))}class TA{constructor(){this.providers=new Map,this.topLevelManager=this}register(e,t){this.providers.set(e,t)}getCredentialsProvider(e,t){const n=this.providers.get(e);if(n===void 0)throw new Error(`No registered credentials provider: ${JSON.stringify(e)}`);return n(t,this.topLevelManager)}}class o0 extends D.O8{constructor(e){super(),this.base=e,this.memoize=new Tc.e}getCredentialsProvider(e,t){return this.memoize.get({key:e,parameters:t},()=>this.registerDisposer(this.base.getCredentialsProvider(e,t).addRef()))}}class DA extends o0{constructor(){super(new TA),this.base.topLevelManager=this}register(e,t){this.base.register(e,t)}}class IA extends Xa{constructor(e,t){super(),this.baseProvider=e,this.anonymousCredentials=t,this.anonymous=!0,this.get=Ru(n=>this.anonymous&&n===void 0?Promise.resolve({generation:-10,credentials:this.anonymousCredentials}):(this.anonymous=!1,this.baseProvider.get(n)))}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function a0(i){return new Error(`Nggraph server ${i} does not allow requests from Neuroglancer instance ${self.origin}`)}async function RA(i){const e=new Se(!1);function t(s,r){e.element.textContent=s+" ";const o=document.createElement("button");o.textContent=r,e.element.appendChild(o),o.addEventListener("click",()=>{window.open(`${i}/login?origin=${encodeURIComponent(self.origin)}`),t(`Waiting for login to nggraph server ${i}...`,"Retry")})}const n=new Promise((s,r)=>{function o(a){if((a.origin||a.originalEvent.origin)!==i||typeof a.data!="string")return;const c=()=>{window.removeEventListener("message",o,!1)};a.data==="badorigin"?(c(),r(a0(i))):(c(),s(a.data))}window.addEventListener("message",o,!1)});t(`Nggraph server ${i} login required.`,"Login");try{return{token:await n}}finally{e.dispose()}}class kA extends Xa{constructor(e){super(),this.serverUrl=e,this.get=r0(async()=>{const t=await fetch(`${this.serverUrl}/token`,{method:"POST",credentials:"include"});switch(t.status){case 200:return{token:await t.text()};case 401:return await RA(this.serverUrl);case 403:throw a0(this.serverUrl);default:throw Me.j$.fromResponse(t)}})}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const LA="^(https?://[^/]+)/(.*)$";function PA(i){return(0,p.Rf)(i),{id:(0,p.cQ)(i,"id",e=>M.R.parseString((0,p.zr)(e))),baseSegments:(0,p.cQ)(i,"base_segment_ids",e=>(0,p.$v)(e,t=>M.R.parseString((0,p.zr)(t)))),baseSegmentParents:(0,p.cQ)(i,"base_segment_parent_ids",e=>(0,p.$v)(e,t=>M.R.parseString((0,p.zr)(t)))),name:(0,p.cQ)(i,"name",p.zr),tags:(0,p.cQ)(i,"tags",p.si),numVoxels:(0,p.cQ)(i,"num_voxels",p.bX),bounds:(0,p.cQ)(i,"bounds",e=>(0,p.$v)(e,t=>(0,p.zo)(t))),lastLogId:(0,p.cQ)(i,"last_log_id",e=>e==null?null:M.R.parseString((0,p.zr)(e)))}}let l0=0;class AA extends Id{constructor(e,t){super(e,t),this.debouncedVisibleSegmentsChanged=this.registerCancellable((0,xe.A)(()=>this.visibleSegmentsChanged(),0)),this.segmentQueries=new Map,this.ignoreVisibleSegmentsChanged=!1,this.segmentEquivalencesChanged=this.registerCancellable((0,xe.A)(()=>{this.debouncedVisibleSegmentsChanged.flush(),this.segmentEquivalencesChanged.cancel();const{segmentQueries:s}=this,{segmentEquivalences:r}=this.segmentsState;r.clear();for(const[o,a]of s){if(a.current===void 0||(0,Tt.YR)(a.id))continue;const{id:l,baseSegments:c}=a.current;if(c.length>0){for(const d of c)r.link(d,l);a.addedEquivalences=!0}else a.addedEquivalences=!1}},0));const n=()=>{this.ignoreVisibleSegmentsChanged||this.debouncedVisibleSegmentsChanged()};this.registerDisposer(t.visibleSegments.changed.add(n)),this.registerDisposer(t.temporaryVisibleSegments.changed.add(n)),this.visibleSegmentsChanged()}computeSplit(e,t){const{segmentEquivalences:n}=this.segmentsState,s=n.get(e);if((0,Tt.YR)(s)||!M.R.equal(n.get(t),s))return;const r=this.segmentQueries.get(s.toString());if(r===void 0)return;const{current:o}=r;if(o===void 0)return;const{baseSegments:a,baseSegmentParents:l}=o,c=l.length,d=new Rd.I;for(let m=0;m<c;++m){const g=a[m],v=l[m];M.R.equal(g,t)||M.R.equal(v,t)||(d.link(g,v),console.log(`Linking ${g} - ${v} == ${e}? ${M.R.equal(e,g)} ${M.R.equal(e,v)} :: unioned with include = ${M.R.equal(e,d.get(g))}, with exclude = ${M.R.equal(t,d.get(g))}`))}const u=[],h=[],f=d.get(e);for(const m of a)M.R.equal(d.get(m),f)?u.push(m):h.push(m);return console.log("include = "+u.map(m=>m.toString()).join(",")),console.log("exclude = "+h.map(m=>m.toString()).join(",")),{includeRepresentative:s,includeBaseSegments:u,excludeRepresentative:Tt.G1,excludeBaseSegments:h}}registerVisibleSegment(e){const t={id:e,current:void 0,addedEquivalences:!1,seenGeneration:l0,disposer:this.graph.watchSegment(e,s=>this.handleSegmentUpdate(t.id.toString(),s))},n=e.toString();this.segmentQueries.set(n,t),console.log(`adding to segmentQueries: ${n}`)}handleSegmentUpdate(e,t){console.log(`handleSegmentUpdate: ${e}`);const n=this.segmentQueries.get(e);if(t==="invalid"){n.disposer(),console.log(`removing from segmentQueries: ${e} due to invalid`),this.segmentQueries.delete(e);try{this.ignoreVisibleSegmentsChanged=!0,this.segmentsState.visibleSegments.delete(n.id),this.segmentsState.temporaryVisibleSegments.delete(n.id)}finally{this.ignoreVisibleSegmentsChanged=!1}n.addedEquivalences&&this.segmentEquivalencesChanged();return}if(t==="error"){n.current=void 0,n.addedEquivalences&&this.segmentEquivalencesChanged(),console.log(`Error from ${this.graph.serverUrl}/${this.graph.entityName} watching segment ${e}`);return}n.current=t;const s=n.id,r=t.id;if(M.R.equal(r,s))n.current=t,(0,Tt.YR)(n.id)||this.segmentEquivalencesChanged();else{n.id=r;const o=r.toString(),a=this.segmentQueries.get(o);console.log(`removing from segmentQueries: ${e} due to rename -> ${r}`),this.segmentQueries.delete(e);try{this.ignoreVisibleSegmentsChanged=!0,this.segmentsState.visibleSegments.has(s)&&this.segmentsState.visibleSegments.add(r),this.segmentsState.selectedSegments.has(s)&&(this.segmentsState.selectedSegments.delete(s),this.segmentsState.selectedSegments.add(r)),this.segmentsState.temporaryVisibleSegments.has(s)&&(this.segmentsState.temporaryVisibleSegments.delete(s),this.segmentsState.temporaryVisibleSegments.add(r))}finally{this.ignoreVisibleSegmentsChanged=!1}a===void 0?(console.log(`adding to segmentQueries due to rename -> ${r}`),this.segmentQueries.set(o,n),this.segmentEquivalencesChanged()):(t.lastLogId!==null&&(typeof a.current!="object"||a.current.lastLogId===null||M.R.less(a.current.lastLogId,t.lastLogId))&&(a.current=t,this.segmentEquivalencesChanged()),n.disposer())}}visibleSegmentsChanged(){const{segmentsState:e}=this,{segmentQueries:t}=this,n=++l0,s=r=>{for(const o of r.unsafeKeys()){if(M.R.equal(o,Tt.G1))continue;const a=o.toString(),l=t.get(a);if(l!==void 0){l.seenGeneration=n;continue}this.registerVisibleSegment(o.clone())}};s(e.visibleSegments),s(e.temporaryVisibleSegments);for(const[r,o]of t)o.seenGeneration!==n&&(console.log(`removing from segmentQueries due to seenGeneration: ${r}`),t.delete(r),o.disposer(),o.addedEquivalences&&this.segmentEquivalencesChanged())}}class MA extends Dd{constructor(e,t,n){super(),this.chunkManager=e,this.serverUrl=t,this.entityName=n,this.startingWebsocket=!1,this.websocket=void 0,this.watchesById=new Map,this.watches=new Set,this.nextWatchId=0,this.numOpenFailures=0}get visibleSegmentEquivalencePolicy(){return Tt.y6.MAX_REPRESENTATIVE|Tt.y6.REPRESENTATIVE_EXCLUDED}startWebsocket(){if(this.startingWebsocket||this.watches.size===0)return;this.startingWebsocket=!0;let e=new Se(!this.numOpenFailures);e.setText(`Opening websocket connection for nggraph://${this.serverUrl}/${this.entityName}`),(async()=>{const{numOpenFailures:t}=this;if(t>1){const o=1e3*Math.min(16,2**t);await new Promise(a=>setTimeout(a,o))}const n=(await Lu(this.chunkManager,this.serverUrl,this.entityName).get()).credentials,s=new URL("/graph/watch/"+encodeURIComponent(n.token),this.serverUrl);s.protocol=s.protocol.replace("http","ws");const r=new WebSocket(s.href);r.onclose=()=>{e!==void 0&&(e.dispose(),e=void 0),++this.numOpenFailures,this.websocket=void 0,this.startingWebsocket=!1,this.watchesById.clear(),this.startWebsocket()},r.onopen=()=>{e!==void 0&&(e.dispose(),e=void 0),this.numOpenFailures=0,this.websocket=r,this.nextWatchId=0;try{for(const o of this.watches){r.send(JSON.stringify({watch:{segment_id:o.segment.toString()}}));const a=this.nextWatchId++;o.watchId=a,this.watchesById.set(a,o)}}catch{}},r.onmessage=o=>{let a,l;try{const c=JSON.parse(o.data);(0,p.Rf)(c);const d=(0,p.cQ)(c,"watch_id",p.bX),u=this.watchesById.get(d);if(u===void 0)return;l=u;const h=(0,p.cQ)(c,"state",p.zr);h==="invalid"||h==="error"?a=h:a=(0,p.cQ)(c,"info",PA)}catch(c){console.log(`Received unexpected websocket message from ${this.serverUrl}:`,o.data,c);return}console.log("got update",a),l.callback(a)}})()}connect(e){const t=e.displayState.segmentationGroupState.value;return new AA(this,t)}trackSegment(e,t){return this.watchSegment(e,n=>{if(n==="invalid")t(null);else{if(n==="error")return;t(n.id)}})}watchSegment(e,t){const n={callback:t,segment:e,watchId:-1};this.watches.add(n);const{websocket:s}=this;if(s!==void 0)try{s.send(JSON.stringify({watch:{segment_id:e.toString()}}));const o=this.nextWatchId++;n.watchId=o,this.watchesById.set(o,n)}catch{}else this.startWebsocket();return()=>{const{websocket:o}=this;if(o!==void 0&&o.readyState===WebSocket.OPEN){const a=n.watchId;this.watchesById.delete(a);try{o.send(JSON.stringify({unwatch:{watch_id:a}}))}catch{}}this.watches.delete(n)}}async merge(e,t){const n=await Pu(this.chunkManager,this.serverUrl,this.entityName,"/graph/mutate",{body:JSON.stringify({merge:{anchor:e.toString(),other:t.toString()}}),headers:{"Content-Type":"application/json"},method:"POST"});return(0,p.Rf)(n),(0,p.cQ)(n,"merged",s=>M.R.parseString(s))}async split(e,t){const n=await Pu(this.chunkManager,this.serverUrl,this.entityName,"/graph/mutate",{body:JSON.stringify({split:{include:e.toString(),exclude:t.toString()}}),headers:{"Content-Type":"application/json"},method:"POST"});return(0,p.Rf)(n),{include:(0,p.cQ)(n,"include",s=>M.R.parseString(s)),exclude:(0,p.cQ)(n,"exclude",s=>M.R.parseString(s))}}}function c0(i){const e=i.match(LA);if(e===null)throw new Error(`Invalid nggraph url: ${JSON.stringify(i)}`);return{serverUrl:e[1],id:e[2]}}function ku(i,e,t,n,s=at.fx){return(0,hu.R)(i,`${e}${t}`,n,Me.cj,(r,o)=>{const a=new Headers(o.headers);return a.set("Authorization",r.token),{...o,headers:a}},r=>{const{status:o}=r;if(o===401)return"refresh";throw r},s)}function NA(i,e,t,n,s=at.fx){return ku(d0(i,e),e,t,n,s)}class OA extends Xa{constructor(e,t,n){super(),this.parentCredentialsProvider=e,this.serverUrl=t,this.entityName=n,this.get=r0(async()=>{const s=await ku(this.parentCredentialsProvider,this.serverUrl,"/entity_token",{body:JSON.stringify({entity:this.entityName}),headers:{"Content-Type":"application/json"},method:"POST"});return{token:s.token,entityType:s.entity_type,role:s.role}})}}function d0(i,e){return i.memoize.getUncounted({type:"nggraph:credentialsProvider",serverUrl:e},()=>new kA(e))}function Lu(i,e,t){return i.memoize.getUncounted({type:"nggraph:entityCredentialsProvider",serverUrl:e,entityName:t},()=>new OA(d0(i,e),e,t))}function Pu(i,e,t,n,s,r=at.fx){return ku(Lu(i,e,t),e,n,s,r)}function VA(i){return(0,p.Rf)(i),(0,p.cQ)(i,"entities",e=>(0,p.$v)(e,t=>{(0,p.Rf)(t);const n=(0,p.cQ)(t,"entity",p.zr),s=(0,p.cQ)(t,"entity_type",p.zr),r=(0,p.cQ)(t,"access_role",p.zr);return{id:n,entityType:s,accessRole:r}}))}class _A extends Ut{get description(){return"nggraph data source"}get(e){const{serverUrl:t,id:n}=c0(e.providerUrl);return e.chunkManager.memoize.getUncounted({type:"nggraph:get",serverUrl:t,id:n},async()=>{const s=Lu(e.chunkManager,t,n),{entityType:r}=(await s.get()).credentials;if(r!=="graph")throw new Error(`Unsupported entity type: ${JSON.stringify(r)}`);const{datasource_url:o}=await Pu(e.chunkManager,t,n,"/graph/config",{method:"POST"}),a=await e.registry.get({...e,url:o}),l=new MA(e.chunkManager,t,n),c=[...a.subsources,{id:"graph",default:!0,subsource:{segmentationGraph:l}}];return{modelTransform:a.modelTransform,subsources:c}})}async completeUrl(e){const{serverUrl:t,id:n}=c0(e.providerUrl),s=await e.chunkManager.memoize.getUncounted({type:"nggraph:list",serverUrl:t},async()=>VA(await NA(e.chunkManager,t,"/list",{method:"POST"})));return{offset:t.length+1,completions:Wt(n,s,r=>r.id,r=>`${r.entityType} (${r.accessRole})`)}}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("nggraph",()=>new _A);var u0=G(6435);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class BA extends Ke(st()(Mn),u0.C){}class FA extends Ht{constructor(e,t,n,s){super(e),this.credentialsProvider=t,this.url=n,this.info=s}get dataType(){return this.info.dataType}get volumeType(){return gt.UNKNOWN}get rank(){return this.info.rank}getSources(e){const{info:t}=this,n=we.DA(Float32Array,t.rank+1),s=fv({rank:t.rank,volumeType:gt.UNKNOWN,chunkDataSize:t.volumeSize,dataType:t.dataType,upperVoxelBound:Float32Array.from(t.volumeSize),chunkToMultiscaleTransform:n,volumeSourceOptions:e});return[[{chunkSource:this.chunkManager.getChunkSource(BA,{credentialsProvider:this.credentialsProvider,spec:s,parameters:{url:this.url}}),chunkToMultiscaleTransform:n}]]}}function UA(i,e,t,n){return i.rpc.promiseInvoke(u0.Y,{chunkManager:i.addCounterpartRef(),credentialsProvider:du(i,e),url:t},n)}function $A(i,e,t){return i.memoize.getUncounted({type:"nifti/getVolume",url:t},async()=>{const{url:n,credentialsProvider:s}=bn(t,e),r=await UA(i,s,n,at.fx),o=new FA(i,s,n,r),a={lowerBounds:new Float64Array(r.rank),upperBounds:Float64Array.from(r.volumeSize)},l=ke({rank:r.rank,names:r.sourceNames,scales:r.sourceScales,units:r.units,boundingBoxes:[dn(a)]}),c=ke({rank:r.rank,names:r.viewNames,scales:r.viewScales,units:r.units});return{subsources:[{id:"default",default:!0,subsource:{volume:o}},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(a)}}],modelTransform:{sourceRank:r.rank,rank:r.rank,inputSpace:l,outputSpace:c,transform:r.transform}}})}class GA extends Ut{get description(){return"Single NIfTI file"}get(e){return $A(e.chunkManager,e.credentialsManager,e.providerUrl)}completeUrl(e){return Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("nifti",()=>new GA);/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class zA extends Ut{get description(){return"Wavefront OBJ mesh file"}async get(e){const t=await nS(e.chunkManager,e.credentialsManager,e.url),n=ke({rank:3,names:["x","y","z"],units:["m","m","m"],scales:Float64Array.of(1e-9,1e-9,1e-9)});return{modelTransform:yt(n),subsources:[{id:"default",default:!0,subsource:{singleMesh:t}}]}}completeUrl(e){return Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("obj",()=>new zA);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("precomputed",()=>new kS);var WA=G(8997);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const HA=new Set(["jpg","raw16"]),JA=Ke(Mn,WA.vc);class jA extends JA{}const YA=new Set(["COMPLETE","READ_ONLY"]),QA=new Set(["LOADING"]);function qA(i){const e=(0,p.$v)(i,p.Rf);if(e.length<1)throw new Error("No stacks found for owner object.");const t=new Map,n=(0,p.cQ)(e[0],"stackId",XA);for(const s of e){const r=(0,p.cQ)(s,"stackId",KA),o=ZA(s);if(o!==void 0){const a=o.project;let l=t.get(a);if(l===void 0){const c=new Map;t.set(a,{stacks:c}),l=t.get(a)}l.stacks.set(r,o)}}return{owner:n,projects:t}}function KA(i){return(0,p.Rf)(i),(0,p.cQ)(i,"stack",p.zr)}function XA(i){return(0,p.Rf)(i),(0,p.cQ)(i,"owner",p.zr)}function ZA(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"state",p.zr);let t=[],n=w.eR.create(),s=w.eR.create();if(YA.has(e)){const a=(0,p.cQ)(i,"stats",p.Rf);n=tM(a),s=eM(a),Object.prototype.hasOwnProperty.call(a,"channelNames")&&(t=nM(a))}else if(!QA.has(e))return;const r=(0,p.cQ)(i,"currentVersion",iM),o=(0,p.cQ)(i,"stackId",sM);return{lowerVoxelBound:n,upperVoxelBound:s,voxelResolution:r,project:o,channels:t}}function eM(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"stackBounds",p.Rf),t=w.eR.create();return t[0]=(0,p.cQ)(e,"maxX",p._D)+1,t[1]=(0,p.cQ)(e,"maxY",p._D)+1,t[2]=(0,p.cQ)(e,"maxZ",p._D)+1,t}function tM(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"stackBounds",p.Rf),t=w.eR.create();return t[0]=(0,p.cQ)(e,"minX",p._D),t[1]=(0,p.cQ)(e,"minY",p._D),t[2]=(0,p.cQ)(e,"minZ",p._D),t}function nM(i){return(0,p.Rf)(i),(0,p.cQ)(i,"channelNames",e=>(0,p.$v)(e,p.zr))}function iM(i){(0,p.Rf)(i);const e=w.eR.create();try{e[0]=(0,p.cQ)(i,"stackResolutionX",p._D),e[1]=(0,p.cQ)(i,"stackResolutionY",p._D),e[2]=(0,p.cQ)(i,"stackResolutionZ",p._D)}catch{e[0]=1,e[1]=1,e[2]=1}return e}function sM(i){return(0,p.Rf)(i),(0,p.cQ)(i,"project",p.zr)}class rM extends Ht{constructor(e,t,n,s,r,o,a){super(e),this.baseUrl=t,this.ownerInfo=n,this.project=r,this.parameters=a;const l=n.projects.get(r);if(l===void 0)throw new Error(`Specified project ${JSON.stringify(r)} does not exist for specified owner ${JSON.stringify(n.owner)}`);if(s===void 0){const h=Array.from(l.stacks.keys());if(h.length!==1)throw new Error(`Dataset contains multiple stacks: ${JSON.stringify(h)}`);s=h[0]}const c=l.stacks.get(s);if(c===void 0)throw new Error(`Specified stack ${JSON.stringify(s)} is not one of the supported stacks: `+JSON.stringify(Array.from(l.stacks.keys())));this.stack=s,this.stackInfo=c,o!==void 0&&o.length>0&&(this.channel=o),this.minIntensity=(0,p.zB)(a.minIntensity),this.maxIntensity=(0,p.zB)(a.maxIntensity),this.maxTileSpecsToRender=(0,p.zB)(a.maxTileSpecsToRender),this.filter=(0,p.uS)(a.filter),this.minX=(0,p.zB)(a.minX),this.minY=(0,p.zB)(a.minY),this.minZ=(0,p.zB)(a.minZ),this.maxX=(0,p.zB)(a.maxX),this.maxY=(0,p.zB)(a.maxY),this.maxZ=(0,p.zB)(a.maxZ),this.minX!==void 0&&(c.lowerVoxelBound[0]=this.minX),this.minY!==void 0&&(c.lowerVoxelBound[1]=this.minY),this.minZ!==void 0&&(c.lowerVoxelBound[2]=this.minZ),this.maxX!==void 0&&(c.upperVoxelBound[0]=this.maxX),this.maxY!==void 0&&(c.upperVoxelBound[1]=this.maxY),this.maxZ!==void 0&&(c.upperVoxelBound[2]=this.maxZ);let d=(0,p.z$)(a.encoding);if(d===void 0)d="jpg";else if(!HA.has(d))throw new Error(`Invalid encoding: ${JSON.stringify(d)}.`);this.encoding=d,this.numLevels=(0,p.zB)(a.numlevels),this.dims=w.eR.create();let u=(0,p.zB)(a.tilesize);u===void 0&&(u=1024),this.dims[0]=u,this.dims[1]=u,this.dims[2]=1}get dataType(){return this.parameters.encoding==="raw16"?I.UINT16:I.UINT8}get volumeType(){return gt.IMAGE}get rank(){return 3}getSources(e){const t=[];let n=this.numLevels;n===void 0&&(n=oM(this.stackInfo,this.dims[0]));const{lowerVoxelBound:s,upperVoxelBound:r}=this.stackInfo;for(let o=0;o<n;o++){const a=w.pB.create(),l=Uint32Array.of(1,1,1);for(let g=0;g<2;++g)a[5*g]=2**o,l[g]=this.dims[g];const c=w.eR.create(),d=w.eR.create(),u=w.eR.create(),h=w.eR.create();for(let g=0;g<3;g++){const v=a[5*g],y=u[g]=s[g]/v,S=h[g]=r[g]/v;c[g]=Math.floor(y),d[g]=Math.ceil(S)}const f=Ad({rank:3,chunkDataSize:l,dataType:this.dataType,lowerVoxelBound:c,upperVoxelBound:d}),m=this.chunkManager.getChunkSource(jA,{spec:f,parameters:{baseUrl:this.baseUrl,owner:this.ownerInfo.owner,project:this.stackInfo.project,stack:this.stack,channel:this.channel,minIntensity:this.minIntensity,maxIntensity:this.maxIntensity,maxTileSpecsToRender:this.maxTileSpecsToRender,filter:this.filter,dims:`${this.dims[0]}_${this.dims[1]}`,level:o,encoding:this.encoding}});t.push([{chunkSource:m,chunkToMultiscaleTransform:a,lowerClipBound:u,upperClipBound:h}])}return(0,z.RO)(t)}}function oM(i,e){let t=0;for(let s=0;s<2;s++)t=Math.max(t,i.upperVoxelBound[s]);if(e>=t)return 1;let n=0;for(;t>e;)t=t/2,n++;return n}function Za(i,e,t){return i.memoize.getUncounted({type:"render:getOwnerInfo",hostname:e,owner:t},()=>(0,Me.vd)(`${e}/render-ws/v1/owner/${t}/stacks`).then(n=>n.json()).then(qA))}const aM=/^([^/?]+)(?:\/([^/?]+))?(?:\/([^/?]+))(?:\/([^/?]*))?(?:\?(.*))?$/,h0=/^((?:(?:(?:http|https):\/\/[^,/]+)[^/?]))\/(.*)$/;function lM(i,e){let t,n;{const d=e.match(h0);if(d===null)throw new Error(`Invalid render volume path: ${JSON.stringify(e)}`);t=d[1],n=d[2]}const s=n.match(aM);if(s===null)throw new Error(`Invalid volume path ${JSON.stringify(n)}`);const r=s[1],o=s[2],a=s[3],l=s[4],c=(0,p.bL)(s[5]||"");return i.memoize.getUncounted({type:"render:MultiscaleVolumeChunkSource",hostname:t,path:n},async()=>{const d=await Za(i,t,r),u=new rM(i,t,d,a,o,l,c),h=ke({rank:3,names:["x","y","z"],units:["m","m","m"],scales:Float64Array.from(u.stackInfo.voxelResolution,m=>m/1e9),boundingBoxes:[dn({lowerBounds:new Float64Array(u.stackInfo.lowerVoxelBound),upperBounds:new Float64Array(u.stackInfo.upperVoxelBound)})]});return{modelTransform:yt(h),subsources:[{id:"default",default:!0,subsource:{volume:u}},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(h.bounds)}}]}})}async function cM(i,e,t){const n=t.match(/^(?:([^/]+)(?:\/([^/]*))?(?:\/([^/]*))?(\/.*?)?)?$/);if(n===null||n[2]===void 0)throw null;if(n[3]===void 0){const d=n[2]||"",u=await Za(i,e,n[1]),h=Wt(d,u.projects,f=>f[0]+"/",()=>{});return{offset:n[1].length+1,completions:h}}if(n[4]===void 0){const d=n[3]||"",h=(await Za(i,e,n[1])).projects.get(n[2]);if(h===void 0)throw null;const f=Wt(d,h.stacks,m=>m[0]+"/",m=>m[1].project);return{offset:n[1].length+n[2].length+2,completions:f}}const s=n[4].substr(1)||"",o=(await Za(i,e,n[1])).projects.get(n[2]);if(o===void 0)throw null;const a=o.stacks.get(n[3]);if(a===void 0)throw null;const l=a.channels;if(l.length===0)throw null;const c=Wt(s,l,d=>d,()=>{});return{offset:n[1].length+n[2].length+n[3].length+3,completions:c}}async function dM(i,e){const t=i.match(h0);if(t===null)throw null;const n=t[1],s=t[2],r=await cM(e,n,s);return li(t[1].length+1,r)}class uM extends Ut{get description(){return"Render"}get(e){return lM(e.chunkManager,e.providerUrl)}completeUrl(e){return dM(e.providerUrl,e.chunkManager)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("render",()=>new uM);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hM extends Ut{get description(){return"VTK mesh file"}async get(e){const t=await nS(e.chunkManager,e.credentialsManager,e.url),n=ke({rank:3,names:["x","y","z"],units:["m","m","m"],scales:Float64Array.of(1e-9,1e-9,1e-9)});return{modelTransform:yt(n),subsources:[{id:"default",default:!0,subsource:{singleMesh:t}}]}}completeUrl(e){return Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("vtk",()=>new hM);var Ot=G(2334);/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Au(i,e,t){(0,p.Rf)(i);const n=(0,p.cQ)(i,"name",r=>e((0,p.zr)(r))),s=(0,p.cQ)(i,"configuration",r=>(r===void 0?r={}:(0,p.Rf)(r),t(r,n)));return{name:n,configuration:s}}/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function pM(i){const{name:e,configuration:t}=Au(i,n=>{const s=p0.get(n);if(s===void 0)throw new Error(`Unknown codec: ${JSON.stringify(n)}`);return s},n=>n);return{resolver:e,configuration:t}}const p0=new Map;function Zi(i){p0.set(i.name,i)}function el(i,e){const t=[],n=[],s=[],r=[];n.push(e);const o=(0,p.$v)(i,pM),a=o.length;let l=0;for(;l<a;++l){const{resolver:g,configuration:v}=o[l];if(g.kind!==Ot.L.arrayToArray)break;const y=g,{configuration:S,encodedArrayInfo:x}=y.resolve(v,e);n.push(x),e=x,t.push({kind:Ot.L.arrayToArray,name:g.name,configuration:S})}if(l===a||o[l].resolver.kind!==Ot.L.arrayToBytes)throw new Error("Missing array -> bytes codec");const{codecSpec:c,layoutInfo:d,encodedSize:u,shardingInfo:h}=(()=>{const{resolver:g,configuration:v}=o[l],y=g,{configuration:S,shardingInfo:x,encodedSize:b}=y.resolve(v,e);if(x!==void 0&&l+1!==a)throw new Error("bytes -> bytes codecs not supported following sharding codec");const E=y.getDecodedArrayLayoutInfo(S,e);return{codecSpec:{name:g.name,kind:Ot.L.arrayToBytes,configuration:S},layoutInfo:E,encodedSize:b,shardingInfo:x}})();s[l]=d,r.push(u);const f=u,m=[];for(++l;l<a;){const{resolver:g,configuration:v}=o[l];if(g.kind!==Ot.L.bytesToBytes)throw new Error(`Expected bytes -> bytes codec, but received ${JSON.stringify(g.name)} of kind ${Ot.L[g.kind]}`);const y=g,{configuration:S,encodedSize:x}=y.resolve(v,f);m.push({name:g.name,kind:g.kind,configuration:S}),r.push(x),++l}for(let g=t.length-1;g>=0;--g)s[g]=o[g].resolver.getDecodedArrayLayoutInfo(t[g].configuration,n[g],s[g+1]);return{[Ot.L.arrayToArray]:t,[Ot.L.arrayToBytes]:c,[Ot.L.bytesToBytes]:m,arrayInfo:n,layoutInfo:s,shardingInfo:h,encodedSize:r}}/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Zi({name:"blosc",kind:Ot.L.bytesToBytes,resolve(i){return(0,p.Rf)(i),{configuration:{}}}});/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Zi({name:"zstd",kind:Ot.L.bytesToBytes,resolve(i){return(0,p.Rf)(i),{configuration:{}}}});var fM=G(6742);/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Zi({name:"bytes",kind:Ot.L.arrayToBytes,resolve(i,e){(0,p.Rf)(i);const t=(0,p.cQ)(i,"endian",s=>{switch(s){case"little":return F.LITTLE;case"big":return F.BIG;case void 0:if(B[e.dataType]===1)return te}throw new Error(`Invalid endian value: ${JSON.stringify(s)}`)}),n=e.chunkShape.reduce((s,r)=>s*r,1);return{configuration:{endian:t},encodedSize:B[e.dataType]*n}},getDecodedArrayLayoutInfo(i,e){return{physicalToLogicalDimension:Array.from(e.chunkShape,(t,n)=>n),readChunkShape:e.chunkShape}}});/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Zi({name:"crc32c",kind:Ot.L.bytesToBytes,resolve(i,e){let t;return e!==void 0&&(t=e+4),{configuration:{},encodedSize:t}}});/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Zi({name:"gzip",kind:Ot.L.bytesToBytes,resolve(i){return(0,p.Rf)(i),{configuration:{level:(0,p.cQ)(i,"level",p.bX)}}}});/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var tl=(i=>(i[i.DEFAULT=0]="DEFAULT",i[i.V2=1]="V2",i))(tl||{});/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Qn=new Map;Qn.set("|u1",{endianness:F.LITTLE,dataType:I.UINT8}),Qn.set("|i1",{endianness:F.LITTLE,dataType:I.INT8});for(const[i,e]of[["<",F.LITTLE],[">",F.BIG]]){for(const t of["u","i"])Qn.set(`${i}${t}8`,{endianness:e,dataType:I.UINT64});Qn.set(`${i}u2`,{endianness:e,dataType:I.UINT16}),Qn.set(`${i}i2`,{endianness:e,dataType:I.INT16}),Qn.set(`${i}u4`,{endianness:e,dataType:I.UINT32}),Qn.set(`${i}i4`,{endianness:e,dataType:I.INT32}),Qn.set(`${i}f4`,{endianness:e,dataType:I.FLOAT32})}function gM(i){const e=Qn.get(i);if(e===void 0)throw new Error(`Unsupported numpy data type: ${JSON.stringify(i)}`);return e}/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function f0(i){return(0,p.$v)(i,e=>{if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error(`Expected non-negative integer, but received: ${JSON.stringify(e)}`);return e})}function Mu(i,e){return(0,p.Xu)(new Array(e),i,t=>{if(typeof t!="number"||!Number.isInteger(t)||t<=0)throw new Error(`Expected positive integer, but received: ${JSON.stringify(t)}`);return t})}function Nu(i){if(i!=="."&&i!=="/")throw new Error(`Expected "." or "/", but received: ${JSON.stringify(i)}`);return i}const Ou=new Map([["",{unit:"",scale:1}],["angstrom",{unit:"m",scale:1e-10}],["foot",{unit:"m",scale:.3048}],["inch",{unit:"m",scale:.0254}],["mile",{unit:"m",scale:1609.34}],["parsec",{unit:"m",scale:0x6da012f95c9e88}],["yard",{unit:"m",scale:.9144}],["minute",{unit:"s",scale:60}],["hour",{unit:"s",scale:60*60}],["day",{unit:"s",scale:60*60*24}]]);for(const i of["meter","second"])for(const e of Rl){const{longPrefix:t,prefix:n}=e;if(t===void 0)continue;const s={unit:i[0],scale:10**e.exponent};Ou.set(`${t}${i}`,s),Ou.set(`${n}${i[0]}`,s)}function mM(i){if(i===null)return{scale:1,unit:""};if(typeof i!="string")throw new Error(`Expected string but received: ${JSON.stringify(i)}`);const e=i.trim(),t=/^([-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?\d+)?)\s*(.*)/,n=e.match(t);let s,r;n===null?(s=1,r=e):(s=Number(n[1]),r=n[2]);const o=Ou.get(r);if(o===void 0)throw new Error(`Unsupported unit: ${JSON.stringify(r)}`);return{unit:o.unit,scale:s*o.scale}}function g0(i,e){switch(i){case I.UINT8:case I.INT8:case I.UINT16:case I.INT16:case I.UINT32:case I.INT32:case I.UINT64:if(typeof e!="number"||!Number.isInteger(e))throw new Error(`Expected integer but received: ${JSON.stringify(e)}`);return e;case I.FLOAT32:if(typeof e=="number")return e;if(typeof e=="string"){if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e==="NaN")return new Float32Array(Uint32Array.of(2143289344).buffer)[0];if(e.match(/^0x[a-fA-F0-9]+$/))return new Float32Array(Uint32Array.of(Number(e)).buffer)[0]}throw new Error(`Expected number, "Infinity", "-Infinity", "NaN", or hex string but received: ${JSON.stringify(e)}`)}}function vM(i,e){try{(0,p.Rf)(i),(0,p.cQ)(i,"zarr_format",m=>{(0,p.qi)(m,3)});const t=(0,p.cQ)(i,"node_type",m=>{if(e!==void 0&&(0,p.qi)(m,e),m!=="array"&&m!=="group")throw new Error(`Expected "array" or "group" but received: ${JSON.stringify(m)}`);return m});if(e=t,t==="group")return{zarrVersion:3,nodeType:"group",userAttributes:(0,p.MM)(i,"attributes",p.Rf,{})};const n=(0,p.cQ)(i,"shape",f0),s=n.length,r=(0,p.cQ)(i,"dimension_names",m=>(0,p.ZD)(m??void 0,s)),o=(0,p.cQ)(i,"data_type",m=>(0,p.sl)(m,I,/^[a-z0-9]+$/)),{configuration:a}=(0,p.cQ)(i,"chunk_grid",m=>Au(m,g=>(0,p.qi)(g,"regular"),g=>(0,p.cQ)(g,"chunk_shape",v=>Mu(v,s)))),{userAttributes:l,dimensionUnits:c}=(0,p.cQ)(i,"attributes",m=>{m===void 0&&(m={}),(0,p.Rf)(m);const g=(0,p.cQ)(m,"dimension_units",v=>(0,p.ZD)(v,s));return{userAttributes:m,dimensionUnits:g}}),{configuration:d,name:u}=(0,p.cQ)(i,"chunk_key_encoding",m=>Au(m,g=>(0,p.sl)(g,tl,/^(v2|default)$/),(g,v)=>(0,p.MM)(g,"separator",Nu,v===tl.DEFAULT?"/":"."))),h=(0,p.cQ)(i,"fill_value",m=>g0(o,m)),f=(0,p.cQ)(i,"codecs",m=>el(m,{dataType:o,chunkShape:a}));return{zarrVersion:3,nodeType:t,rank:s,shape:n,chunkShape:a,dataType:o,fillValue:h,dimensionNames:r,dimensionUnits:c,chunkKeyEncoding:u,dimensionSeparator:d,userAttributes:l,codecs:f}}catch(t){const n=e===void 0?"":`${e} `;throw new Error(`Error parsing zarr v3 ${n}metadata: ${t.message}`)}}function yM(i,e,t){try{(0,p.Rf)(i),(0,p.cQ)(i,"zarr_format",f=>{(0,p.qi)(f,2)});const n=(0,p.cQ)(i,"shape",f0),s=n.length,r=(0,p.cQ)(i,"chunks",f=>Mu(f,s)),o=(0,p.cQ)(i,"order",f=>{if(f!=="C"&&f!=="F")throw new Error(`Expected "C" or "F", but received: ${JSON.stringify(f)}`);return f}),a=(0,p.MM)(i,"dimension_separator",t===void 0?Nu:f=>(0,p.qi)(f,t),t??"."),l=(0,p.cQ)(i,"dtype",f=>gM((0,p.zr)(f))),c=l.dataType,d=(0,p.cQ)(i,"fill_value",f=>f===null?0:g0(c,f)),u=[];o==="F"&&u.push({name:"transpose",configuration:{order:Array.from(n,(f,m)=>s-m-1)}}),u.push({name:"bytes",configuration:{endian:l.endianness===F.LITTLE?"little":"big"}}),(0,p.cQ)(i,"compressor",f=>{if(f===null)return;(0,p.Rf)(f);const m=(0,p.cQ)(f,"id",p.zr);switch(m){case"blosc":u.push({name:"blosc",configuration:{cname:(0,p.cQ)(f,"cname",p.zr),clevel:(0,p.cQ)(f,"clevel",p.bX),typesize:B[c],shuffle:(0,p.cQ)(f,"shuffle",g=>{switch(g){case-1:return B[c]===1?"bitshuffle":"shuffle";case 0:return"noshuffle";case 1:return"shuffle";case 2:return"bitshuffle"}throw new Error(`Invalid value: ${JSON.stringify(g)}`)}),blocksize:(0,p.MM)(f,"blocksize",p.bX,0)}});break;case"zlib":case"gzip":u.push({name:"gzip",configuration:{level:(0,p.cQ)(f,"level",p.bX)}});break;case"zstd":u.push({name:"zstd",configuration:{level:(0,p.cQ)(f,"level",p.bX)}});break;default:throw new Error(`Unsupported compressor: ${JSON.stringify(m)}`)}});const h=el(u,{dataType:c,chunkShape:r});return{zarrVersion:2,nodeType:"array",rank:s,shape:n,chunkShape:r,dataType:c,fillValue:d,dimensionNames:(0,p.cQ)(e,"_ARRAY_DIMENSIONS",f=>(0,p.ZD)(f,s)),dimensionUnits:(0,p.cQ)(e,"dimension_units",f=>(0,p.ZD)(f,s)),userAttributes:e,dimensionSeparator:a,chunkKeyEncoding:tl.V2,codecs:h}}catch(n){throw new Error(`Error parsing zarr v2 metadata: ${n.message}`)}}/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var m0=(i=>(i[i.START=0]="START",i[i.END=1]="END",i))(m0||{});Zi({name:"sharding_indexed",kind:Ot.L.arrayToBytes,resolve(i,e){(0,p.Rf)(i);const t=(0,p.cQ)(i,"chunk_shape",l=>Mu(l,e.chunkShape.length)),n=(0,p.MM)(i,"index_location",l=>(0,p.sl)(l,m0,/^[a-z]+$/),1),s=Array.from(e.chunkShape,(l,c)=>{const d=t[c];if(l%d!==0)throw new Error(`sub-chunk shape of ${JSON.stringify(d)} does not evenly divide outer chunk shape of ${JSON.stringify(e.chunkShape)}`);return l/d}),r=Array.from(s);r.push(2);const o=(0,p.cQ)(i,"index_codecs",l=>el(l,{dataType:I.UINT64,chunkShape:r}));if(o.encodedSize[o.encodedSize.length-1]===void 0)throw new Error("index_codecs must specify fixed-size encoding");const a=(0,p.cQ)(i,"codecs",l=>el(l,{dataType:e.dataType,chunkShape:t}));return{configuration:{indexCodecs:o,subChunkCodecs:a,subChunkShape:t,subChunkGridShape:s,indexLocation:n},shardingInfo:{subChunkShape:t,subChunkGridShape:s,subChunkCodecs:a}}},getDecodedArrayLayoutInfo(i,e){return i.subChunkCodecs.layoutInfo[0]}});/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Zi({name:"transpose",kind:Ot.L.arrayToArray,resolve(i,e){(0,p.Rf)(i);const{order:t,inverseOrder:n}=(0,p.cQ)(i,"order",r=>{const o=e.chunkShape.length,a=new Array(o),l=new Array(o);if(r==="C")for(let c=0;c<o;++c)a[c]=c,l[c]=c;else if(r==="F")for(let c=0;c<o;++c)a[c]=o-c-1,l[c]=o-c-1;else(0,p.Xu)(a,r,(c,d)=>{if(typeof c!="number"||!Number.isInteger(c)||c<0||c>=o)throw new Error(`Expected integer in range [0, ${o}) but received: ${JSON.stringify(c)}`);if(l[c]!==void 0)throw new Error(`Invalid permutation: ${JSON.stringify(r)}`);return l[c]=d,c});return{order:a,inverseOrder:l}}),s={dataType:e.dataType,chunkShape:Array.from(t,r=>e.chunkShape[r])};return{configuration:{encodedToDecoded:t,decodedToEncoded:n},encodedArrayInfo:s}},getDecodedArrayLayoutInfo(i,e,t){return{physicalToLogicalDimension:Array.from(t.physicalToLogicalDimension,s=>i.encodedToDecoded[s]),readChunkShape:Array.from(i.decodedToEncoded,s=>t.readChunkShape[s])}}});/**
 * @license
 * Copyright 2022 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const SM=new Set(["0.4","0.5-dev"]),v0=new Map([["angstrom",{unit:"m",scale:1e-10}],["foot",{unit:"m",scale:.3048}],["inch",{unit:"m",scale:.0254}],["mile",{unit:"m",scale:1609.34}],["parsec",{unit:"m",scale:0x6da012f95c9e88}],["yard",{unit:"m",scale:.9144}],["minute",{unit:"s",scale:60}],["hour",{unit:"s",scale:60*60}],["day",{unit:"s",scale:60*60*24}]]);for(const i of["meter","second"])for(const e of Rl){const{longPrefix:t}=e;t!==void 0&&v0.set(`${t}${i}`,{unit:i[0],scale:10**e.exponent})}function bM(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"name",p.zr),t=(0,p.MM)(i,"type",p.zr),n=(0,p.MM)(i,"unit",s=>{const r=v0.get(s);if(r===void 0)throw new Error(`Unsupported unit: ${JSON.stringify(s)}`);return r},{unit:"",scale:1});return{name:e,unit:n.unit,scale:n.scale,type:t}}function wM(i){const e=(0,p.$v)(i,bM);return ke({names:e.map(t=>{const{name:n,type:s}=t;return s==="channel"?`${n}'`:n}),scales:Float64Array.from(e,t=>t.scale),units:e.map(t=>t.unit)})}function CM(i,e){const t=(0,p.cQ)(e,"scale",n=>(0,p.Xu)(new Float64Array(i),n,p.Mo));return we.nx(Float64Array,t)}function xM(i,e){return we.DA(Float64Array,i+1)}function EM(i,e){const t=(0,p.cQ)(e,"translation",n=>(0,p.Xu)(new Float64Array(i),n,p.zo));return we.u6(Float64Array,t)}const TM=new Map([["scale",CM],["identity",xM],["translation",EM]]);function DM(i,e){(0,p.Rf)(e);const t=(0,p.cQ)(e,"type",p.zr),n=TM.get(t);if(n===void 0)throw new Error(`Unsupported coordinate transform type: ${JSON.stringify(t)}`);return n(i,e)}function y0(i,e){let t=we.DA(Float64Array,i+1);return e===void 0||(0,p.$v)(e,n=>{const s=DM(i,n);t=we.lw(new Float64Array(t.length),i+1,s,i+1,t,i+1,i+1,i+1,i+1)}),t}function IM(i,e,t){const n=(0,p.cQ)(t,"path",p.zr),s=(0,p.cQ)(t,"coordinateTransformations",o=>y0(i,o));return{url:`${e}/${n}`,transform:s}}function RM(i,e){const t=(0,p.cQ)(e,"axes",wM),n=t.rank,s=(0,p.cQ)(e,"coordinateTransformations",l=>y0(n,l)),r=(0,p.cQ)(e,"datasets",l=>(0,p.$v)(l,c=>{const d=IM(n,i,c);return d.transform=we.lw(new Float64Array((n+1)**2),n+1,s,n+1,d.transform,n+1,n+1,n+1,n+1),d}));if(r.length===0)throw new Error("At least one scale must be specified");const o=r[0].transform,a=new Float64Array(n);for(let l=0;l<n;++l){const c=a[l]=o[l*(n+1)+l];t.scales[l]*=c}for(const l of r){const c=l.transform;for(let d=0;d<n;++d){let u=0;for(let h=0;h<n;++h)u+=c[h*(n+1)+d]*.5;c[n*(n+1)+d]-=u}for(let d=0;d<n;++d)for(let u=0;u<=n;++u)c[u*(n+1)+d]/=a[d]}return{coordinateSpace:t,scales:r}}function kM(i,e){const t=e.multiscales;if(!Array.isArray(t))return;const n=[];for(const s of t){if(typeof s!="object"||s==null||Array.isArray(s))return;const r=s.version;if(r===void 0)return;if(!SM.has(r)){n.push(`OME multiscale metadata version ${JSON.stringify(r)} is not supported`);continue}return RM(i,s)}if(n.length!==0)throw new Error(n[0])}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class LM extends Ke(st()(Mn),fM.j){}class PM extends Ht{constructor(e,t,n){super(e),this.credentialsProvider=t,this.multiscale=n,this.volumeType=gt.IMAGE}get dataType(){return this.multiscale.dataType}get modelSpace(){return this.multiscale.coordinateSpace}get rank(){return this.multiscale.coordinateSpace.rank}getSources(e){return(0,z.RO)(this.multiscale.scales.map(t=>{const{metadata:n}=t,{rank:s,codecs:r,shape:o}=n,a=r.layoutInfo[0].readChunkShape,{physicalToLogicalDimension:l}=n.codecs.layoutInfo[0],c=new Uint32Array(s),d=new Float32Array(s),u=new Float32Array((s+1)**2);u[(s+1)**2-1]=1;for(let f=0;f<s;++f){const m=l[s-1-f];c[f]=a[m],d[f]=o[m],u[f+m*(s+1)]=1}const h=new Float32Array((s+1)**2);return we.lw(h,s+1,t.transform,s+1,u,s+1,s+1,s+1,s+1),gi({rank:s,chunkToMultiscaleTransform:h,dataType:n.dataType,upperVoxelBound:d,volumeType:this.volumeType,chunkDataSizes:[c],volumeSourceOptions:e,fillValue:n.fillValue}).map(f=>({chunkSource:this.chunkManager.getChunkSource(LM,{credentialsProvider:this.credentialsProvider,spec:f,parameters:{url:t.url,metadata:n}}),chunkToMultiscaleTransform:h}))}))}}function Vu(i,e,t){return i.memoize.getUncounted({type:"zarr:json",url:t,credentialsProvider:St(e)},async()=>{try{return await rn(e,t,{},Me.cj)}catch(n){if((0,Me.El)(n))return;throw n}})}const AM=[{key:{value:"dimension_separator",description:"Dimension separator in chunk keys"},values:[{value:".",description:"(default)"},{value:"/",description:""}]}];function MM(i,e){const t=new Set,n=e===2?"d":"dim_";return i.map((s,r)=>{if(s===null){let a=r;for(;;){if(s=`${n}${a}`,!t.has(s))return t.add(s),s;++a}}if(!t.has(s))return t.add(s),s;let o=1;for(;;){const a=`${s}${o}`;if(!t.has(a))return t.add(a),a;++o}})}function NM(i,e){const t=MM(e.dimensionNames,e.zarrVersion),n=e.dimensionUnits.map(mM),s=ke({names:t,scales:Float64Array.from(Array.from(n,o=>o.scale)),units:Array.from(n,o=>o.unit),boundingBoxes:[dn({lowerBounds:new Float64Array(e.rank),upperBounds:Float64Array.from(e.shape)})]}),r=we.DA(Float64Array,e.rank+1);return{coordinateSpace:s,dataType:e.dataType,scales:[{url:i,transform:r,metadata:e}]}}async function OM(i,e,t,n){const s=await Promise.all(t.scales.map(async g=>{const v=await nl(i,e,g.url,{zarrVersion:n.zarrVersion,expectedNodeType:"array",explicitDimensionSeparator:n.explicitDimensionSeparator});if(v===void 0)throw new Error(`zarr v{zarrVersion} array metadata not found at ${g.url}`);return v})),r=s[0].dataType,o=s.length,a=t.coordinateSpace.rank;for(let g=0;g<o;++g){const v=t.scales[g],y=s[g];if(y.rank!==a)throw new Error(`Expected zarr array at ${JSON.stringify(v.url)} to have rank ${a}, but received: ${y.rank}`);if(y.dataType!==r)throw new Error(`Expected zarr array at ${JSON.stringify(v.url)} to have data type ${I[r]}, but received: ${I[y.dataType]}`)}const l=new Float64Array(a),c=new Float64Array(a),d=t.scales[0],u=s[0];for(let g=0;g<a;++g){const v=l[g]=d.transform[(a+1)*a+g];c[g]=v+u.shape[g]}const h=dn({lowerBounds:l,upperBounds:c}),{coordinateSpace:f}=t;return{coordinateSpace:ke({names:f.names,units:f.units,scales:f.scales,boundingBoxes:[h]}),dataType:r,scales:t.scales.map((g,v)=>{const y=s[v];return{url:g.url,transform:g.transform,metadata:y}})}}async function nl(i,e,t,n){if(n.zarrVersion===2){const[o,a]=await Promise.all([Vu(i,e,`${t}/.zarray`),Vu(i,e,`${t}/.zattrs`)]);return o===void 0?a===void 0||n.expectedNodeType==="array"?void 0:{zarrVersion:2,nodeType:"group",userAttributes:(0,p.Rf)(a)}:n.expectedNodeType==="group"?void 0:yM(o,a??{},n.explicitDimensionSeparator)}if(n.zarrVersion===3){const o=await Vu(i,e,`${t}/zarr.json`);if(o===void 0)return;if(n.explicitDimensionSeparator!==void 0)throw new Error("dimension_separator query parameter not supported for zarr v3");return vM(o,n.expectedNodeType)}const[s,r]=await Promise.all([nl(i,e,t,{...n,zarrVersion:2}),nl(i,e,t,{...n,zarrVersion:3})]);if(s!==void 0&&r!==void 0)throw new Error("Both zarr v2 and v3 metadata found");return s??r}class _u extends Ut{constructor(e=void 0){super(),this.zarrVersion=e}get description(){return`Zarr${this.zarrVersion===void 0?"":` v${this.zarrVersion}`} data source`}get(e){let[,t,n]=e.providerUrl.match(/([^?]*)(?:\?(.*))?$/);const s=(0,p.bL)(n||"");(0,p.Rf)(s);const r=(0,p.MM)(s,"dimension_separator",Nu);return t.endsWith("/")&&(t=t.substring(0,t.length-1)),e.chunkManager.memoize.getUncounted({type:"zarr:MultiscaleVolumeChunkSource",providerUrl:t,dimensionSeparator:r},async()=>{const{url:o,credentialsProvider:a}=bn(t,e.credentialsManager),l=await nl(e.chunkManager,a,o,{zarrVersion:this.zarrVersion,explicitDimensionSeparator:r});if(l===void 0)throw new Error("No zarr metadata found");let c;if(l.nodeType==="group"){const u=kM(o,l.userAttributes);if(u===void 0)throw new Error("Neithre array nor OME multiscale metadata found");c=await OM(e.chunkManager,a,u,{zarrVersion:l.zarrVersion,explicitDimensionSeparator:r})}else c=NM(o,l);const d=new PM(e.chunkManager,a,c);return{modelTransform:yt(d.modelSpace),subsources:[{id:"default",default:!0,url:void 0,subsource:{volume:d}},{id:"bounds",default:!0,url:void 0,subsource:{staticAnnotations:cn(d.modelSpace.bounds)}}]}})}async completeUrl(e){const[,,t]=e.providerUrl.match(/([^?]*)(?:\?(.*))?$/);return t!==void 0?li(e.providerUrl.length-t.length,await cg(t,AM)):await Ki(e.credentialsManager,e.providerUrl,e.cancellationToken)}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Nt("zarr",()=>new _u),Nt("zarr2",()=>new _u(2)),Nt("zarr3",()=>new _u(3));var il=G(9063);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Bu(i){class e extends i{constructor(...n){super(...n);const s=n[1],r=this.dataSource=this.registerDisposer(s.dataSource.addRef());this.generation=s.generation;const o=s.parameters.key;r.registerSource(o,this)}static encodeOptions(n){const s=super.encodeOptions(n);return s.dataSource=St(n.dataSource),s}}return e}class VM extends Bu(Ke(Mn,il.jj)){}class S0 extends Bu(Ke(pi,il.Ve)){}function b0(i,e,t,n,s,r){const o=i.length,a=new Float32Array(o);a.fill(1);const l=[a.slice()];let c=1;const d=e.length;if(d===0)return l;for(;!(l.length>=s||c>=n||a.every((m,g)=>i[g]/m<=r));){let u=e[0];const h=m=>a[m]*t[m];for(let m=1;m<d;++m){const g=e[m];h(g)<h(u)&&(u=g)}a[u]*=2,c*=2;const f=h(u);for(let m=0;m<d&&c<n;++m){const g=e[m];if(g===u)continue;const v=h(g);Math.abs(v-f)>Math.abs(v*2-f)&&(a[g]*=2,c*=2)}l.push(new Float32Array(a))}return l}function w0(i){(0,p.Rf)(i);const e={...(0,p.cQ)(i,"coordinateSpace",Ei),valid:!0},{rank:t}=e;e.coordinateArrays.forEach(r=>{r!==void 0&&(r.explicit=!1)});const n=we.D_(new Float32Array((t+1)*(t+1)),t+1,t+1),s=(0,p.cQ)(i,"voxelOffset",r=>(0,p.Xu)(new Float64Array(t),r,p.zo));for(let r=0;r<t;++r)n[(t+1)*t+r]=s[r];return{subsourceToModelTransform:n,baseModelSpace:e,voxelOffset:s}}class _M extends Ht{constructor(e,t,n,s){super(t),this.dataSource=e,this.key=n,this.response=s;const{baseModelSpace:r,subsourceToModelTransform:o,voxelOffset:a}=w0(s);this.dataType=(0,p.cQ)(s,"dataType",h=>(0,p.sl)(h,I)),this.volumeType=(0,p.cQ)(s,"volumeType",h=>(0,p.sl)(h,gt)),this.encoding=(0,p.cQ)(s,"encoding",h=>(0,p.sl)(h,il.r7));const l=r.rank;this.subsourceToModelTransform=o;const c=(0,p.cQ)(s,"shape",h=>(0,p.Xu)(new Float32Array(l),h,p.We));this.shape=c,this.maxDownsampling=(0,p.cQ)(s,"maxDownsampling",h=>h===null?Number.POSITIVE_INFINITY:(0,p.bX)(h)),this.maxDownsampledSize=(0,p.cQ)(s,"maxDownsampledSize",h=>h===null?Number.POSITIVE_INFINITY:(0,p.bX)(h)),this.maxDownsamplingScales=(0,p.cQ)(s,"maxDownsamplingScales",h=>h===null?Number.POSITIVE_INFINITY:(0,p.bX)(h)),this.downsamplingLayout=(0,p.cQ)(s,"downsamplingLayout",h=>h==="2d"?Vi.FLAT:Vi.ISOTROPIC),this.chunkLayoutPreference=(0,p.cQ)(s,"chunkLayout",h=>(0,p.sl)(h,Vi));const d={lowerBounds:a,upperBounds:Ll(new Float64Array(l),a,c)},u=ke({rank:l,names:r.names,scales:r.scales,units:r.units,boundingBoxes:[dn(d)],coordinateArrays:r.coordinateArrays});this.modelSpace=u,this.generation=(0,p.cQ)(s,"generation",h=>h),this.maxVoxelsPerChunkLog2=(0,p.MM)(s,"maxVoxelsPerChunkLog2",p.We,Wf)}get rank(){return this.modelSpace.rank}getSources(e){const t=[],{rank:n,volumeType:s,dataType:r,shape:o,encoding:a}=this,l=new Float32Array(n),{multiscaleToViewTransform:c,modelChannelDimensionIndices:d,displayRank:u}=e;for(let g=0;g<n;++g){let v=0;for(let y=0;y<u;++y){const S=c[g*u+y];v+=S*S}v!==0&&t.push(g),l[g]=Math.sqrt(v)}const h=(g,v,y)=>{const S=new Float32Array((n+1)**2);S[S.length-1]=1;for(let C=0;C<n;++C)S[(n+2)*C]=g[C];const x=new Float32Array(n),b=new Float32Array(n);for(let C=0;C<n;++C)x[C]=Math.ceil(o[C]/g[C]),b[C]=o[C]/g[C];const E=new Uint32Array(n);E.fill(1);for(const C of v)E[C]=4294967295;for(const C of d)E[C]=4294967295;return gi({chunkToMultiscaleTransform:S,rank:n,dataType:r,volumeType:s,maxBlockSize:E,upperVoxelBound:x,volumeSourceOptions:e,chunkLayoutPreference:y}).map(C=>({chunkSource:this.chunkManager.getChunkSource(VM,{spec:C,dataSource:this.dataSource,generation:this.generation,parameters:{baseUrl:window.location.href,key:this.key,scaleKey:g.join(),encoding:a}}),chunkToMultiscaleTransform:S,upperClipBound:b}))},f=g=>b0(this.shape,g,l,this.maxDownsampling,this.maxDownsamplingScales,this.maxDownsampledSize).map(v=>h(v,g,Vi.ISOTROPIC)[0]),{downsamplingLayout:m}=this;return m===Vi.FLAT?[f([t[0],t[1]]),f([t[0],t[2]]),f([t[1],t[2]])]:(0,z.RO)(b0(this.shape,t,l,this.maxDownsampling,this.maxDownsamplingScales,this.maxDownsampledSize).map(g=>h(g,t,this.chunkLayoutPreference)))}getMeshSource(){const{skeletonVertexAttributes:e}=this;return e!==void 0?this.chunkManager.getChunkSource(C0,{dataSource:this.dataSource,generation:this.generation,parameters:{baseUrl:window.location.href,key:this.key,vertexAttributes:e}}):this.chunkManager.getChunkSource(S0,{dataSource:this.dataSource,generation:this.generation,parameters:{baseUrl:window.location.href,key:this.key}})}}class C0 extends Bu(Ke(Br,il.NV)){get vertexAttributes(){return this.parameters.vertexAttributes}}function BM(i){return(0,p.Rf)(i),{dataType:(0,p.cQ)(i,"dataType",e=>(0,p.sl)(e,I)),numComponents:(0,p.cQ)(i,"numComponents",p.We)}}function FM(i,e,t){return e.chunkManager.memoize.getUncounted({type:"python:VolumeDataSource",key:t},async()=>{const n=await(await(0,Me.vd)(new URL(`../../neuroglancer/info/${t}`,window.location.href).href)).json(),s=new _M(i,e.chunkManager,t,n),r={modelTransform:yt(s.modelSpace),subsources:[{id:"default",default:!0,subsource:{volume:s},subsourceToModelSubspaceTransform:s.subsourceToModelTransform},{id:"bounds",default:!0,subsource:{staticAnnotations:cn(s.modelSpace.bounds)}}]};if(s.rank===3&&s.dataType!==I.FLOAT32){const o=new Float32Array(s.subsourceToModelTransform),{scales:a,rank:l}=s.modelSpace;for(let c=0;c<l;++c)o[(l+2)*c]=1/a[c];r.subsources.push({id:"meshes",default:!0,subsourceToModelSubspaceTransform:o,subsource:{mesh:e.chunkManager.getChunkSource(S0,{dataSource:i,generation:s.generation,parameters:{baseUrl:window.location.href,key:t}})}})}return r})}function UM(i,e,t){return e.chunkManager.memoize.getUncounted({type:"python:SkeletonDataSource",key:t},async()=>{const n=await(await(0,Me.vd)(new URL(`../../neuroglancer/skeletoninfo/${t}`,window.location.href).href)).json(),{baseModelSpace:s,subsourceToModelTransform:r}=w0(n),o=(0,p.cQ)(n,"attributes",d=>(0,p.vS)(d,BM)),a=(0,p.cQ)(n,"generation",d=>d),l=e.chunkManager.getChunkSource(C0,{dataSource:i,generation:a,parameters:{baseUrl:window.location.href,key:t,vertexAttributes:o}});return{modelTransform:yt(s),subsources:[{id:"default",subsourceToModelSubspaceTransform:r,default:!0,subsource:{mesh:l}}]}})}class $M extends Ut{constructor(){super(...arguments),this.sources=new Map,this.sourceGenerations=new Map}registerSource(e,t){let n=this.sources.get(e);n===void 0&&(n=new Set,this.sources.set(e,n));const s=this.sourceGenerations.get(e);s!==void 0&&(t.generation=s),n.add(t),t.registerDisposer(()=>{n.delete(t),n.size===0&&this.sources.delete(e)})}setSourceGeneration(e,t){const{sourceGenerations:n}=this;if(n.get(e)===t)return;n.set(e,t);const s=this.sources.get(e);if(s!==void 0)for(const r of s)r.generation!==t&&(r.generation=t,r.invalidateCache())}deleteSourceGeneration(e){this.sourceGenerations.delete(e)}get description(){return"Python-served volume"}get(e){const t=e.providerUrl.match("^(volume|skeleton)/(.*)$");if(t===null)throw new Error(`Invalid Python data source URL: ${JSON.stringify(e.providerUrl)}`);const n=t[2];return t[1]==="volume"?FM(this,e,n):UM(this,e,n)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const x0=!1;function GM(){const i=window.location.pathname.match(/^(.*)\/v\/([^/]+)/);if(i===null)throw new Error("Failed to determine token from URL.");const e=`${window.location.origin}${i[1]}`.replace(/\/+$/,""),t=i[2];return{socket:`${e}/socket/${t}`,action:`${e}/action/${t}`,volumeInfo:`${e}/volume_response/${t}`,events:`${e}/events/${t}`,state:`${e}/state/${t}`,credentials:`${e}/credentials/${t}`}}class E0 extends D.O8{constructor(e,t,n){super(),this.client=e,this.state=t,this.clientGeneration=-1,this.lastServerState="",this.lastServerGeneration="",this.needUpdate=!1,this.updateInProgress=!1,n!==null&&this.registerDisposer(t.changed.add(this.registerCancellable((0,Ls.A)(this.registerCancellable((0,xe.A)(()=>this.handleStateChanged(),0)),n,{leading:!1}))))}async handleStateChanged(){if(this.needUpdate=!0,!this.updateInProgress)try{for(this.updateInProgress=!0;this.needUpdate;){this.needUpdate=!1;const e=this.state.changed.count;if(e===this.clientGeneration)return;const t=ri(this.state).value,n=JSON.stringify(t);if(n===this.lastServerState){this.clientGeneration=e;return}x0&&console.log("Sending update due to mismatch: ",{newStateEncoded:n,lastServerState:this.lastServerState,lastServerGeneration:this.lastServerGeneration});try{const s=await fetch(this.client.urls.state,{method:"POST",body:JSON.stringify({s:t,g:e,pg:this.lastServerGeneration,c:this.client.clientId})});if(s.status===200){const r=await s.json();this.lastServerState=n,this.lastServerGeneration=r.g,this.clientGeneration=e}else if(s.status!==412)throw Me.j$.fromResponse(s)}catch(s){console.log("Failed to send state update",s);return}}}finally{this.updateInProgress=!1}}setServerState(e,t){const n=this.state;n.reset(),n.restoreState(e),this.lastServerState=JSON.stringify(e),this.clientGeneration=n.changed.count,this.lastServerGeneration=t}}class zM extends D.O8{constructor(e,t){super(),this.client=e,this.states=t,this.numConnectionFailures=0,this.status=this.registerDisposer(new Se(!0)),this.waitingToReconnect=-1,this.connect()}disposed(){this.eventSource?.close(),this.waitingToReconnect!==-1&&(clearInterval(this.waitingToReconnect),this.waitingToReconnect=-1)}connect(){this.status.setText("Connecting to Python server"),this.status.setVisible(!0);const e=new URL(this.client.urls.events);e.searchParams.set("c",this.client.clientId);for(const[n,s]of this.states)e.searchParams.set(`g${n}`,s.lastServerGeneration);const t=this.eventSource=new EventSource(e.toString());t.onmessage=n=>{const s=JSON.parse(n.data);x0&&console.log("got message",s);const r=s.g,o=s.k,a=s.s,l=this.states.get(o);if(l===void 0){console.log("unexpected state update for key: ",o);return}l.setServerState(a,r)},t.onerror=()=>{console.log("python state event source disconnected"),t.close(),this.eventSource=void 0;const n=Math.min(3e4,100*2**Math.min(20,this.numConnectionFailures)),s=Date.now()+n;++this.numConnectionFailures,this.status.setVisible(!0);const r=o=>{this.status.setText(`Disconnected from Python server.  Retrying in ${Math.ceil(o/1e3)} seconds.`)};this.waitingToReconnect=window.setInterval(()=>{const o=s-Date.now();o<0?(window.clearInterval(this.waitingToReconnect),this.waitingToReconnect=-1,this.connect()):r(o)},1e3),r(n)},t.onopen=()=>{this.status.setVisible(!1),console.log("python state event source connected"),this.numConnectionFailures=0}}}class WM{constructor(){this.urls=GM(),this.clientId=it()}sendActionNotification(e,t){fetch(this.urls.action,{method:"POST",body:JSON.stringify({action:e,state:t})})}sendVolumeInfoNotification(e,t){fetch(`${this.urls.volumeInfo}/${e}/info`,{method:"POST",body:JSON.stringify(t)})}sendVolumeChunkNotification(e,t){const{data:n,...s}=t;fetch(`${this.urls.volumeInfo}/${e}/chunk?p=${encodeURIComponent(JSON.stringify(s))}`,{method:"POST",body:n})}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class HM extends Xa{constructor(e,t,n){super(),this.client=e,this.key=t,this.parameters=n,this.get=Ru(async s=>{const o=await(await(0,Me.vd)(this.client.urls.credentials,{method:"POST",body:JSON.stringify({key:this.key,parameters:this.parameters,invalid:s?.generation})})).json();(0,p.Rf)(o);const a=(0,p.cQ)(o,"generation",p.bX),l=o.credentials;return{generation:a,credentials:l}})}}class JM extends IA{constructor(e){super(e,{accessToken:"",tokenType:""})}}class jM{constructor(e){this.client=e,this.memoize=new Tc.d}getCredentialsProvider(e,t){t===void 0&&(t=null);const n=(0,p.JB)({key:e,parameters:t});return this.memoize.get(n,()=>{const s=new HM(this.client,e,t);return e==="gcs"?new JM(s):s})}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sl{constructor(){this.eventActionMap=new Pe,this.changed=new j.IY}reset(){this.eventActionMap.clear(),this.changed.dispatch()}restoreState(e){(0,p.Rf)(e);const{eventActionMap:t}=this;for(const n of Object.keys(e)){const s=(0,p.zr)(e[n]);t.set(n,s)}this.changed.dispatch()}toJSON(){const e={};for(const[t,n]of this.eventActionMap.bindings)e[t]=n.action;return e}}var YM=G(9580);/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Qr(i,e=i.value){i.style.minWidth=e.length+1+"ch"}const T0="neuroglancer-coordinate-space-transform-singleton";function D0(i,e,t){let n;t&&(i+=.5,e+=.5),i===Number.NEGATIVE_INFINITY?n="(-\u221E,":n=`[${Math.floor(i)},`;let s;return e===Number.POSITIVE_INFINITY?s="+\u221E)":s=`${Math.floor(e)})`,{lower:n,upper:s}}const I0=Pe.fromObject({arrowup:{action:"move-up"},arrowdown:{action:"move-down"},arrowleft:{action:"move-left",preventDefault:!1},arrowright:{action:"move-right",preventDefault:!1},enter:{action:"commit"},escape:{action:"cancel"}});function R0(){const i=document.createElement("div"),e=document.createElement("input");i.classList.add("neuroglancer-coordinate-space-transform-scale-container"),e.spellcheck=!1,e.autocomplete="off",e.size=1,e.classList.add("neuroglancer-coordinate-space-transform-scale"),i.appendChild(e);const t=document.createElement("div"),n=document.createElement("span");n.innerHTML=YM,t.appendChild(n);const s=document.createTextNode("");return t.appendChild(s),t.classList.add("neuroglancer-coordinate-space-transform-scale-suggestion"),i.appendChild(t),{cellElement:i,inputElement:e,suggestionElement:t}}function k0(i,e,t,n,s){if(e===void 0||e.scale===t&&e.unit===n)i.style.display="none";else{i.style.display="";const r=Ci(e.scale,e.unit,{elide1:!1});i.lastChild.textContent=r,i.title=`${s}${r}`}}function L0(){const i=document.createElement("input");return i.spellcheck=!1,i.autocomplete="off",i.size=1,i.placeholder=" ",i.classList.add("neuroglancer-coordinate-space-transform-output-name"),i}function P0(i,e,t){const n=i.map(h=>Zs(h.value));if(n.includes(void 0))return!1;const s=Float64Array.from(n,h=>h.scale),r=Array.from(n,h=>h.unit),o=t.value,{scales:a,units:l,rank:c}=o;for(let h=0;h<c;++h)e[h]||(s[h]=a[h],r[h]=l[h]);if((0,z.r1)(a,s)&&(0,z.r1)(l,r))return!1;const d=o.timestamps.map((h,f)=>s[f]===a[f]&&r[f]===l[f]?h:Date.now()),u=ke({valid:o.valid,rank:o.rank,scales:s,units:r,timestamps:d,ids:o.ids,names:o.names,boundingBoxes:o.boundingBoxes,coordinateArrays:o.coordinateArrays});return t.value=u,!0}function A0(i,e,t,n){const s=new Float64Array(i.scales),r=Array.from(i.units);if(s[e]===t&&r[e]===n)return i;const o=Array.from(i.timestamps);return s[e]=t,r[e]=n,o[e]=Date.now(),{...i,scales:s,units:r,timestamps:o}}class QM extends D.O8{constructor(e,t,n){super(),this.transform=e,this.localCombiner=t,this.globalCombiner=n,this.element=document.createElement("div"),this.coefficientContainer=document.createElement("div"),this.translationContainer=document.createElement("div"),this.outputNameContainer=document.createElement("div"),this.outputScaleContainer=document.createElement("div"),this.inputNameContainer=document.createElement("div"),this.inputScaleContainer=document.createElement("div"),this.inputLowerBoundsContainer=document.createElement("div"),this.inputUpperBoundsContainer=document.createElement("div"),this.coefficientElements=[],this.inputNameElements=[],this.outputNameElements=[],this.outputScaleElements=[],this.outputScaleSuggestionElements=[],this.inputScaleSuggestionElements=[],this.inputScaleElements=[],this.inputBoundsElements=[],this.outputBoundsElements=[],this.addSourceDimensionIcon=_e({svg:ka,text:"S"}),this.addOutputDimensionIcon=_e({svg:ka,text:"V"}),this.addOutputDimensionCell=document.createElement("div"),this.addOutputDimensionInput=L0(),this.inputScaleModified=[],this.outputScaleModified=[],this.curSourceRank=-1,this.curRank=-1,this.curTransform=void 0,this.addingSourceDimension=!1,this.resetToIdentityButton=_e({text:"Set to identity",title:"Reset to identity transform",onClick:()=>{const{transform:L}=this,_=L.value.rank;L.transform=(0,we.DA)(Float64Array,_+1)}}),this.resetToDefaultButton=_e({text:"Reset to default",title:"Reset to default input scales, transform, and output dimensions.",onClick:()=>{const{transform:L}=this;if(L.mutableSourceRank)return;const{defaultTransform:_}=L,{outputSpace:R}=_,P=R.ids.map(()=>os());L.value={..._,outputSpace:{...R,ids:P}}}});const{element:s}=this,r=this.registerDisposer(new mn(s,I0));r.allShortcutsAreGlobal=!0,s.classList.add("neuroglancer-coordinate-space-transform-widget"),this.registerDisposer(new fn(s,I0));const o=(0,je.t)(()=>this.updateView());this.registerDisposer(e.changed.add(o));const{coefficientContainer:a,translationContainer:l,outputNameContainer:c,inputNameContainer:d,inputScaleContainer:u,inputLowerBoundsContainer:h,inputUpperBoundsContainer:f,outputScaleContainer:m,addOutputDimensionCell:g,addOutputDimensionIcon:v,addSourceDimensionIcon:y,resetToIdentityButton:S,resetToDefaultButton:x}=this;a.style.display="contents",l.style.display="contents",c.style.display="contents",d.style.display="contents",u.style.display="contents",m.style.display="contents",h.style.display="contents",f.style.display="contents";const b=document.createElement("div");b.classList.add("neuroglancer-coordinate-space-transform-widget-reset-buttons"),S.classList.add("neuroglancer-coordinate-space-transform-widget-reset-to-identity"),x.classList.add("neuroglancer-coordinate-space-transform-widget-reset-to-default"),b.appendChild(S),b.appendChild(x),s.appendChild(b);for(const[L,_]of[["source","Source dimensions"],["output","Output dimensions"],["input-lower","Lower"],["input-upper","Upper"],["input-scale","Scale"],["translation","Translation"]]){const R=document.createElement("div");R.classList.add(`neuroglancer-coordinate-space-transform-${L}-label`),R.classList.add("neuroglancer-coordinate-space-transform-label"),R.textContent=_,s.appendChild(R)}e.mutableSourceRank&&g.appendChild(y),g.appendChild(v),g.classList.add("neuroglancer-coordinate-space-transform-output-extend");const E="Embed in additional output dimension",C="Extend to additional source dimension";v.title=E,y.title=C,g.appendChild(this.addOutputDimensionInput),g.dataset.isActive="false",v.addEventListener("click",()=>{this.addingSourceDimension=!1,this.addOutputDimensionInput.title=E,this.addOutputDimensionCell.dataset.isActive="true",this.addOutputDimensionInput.focus()}),y.addEventListener("click",()=>{this.addingSourceDimension=!0,this.addOutputDimensionInput.title=C,this.addOutputDimensionCell.dataset.isActive="true",this.addOutputDimensionInput.focus()}),this.addOutputDimensionInput.addEventListener("blur",()=>{this.updateAddOutputDimensionCellStyle()}),s.appendChild(a),s.appendChild(c),s.appendChild(d),s.appendChild(u),s.appendChild(m),s.appendChild(h),s.appendChild(f),a.appendChild(l),s.addEventListener("input",L=>{const{target:_}=L;if(_ instanceof HTMLInputElement){Qr(_);let R=this.inputScaleElements.indexOf(_);if(R!==-1){this.inputScaleModified[R]=!0,this.updateScaleValidity(_);return}if(R=this.outputScaleElements.indexOf(_),R!==-1){this.outputScaleModified[R]=!0,this.updateScaleValidity(_);return}if(R=this.outputNameElements.indexOf(_),R!==-1){this.updateOutputNameValidity();return}if(this.coefficientContainer.contains(_)){this.updateCoefficientValidity(_);return}}});const k=(L,_,R)=>{X(s,L,P=>{P.stopPropagation();const V=P.target;if(!(V instanceof HTMLInputElement)||R!==0&&(V.selectionStart!==V.selectionEnd||V.selectionStart!==(R===1?V.value.length:0)))return;const $=this.getElementGridPosition(V);if($===void 0)return;const Q=this.getElementByGridPosition($.row+_,$.col+R);Q!==null&&(Q.focus(),P.preventDefault())})};k("move-up",-1,0),k("move-down",1,0),k("move-left",0,-1),k("move-right",0,1);const T=(L,_)=>{L.addEventListener("focusout",R=>{const{relatedTarget:P}=R;P instanceof Node&&L.contains(P)||_(R)})};T(a,()=>{this.updateModelTransform()||this.updateViewTransformCoefficients()}),T(c,()=>{this.updateModelOutputNames()||this.updateViewOutputNames()}),T(u,()=>{this.updateModelInputScales()||this.updateViewInputScales()}),T(m,()=>{this.updateModelOutputScales()||this.updateViewOutputScales()}),X(s,"cancel",L=>{this.curTransform=void 0,this.updateView(),L.target.blur()}),X(a,"commit",()=>{this.updateModelTransform()}),X(c,"commit",()=>{this.updateModelOutputNames()}),X(u,"commit",()=>{this.updateModelInputScales()}),X(m,"commit",()=>{this.updateModelOutputScales()}),s.addEventListener("focusin",L=>{const{target:_}=L;_ instanceof HTMLInputElement&&_.select()}),this.updateView()}updateWillBeDeletedAttributes(e){const{rank:t}=this.transform.value;e===void 0&&(e=new Array(t),e.fill(!1));const{coefficientElements:n,inputBoundsElements:s,inputScaleElements:r}=this;for(let o=0;o<t;++o){const a=e[o];for(let d=0;d<=t;++d){const u=n[t*d+o],h=d<t&&e[d];u.dataset.willBeDeleted=(a||h).toString()}r[o].dataset.willBeDeleted=a.toString();const{lower:l,upper:c}=s[o];l.dataset.willBeDeleted=a.toString(),c.dataset.willBeDeleted=a.toString()}}updateAddOutputDimensionCellStyle(){const{addOutputDimensionInput:e}=this;this.addOutputDimensionCell.dataset.isActive=(e.value.length!==0||document.activeElement===e).toString()}updateOutputNameValidity(){const{outputNameElements:e}=this,t=e.map(l=>l.value),{value:{sourceRank:n,rank:s},mutableSourceRank:r}=this.transform;if(e.length!==s+1)return;const o=_l(t),a=new Array(s);a.fill(!1);for(let l=0;l<=s;++l){let c=o[l];t[l].length===0&&(r||l>=n)&&(c=!0,a[l]=!0),e[l].dataset.isValid=c.toString()}this.updateWillBeDeletedAttributes(a),this.updateAddOutputDimensionCellStyle()}updateScaleValidity(e){const t=Zs(e.value)!==void 0;e.dataset.isValid=t.toString()}updateCoefficientValidity(e){const t=Number.isFinite(Number(e.value));e.dataset.isValid=t.toString()}getElementGridPosition(e){{const t=this.outputNameElements.indexOf(e);if(t!==-1)return{row:t,col:-2}}{const t=this.inputScaleElements.indexOf(e);if(t!==-1)return{row:-1,col:t}}{const t=this.coefficientElements.indexOf(e),{rank:n}=this.transform.value;if(t!==-1)return{row:t%n,col:Math.floor(t/n)}}{const t=this.outputScaleElements.indexOf(e);if(t!==-1)return{row:t,col:-1}}}getElementByGridPosition(e,t){const{rank:n}=this.transform.value;return e===-1?t<0||t>=n?null:this.inputScaleElements[t]:t===-2?e<0||e>n?null:this.outputNameElements[e]:t===-1?e<0||e>=n?null:this.outputScaleElements[e]:e<0||e>=n||t<0||t>n?null:this.coefficientElements[t*n+e]}dimensionRefCount(e){return(tr(e)?this.localCombiner:this.globalCombiner).dimensionRefCounts.get(e)||0}updateModelInputScales(){return P0(this.inputScaleElements,this.inputScaleModified,this.transform.inputSpace)}updateModelOutputScales(){return P0(this.outputScaleElements,this.outputScaleModified,this.transform.outputSpace)}updateModelOutputNames(){const e=this.outputNameElements.map(S=>S.value),{value:t,mutableSourceRank:n}=this.transform,{outputSpace:s,rank:r,sourceRank:o}=t;if(e.length!==r+1)return;const a=[],l=[],c=e[r].length!==0;let d=o;for(let S=0;S<=r;++S){const x=e[S];if(x.length===0){if(S<o){if(!n)return!1;--d}continue}l.push(x),a.push(S)}if(!oo(l))return!1;const u=s.names;if(!c&&(0,z.r1)(u,l))return!0;let h=t.inputSpace,f=t.outputSpace,m=t.transform;if(c){this.addingSourceDimension&&++d;const S=e[r],x=(tr(S)?this.localCombiner:this.globalCombiner).combined.value,b=x.names.indexOf(S);let E,C;b!==-1?(E=x.units[b],C=x.scales[b]):(E="",C=1);const k=h.boundingBoxes.map(T=>Mh(T,r,r+1));this.addingSourceDimension||k.push(Ah(r+1,r)),h=ke({valid:h.valid,rank:r+1,names:[...h.names,""],ids:[...h.ids,os()],timestamps:[...h.timestamps,Date.now()],scales:Float64Array.from([...h.scales,C]),units:[...h.units,E],boundingBoxes:k,coordinateArrays:[...h.coordinateArrays,void 0]}),f=ke({valid:s.valid,rank:r+1,names:[...s.names,S],ids:[...s.ids,os()],timestamps:[...s.timestamps,Date.now()],scales:Float64Array.from([...s.scales,C]),units:[...s.units,E],coordinateArrays:[...s.coordinateArrays,void 0]}),m=(0,we.Aw)(new Float64Array((r+2)**2),r+1,m,r)}m=Fh(Float64Array,m,h.rank,a,a),h=Ul(h,a),f=Ul(f,a);const g=f.ids.map((S,x)=>{const b=a[x];if(b===r)return S;const E=l[x],C=u[b];return E===C||this.dimensionRefCount(C)===1&&this.dimensionRefCount(E)===(u.includes(E)?1:0)?S:os()}),v=f.timestamps.map((S,x)=>{const b=a[x];return b===r||l[x]===u[b]?S:Date.now()});f={...f,names:l,ids:g,timestamps:v};const y={rank:f.rank,sourceRank:d,outputSpace:f,inputSpace:h,transform:m};return this.transform.value=y,!0}updateModelTransform(){const e=this.coefficientElements,{rank:t}=this.transform.value,n=new Float64Array((t+1)**2);n[n.length-1]=1;for(let s=0;s<t;++s)for(let r=0;r<=t;++r){const o=e[r*t+s],a=parseFloat(o.value);if(!Number.isFinite(a))return!1;n[r*(t+1)+s]=a}return this.transform.transform=n,!0}updateViewOutputNames(){const{transform:{value:{outputSpace:e,rank:t}}}=this;if(t!==this.curRank)return;const{outputNameElements:n}=this,{names:s}=e;for(let r=0;r<t;++r){const o=n[r];o.value=s[r],o.dataset.isValid="true",Qr(o)}n[t].value="",this.updateWillBeDeletedAttributes()}updateViewTransformCoefficients(){const{transform:{value:{transform:e,rank:t}}}=this,{coefficientElements:n}=this;for(let s=0;s<t;++s)for(let r=0;r<=t;++r){const o=n[r*t+s];o.value=e[r*(t+1)+s].toString(),o.dataset.isValid="true",Qr(o)}}ensureViewRankUpdated(){const e=this.transform.value,{rank:t}=e,n=e.sourceRank;if(this.curSourceRank===n&&this.curRank===t)return;const{inputBoundsElements:s,inputNameElements:r,inputScaleElements:o}=this,{element:a,coefficientElements:l,outputNameElements:c,outputScaleElements:d,outputScaleSuggestionElements:u,inputScaleSuggestionElements:h,outputBoundsElements:f,coefficientContainer:m,translationContainer:g,outputNameContainer:v,inputNameContainer:y,inputScaleContainer:S,inputLowerBoundsContainer:x,inputUpperBoundsContainer:b,outputScaleContainer:E}=this;a.style.gridTemplateColumns=`[outputLabel headerStart] min-content [outputNames] 1fr [outputScales] 1fr [headerEnd] repeat(${Math.max(1,t)+1}, [sourceDim] 1fr)`,a.style.gridTemplateRows=`[sourceLabel headerStart] auto [sourceNames] auto [sourceLower] auto [sourceUpper] auto [sourceScales] auto [headerEnd]repeat(${t+1}, [outputDim] auto)`,Ae(m),Ae(g),m.appendChild(g),Ae(v),Ae(y),Ae(S),Ae(x),Ae(b),Ae(E),r.length=0,o.length=0,s.length=0,d.length=0,u.length=0,h.length=0,l.length=0,c.length=0,f.length=0;for(let C=0;C<t;++C){const k=T=>{T.classList.add("neuroglancer-coordinate-space-transform-input"),C>=n&&T.classList.add(T0)};{const T=document.createElement("div");T.classList.add("neuroglancer-coordinate-space-transform-input-name"),k(T),T.style.gridRowStart="sourceNames",T.style.gridColumnStart=`sourceDim ${C+1}`,y.appendChild(T),r.push(T)}{const{cellElement:T,inputElement:L,suggestionElement:_}=R0();T.classList.add("neuroglancer-coordinate-space-transform-input-scale-container"),k(T),T.style.gridRowStart="sourceScales",T.style.gridColumnStart=`sourceDim ${C+1}`,S.appendChild(T),o.push(L),h.push(_);const R=C;_.addEventListener("click",()=>{const P=Wh(this.transform,R);P!==void 0&&(this.transform.inputSpace.value=A0(this.transform.inputSpace.value,R,P.scale,P.unit))})}{const T=document.createElement("div");k(T),T.classList.add("neuroglancer-coordinate-space-transform-input-bounds"),T.style.gridRowStart="sourceLower",T.style.gridColumnStart=`sourceDim ${C+1}`,x.appendChild(T);const L=document.createElement("div");k(L),L.classList.add("neuroglancer-coordinate-space-transform-input-bounds"),L.style.gridRowStart="sourceUpper",L.style.gridColumnStart=`sourceDim ${C+1}`,b.appendChild(L),s.push({lower:T,upper:L})}}for(let C=0;C<t;++C){for(let k=0;k<=t;++k){const T=document.createElement("input");T.classList.add("neuroglancer-coordinate-space-transform-coeff"),T.spellcheck=!1,T.autocomplete="off",T.size=1,T.style.gridRowStart=`outputDim ${C+1}`,T.placeholder=" ",T.style.gridColumnStart=`sourceDim ${k+1}`,l[k*t+C]=T,k===t?T.classList.add("neuroglancer-coordinate-space-transform-translation-coeff"):k===n&&T.classList.add(T0),(k===t?g:m).appendChild(T)}{const{cellElement:k,suggestionElement:T,inputElement:L}=R0();k.classList.add("neuroglancer-coordinate-space-transform-output-scale-container"),k.style.gridRowStart=`outputDim ${C+1}`,k.style.gridColumnStart="outputScales";const _=C;T.addEventListener("click",()=>{const{value:R}=this.transform,P=zh(R,_);P!==void 0&&(this.transform.outputSpace.value=A0(R.outputSpace,_,P.scale,P.unit))}),u.push(T),E.appendChild(k),d.push(L)}{const k=document.createElement("div");k.classList.add("neuroglancer-coordinate-space-transform-output-name-container"),k.style.gridRowStart=`outputDim ${C+1}`,k.style.gridColumnStart="outputNames";const T=L0();T.title="Rebind to a different dimension",C>=n?T.title+=", or delete to remove singleton dimension":this.transform.mutableSourceRank&&(T.title+=", or delete to remove source dimension"),T.title+=".  Names ending in ' or ^ indicate dimensions local to the layer; names ending in ^ indicate channel dimensions (image layers only).",c.push(T),v.appendChild(k),k.appendChild(T);const L=document.createElement("div");L.classList.add("neuroglancer-coordinate-space-transform-output-bounds"),k.appendChild(L);const _=document.createElement("div");_.classList.add("neuroglancer-coordinate-space-transform-output-bounds"),k.appendChild(_),f.push({lower:L,upper:_}),k.addEventListener("mousedown",R=>{R.target!==T&&(T.focus(),R.preventDefault())})}}c.push(this.addOutputDimensionInput),this.addOutputDimensionInput.value="",v.appendChild(this.addOutputDimensionCell),this.curSourceRank=n,this.curRank=t}updateViewInputScales(){this.ensureViewRankUpdated(),this.inputScaleModified.length=0;const{inputSpace:e,rank:t,sourceRank:n}=this.transform.value,{inputBoundsElements:s,inputNameElements:r,inputScaleElements:o,inputScaleSuggestionElements:a}=this,{names:l,scales:c,units:d,bounds:{lowerBounds:u,upperBounds:h,voxelCenterAtIntegerCoordinates:f}}=e;for(let m=0;m<t;++m){const g=o[m],v=c[m],y=d[m];g.value=Ci(v,y,{elide1:!1}),g.dataset.isValid="true",Qr(g);let S;if(m<n){let C=l[m];C||(C=`${m}`),r[m].textContent=C,S=`source dimension ${C}`,g.title=`Override scale of ${S}`}else S="singleton dimension",g.title=`Set extent of ${S}`;const{lower:x,upper:b}=D0(u[m],h[m],f[m]),E=s[m];E.lower.textContent=x,E.lower.title=`Lower bound of ${S}`,E.upper.title=`Upper bound of ${S}`,E.upper.textContent=b,k0(a[m],Wh(this.transform,m),v,y,`Revert scale of ${S} to `)}}updateViewOutputScales(){const{value:e}=this.transform,{rank:t,names:n,units:s,scales:r,bounds:{lowerBounds:o,upperBounds:a,voxelCenterAtIntegerCoordinates:l}}=e.outputSpace,{outputScaleElements:c,outputBoundsElements:d,outputScaleSuggestionElements:u}=this;for(let h=0;h<t;++h){const f=c[h],m=r[h],g=s[h];f.value=Ci(m,g,{elide1:!1}),Qr(f);const v=n[h];f.dataset.isValid="true";const y=`Change coordinates of ${tr(v)?"local":"global"} dimension ${v}`;f.title=`${y} (does not rescale the source)`;const{lower:S,upper:x}=D0(o[h],a[h],l[h]),b=d[h];b.lower.textContent=S,b.upper.textContent=x,k0(u[h],zh(e,h),m,g,`${y} to inferred scale of `)}}updateResetButtonVisibility(e=!1,t=!1){const{transform:{value:n,mutableSourceRank:s,defaultTransform:r}}=this,{rank:o}=n;this.resetToIdentityButton.style.visibility=e||!(0,we.Lk)(n.transform,o+1,o+1)?"visible":"hidden",this.resetToDefaultButton.style.visibility=!s&&(e||t||!dw(r,n))?"visible":"hidden"}updateView(){const e=this.transform.value;this.curTransform!==e&&(this.curTransform=e,this.ensureViewRankUpdated(),this.updateViewInputScales(),this.updateViewOutputNames(),this.updateViewTransformCoefficients(),this.updateViewOutputScales(),this.updateAddOutputDimensionCellStyle(),this.updateResetButtonVisibility())}disposed(){lt(this.element),super.disposed()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function qM(i,e,{horizontal:t=!1,vertical:n=!0,topMargin:s=6,bottomMargin:r=6,leftMargin:o=6,rightMargin:a=6,maxHeight:l=!0,maxWidth:c=!0}={}){const d=e.getBoundingClientRect();if(t){const u=i.ownerDocument.documentElement.clientWidth,h=d.right,f=u-d.left;h>f?(i.style.left="",i.style.right=`${u-d.right}px`,c&&(i.style.maxWidth=h-o+"px")):(i.style.right="",i.style.left=`${d.left}px`,c&&(i.style.maxWidth=f-a+"px"))}if(n){const u=i.ownerDocument.documentElement.clientHeight,h=d.top-s,f=u-d.bottom-r;i.style.left=`${d.left}px`,i.style.width=`${d.width}px`,h>f*3?(i.style.top="",i.style.bottom=`${u-d.top}px`,l&&(i.style.maxHeight=h+"px")):(i.style.top=`${d.bottom}px`,i.style.bottom="",l&&(i.style.maxHeight=f+"px"))}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function KM(i){const e=i[Symbol.iterator](),{value:t,done:n}=e.next();if(n)return"";let s=t.length;for(;s>0;){const{value:r,done:o}=e.next();if(o)break;let a=0;for(;a<s&&t.charCodeAt(a)===r.charCodeAt(a);++a);s=a}return t.substring(0,s)}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Fu="neuroglancer-multiline-autocomplete-completion-active",XM=!1;function ZM(i){const e=document.createElement("div");return e.textContent=i.value,e}function*M0(i){for(;i.length>0;){const e=i.match(/[:/_]+/);if(e===null){yield i;return}const t=e.index+e[0].length;yield i.substring(0,t),i=i.substring(t)}}function eN(i){const e=document.createElement("div");e.className="neuroglancer-multiline-autocomplete-completion-with-description",e.textContent=i.value;const t=document.createElement("div");return t.className="neuroglancer-multiline-autocomplete-completion-description",t.textContent=i.description||"",e.appendChild(t),e}const tN=Pe.fromObject({arrowdown:{action:"cycle-next-active-completion"},arrowup:{action:"cycle-prev-active-completion"},home:{action:"home"},end:{action:"end"},tab:{action:"choose-active-completion-or-prefix",preventDefault:!1},enter:{action:"commit"},escape:{action:"cancel",preventDefault:!1,stopPropagation:!1}}),nN=200;class iN extends D.O8{constructor(e){super(),this.element=document.createElement("div"),this.inputElement=document.createElement("span"),this.hintElement=document.createElement("span"),this.completionsVirtualList=void 0,this.onCommit=new j.HN,this.onInput=new j.HN,this.prevInputValue="",this.completionsVisible=!1,this.activeCompletionPromise=null,this.activeCompletionCancellationToken=void 0,this.hasFocus=!1,this.completionResult=null,this.dropdownContentsStale=!0,this.hasResultForDropdown=!1,this.commonPrefix="",this.completionDisabled=-1,this.activeIndex=-1,this.dropdownStyleStale=!0,this.resizeHandler=()=>{this.completionsVisible&&this.updateDropdownStyle()},this.resizeObserver=new ResizeObserver(this.resizeHandler),this.debouncedUpdateHintState=this.registerCancellable((0,xe.A)(()=>this.updateHintState(),0)),this.completer=e.completer;const{delay:t=nN}=e,n=this.scheduleUpdateCompletions=(0,xe.A)(()=>{const l=this.activeCompletionCancellationToken=new at.Qi,c=this.activeCompletionPromise=this.completer(this.value,l);c!==null&&c.then(d=>{this.activeCompletionPromise===c&&(this.setCompletions(d),this.activeCompletionPromise=null)})},t);this.registerDisposer(()=>{n.cancel()});const{element:s,inputElement:r,hintElement:o}=this;s.classList.add("neuroglancer-multiline-autocomplete"),this.registerEventListener(window,"resize",this.resizeHandler),this.resizeObserver.observe(s),this.registerDisposer(()=>this.resizeObserver.unobserve(r)),r.contentEditable="true",r.spellcheck=!1,s.appendChild(document.createTextNode("\u200B")),s.appendChild(r),s.appendChild(o),r.classList.add("neuroglancer-multiline-autocomplete-input"),o.classList.add("neuroglancer-multiline-autocomplete-hint"),r.addEventListener("input",()=>{this.completionDisabled=-1,this.setValueAndSelection(this.value,this.getSelectionRange()),this.debouncedUpdateHintState()}),r.addEventListener("copy",l=>{const{clipboardData:c}=l;if(c!==null){const d=window.getSelection();d!==null&&!d.isCollapsed&&d.containsNode(r,!0)&&c.setData("text/plain",d.toString())}l.preventDefault(),l.stopPropagation()}),this.registerEventListener(document,"selectionchange",()=>{const l=this.getSelectionRange(),{completionDisabled:c}=this;l!==void 0&&l.begin===c&&l.end===c||(this.completionDisabled=-1,this.debouncedUpdateHintState())}),this.setValueAndSelection(""),this.updateHintState(),s.addEventListener("pointerdown",l=>{const{target:c}=l;if(c instanceof Node){if(r.contains(c))return;const{completionsVirtualList:d}=this;if(d?.element.contains(c))return}r===document.activeElement&&(this.moveCaretToEndOfInput(),l.stopPropagation(),l.preventDefault())}),s.addEventListener("click",()=>{r.focus()}),this.registerEventListener(this.inputElement,"focus",()=>{if(!this.hasFocus){this.hasFocus=!0,this.dropdownStyleStale=!0,this.updateDropdown();const l=document.createRange(),{childNodes:c}=r;l.setStart(r,0),c.length===0?l.setEnd(r,0):l.setEndAfter(c[c.length-1]);const d=window.getSelection();d!==null&&(d.removeAllRanges(),d.addRange(l)),this.debouncedUpdateHintState()}}),this.registerEventListener(this.inputElement,"blur",()=>{if(this.hasFocus){if(XM)return;this.hasFocus=!1,this.updateDropdown()}this.debouncedUpdateHintState();const l=window.getSelection();l!==null&&l.containsNode(this.inputElement,!0)&&l.removeAllRanges(),this.onCommit.dispatch(this.value,!1)}),this.registerEventListener(window,"resize",()=>{this.dropdownStyleStale=!0}),this.registerEventListener(window,"scroll",()=>{this.dropdownStyleStale=!0});const a=this.registerDisposer(new mn(r,tN));a.allShortcutsAreGlobal=!0,X(r,"cycle-next-active-completion",()=>{this.cycleActiveCompletion(1)}),X(r,"cycle-prev-active-completion",()=>{this.cycleActiveCompletion(-1)}),X(r,"home",()=>{this.moveCaretToBeginningOfInput()}),X(r,"end",()=>{this.moveCaretToEndOfInput()}),X(r,"choose-active-completion-or-prefix",l=>{this.selectActiveCompletion(!0)&&l.preventDefault()}),X(r,"commit",l=>{if(this.selectActiveCompletion(!1))l.stopPropagation();else{const c=!this.completionsVisible;this.disableCompletion(),this.hideCompletions(),this.onCommit.dispatch(this.value,c)}}),X(r,"cancel",l=>{l.stopPropagation(),this.cancel()&&(l.detail.preventDefault(),l.detail.stopPropagation())})}disableCompletion(){const e=this.getSelectionRange();this.completionDisabled=e!==void 0&&e.end===e.begin?e.end:-1}get placeholder(){return this.inputElement.dataset.placeholder||""}set placeholder(e){this.inputElement.dataset.placeholder=e}getSelectionRange(){const e=window.getSelection();if(e===null||e.rangeCount===0)return;const t=e.getRangeAt(0),{inputElement:n}=this,s=document.createRange();s.setStart(n,0),s.setEnd(t.startContainer,t.startOffset);const r=s.toString().length,o=e.toString().length;return{begin:r,end:r+o}}setValueAndSelection(e,t=void 0){const n=this.completionDisabled!==-1;this.onInput.dispatch(e);const{inputElement:s}=this;Ae(s);let r=0;const o=t!==void 0?document.createRange():void 0;let a=!0;for(const l of M0(e)){a||s.appendChild(document.createElement("wbr")),a=!1;const c=r+l.length,d=document.createTextNode(l);if(s.appendChild(d),o!==void 0){const{begin:u,end:h}=t;u>=r&&u<=c&&o.setStart(d,u-r),h>=r&&h<=c&&o.setEnd(d,h-r)}r=c}if(o!==void 0){a&&(o.setStart(s,0),o.setEnd(s,0));const l=window.getSelection();l!==null&&(l.removeAllRanges(),l.addRange(o))}this.completionDisabled=n&&t!==void 0&&t.end===t.begin?t.end:-1}shouldAttemptCompletion(){const{inputElement:e}=this;if(document.activeElement!==e)return!1;const t=this.getSelectionRange();return t!==void 0&&t.end===t.begin&&t.end!==this.completionDisabled&&t.end===this.value.length}hideCompletions(){this.cancelActiveCompletion(),this.clearCompletions(),this.hintElement.textContent=""}updateHintState(){if(this.debouncedUpdateHintState.cancel(),!this.shouldAttemptCompletion()){this.hideCompletions();return}const{value:e}=this;e!==this.prevInputValue&&(this.hideCompletions(),this.prevInputValue=e,this.scheduleUpdateCompletions())}handleDropdownClick(e){const{completionsVirtualList:t}=this;if(t===void 0)return;const n=t.element;for(let s=e.target;s instanceof HTMLElement&&s!==n;s=s.parentElement){const r=s.dataset.completionIndex;if(r!==void 0){this.selectCompletion(Number(r));break}}}cycleActiveCompletion(e){if(this.completionResult===null)return;let{activeIndex:t}=this;const n=this.completionResult.completions.length;t===-1?e>0?t=0:t=n-1:t=(t+e+n)%n,this.setActiveIndex(t)}shouldShowDropdown(){const{completionResult:e}=this;return e===null||!this.hasFocus?!1:this.hasResultForDropdown}updateDropdownStyle(){const{completionsVirtualList:e,element:t}=this;e!==void 0&&qM(e.element,t,{horizontal:!1}),this.dropdownStyleStale=!1}updateDropdown(){let{completionsVirtualList:e}=this;if(this.shouldShowDropdown()){if(this.dropdownContentsStale){e!==void 0&&e.dispose();const n=this.completionResult,{makeElement:s=ZM}=n;e=this.completionsVirtualList=new Pa({source:{length:n.completions.length,render:r=>{const o=n.completions[r],a=s.call(n,o);return a.classList.add("neuroglancer-multiline-autocomplete-completion"),a.dataset.completionIndex=`${r}`,this.activeIndex===r&&a.classList.add(Fu),a}},selectedIndex:this.activeIndex===-1?void 0:this.activeIndex}),e.element.classList.add("neuroglancer-multiline-autocomplete-dropdown"),e.element.addEventListener("mousedown",r=>{this.inputElement.focus(),r.preventDefault()}),e.element.addEventListener("mouseup",this.handleDropdownClick.bind(this)),this.element.appendChild(e.element),this.dropdownContentsStale=!1}this.dropdownStyleStale&&this.updateDropdownStyle(),this.completionsVisible||(this.completionsVisible=!0);const{activeIndex:t}=this;t!==-1&&this.completionsVirtualList.scrollItemIntoView(t)}else this.completionsVisible&&(e!==void 0&&(e.dispose(),this.completionsVirtualList=void 0,this.dropdownContentsStale=!0),this.completionsVisible=!1)}setCompletions(e){this.clearCompletions();const{completions:t}=e;if(t.length===0)return;const n=this.prevInputValue;if(n!==void 0){if(this.completionResult=e,t.length===1){const s=t[0];e.showSingleResult?this.hasResultForDropdown=!0:s.value.startsWith(n)?this.hasResultForDropdown=!1:this.hasResultForDropdown=!0,e.selectSingleResult?this.setActiveIndex(0):this.setHintValue(this.getCompletedValueByIndex(0))}else{this.hasResultForDropdown=!0;const s=KM(function*(){for(const o of e.completions)yield o.value}()),r=this.getCompletedValue(s);r.startsWith(n)&&(this.commonPrefix=r,this.setHintValue(r))}this.updateDropdown()}}setHintValue(e){const t=this.prevInputValue;if(t===void 0)return;(e===t||!e.startsWith(t))&&(e=""),e=e.substring(t.length);const{hintElement:n}=this;Ae(n);let s=!0;for(const r of M0(e)){s||n.appendChild(document.createElement("wbr")),s=!1;const o=document.createTextNode(r);n.appendChild(o)}}setActiveIndex(e){if(!this.dropdownContentsStale){const{activeIndex:t}=this,{completionsVirtualList:n}=this;if(n!==void 0){if(t!==-1){const s=n.getItemElement(t);s!==void 0&&s.classList.remove(Fu)}if(e!==-1){const s=n.getItemElement(e);s!==void 0&&s.classList.add(Fu),n.scrollItemIntoView(e)}}}e!==-1&&this.setHintValue(this.getCompletedValueByIndex(e)),this.activeIndex=e}getCompletedValueByIndex(e){return this.getCompletedValue(this.completionResult.completions[e].value)}getCompletedValue(e){const t=this.completionResult,n=this.prevInputValue;return n===void 0?"":n.substring(0,t.offset)+e}moveCaretToBeginningOfInput(){const e=document.createRange(),{inputElement:t}=this;e.setStart(t,0),e.setEnd(t,0);const n=window.getSelection();n!==null&&(n.removeAllRanges(),n.addRange(e),this.debouncedUpdateHintState())}moveCaretToEndOfInput(){const e=document.createRange(),{inputElement:t}=this,{childNodes:n}=t,s=n[n.length-1];s===void 0?(e.setStart(t,0),e.setEnd(t,0)):(e.setStartAfter(s),e.setEndAfter(s));const r=window.getSelection();r!==null&&(r.removeAllRanges(),r.addRange(e),this.debouncedUpdateHintState())}selectActiveCompletion(e){let{activeIndex:t}=this;if(t===-1){if(!e)return!1;const{completionResult:s}=this;if(s!==null&&s.completions.length===1)t=0;else{const{commonPrefix:r}=this;return r.length>this.value.length?(this.value=r,this.moveCaretToEndOfInput(),!0):!1}}const n=this.getCompletedValueByIndex(t);return this.value===n?!1:(this.value=n,this.moveCaretToEndOfInput(),!0)}selectCompletion(e){this.value=this.getCompletedValueByIndex(e),this.moveCaretToEndOfInput()}cancel(){return!1}cancelActiveCompletion(){this.prevInputValue=void 0;const e=this.activeCompletionCancellationToken;e!==void 0&&e.cancel(),this.activeCompletionCancellationToken=void 0,this.activeCompletionPromise=null}clearCompletions(){if(this.completionResult!==null){this.activeIndex=-1,this.completionResult=null,this.dropdownContentsStale=!0,this.dropdownStyleStale=!0,this.commonPrefix="";const{completionsVirtualList:e}=this;e!==void 0&&(e.dispose(),this.completionsVirtualList=void 0),this.updateDropdown()}}get value(){return this.inputElement.textContent||""}set value(e){e!==this.value&&(this.completionDisabled=-1,this.setValueAndSelection(e),this.debouncedUpdateHintState())}disposed(){const{completionsVirtualList:e}=this;e!==void 0&&e.dispose(),lt(this.element),this.cancelActiveCompletion(),super.disposed()}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sN extends iN{constructor(e){const{manager:t}=e.source.layer,n=(r,o)=>t.dataSourceProviderRegistry.completeUrl({url:r,chunkManager:t.chunkManager,cancellationToken:o}).then(a=>({completions:a.completions,makeElement:eN,offset:a.offset,showSingleResult:!0}));super({completer:n,delay:0}),this.placeholder="Data source URL",this.dataSourceView=e,this.element.classList.add("neuroglancer-layer-data-source-url-input"),this.dirty=new A.B0(!1);const s=r=>{r!==this.dataSourceView.source.spec.url&&(this.dirty.value=!0)};s(""),this.onInput.add(s)}cancel(){return this.value=this.dataSourceView.source.spec.url,this.dirty.value=!1,this.inputElement.blur(),!0}}class N0 extends D.O8{constructor(e){super(),this.model=e,this.element=document.createElement("ul"),this.generation=-1,this.element.classList.add("neuroglancer-layer-data-sources-source-messages");const t=this.registerCancellable((0,je.t)(()=>this.updateView()));this.registerDisposer(e.changed.add(t)),this.registerDisposer(()=>lt(this.element)),this.updateView()}updateView(){const{model:e}=this,t=e.changed.count;if(t===this.generation)return;this.generation=t;const{element:n}=this;Ae(n);const s=new Set;for(const r of e){const o=`${r.severity} ${r.message}`;if(s.has(o))continue;s.add(o);const a=document.createElement("li");n.appendChild(a),a.classList.add("neuroglancer-message"),a.classList.add(`neuroglancer-message-${xn[r.severity]}`),a.textContent=r.message}}}class rN extends D.O8{constructor(e,t){super(),this.loadedSubsource=t,this.element=document.createElement("div");const{element:n}=this;n.classList.add("neuroglancer-layer-data-source-subsource");const s=document.createElement("label"),r=document.createElement("span"),o=()=>{s.dataset.isActive=(t.activated!==void 0||!t.enabled).toString()};o(),this.registerDisposer(t.isActiveChanged.add(o)),this.registerDisposer(e.enabledSubsourcesChanged.add(o));const a=this.registerDisposer(new Un({get value(){return t.enabled},set value(m){t.enabled=m,e.enableDefaultSubsources=!1,e.enabledSubsourcesChanged.dispatch()},changed:e.enabledSubsourcesChanged}));s.classList.add("neuroglancer-layer-data-sources-info-line"),s.appendChild(a.element);const l=document.createElement("span");l.classList.add("neuroglancer-layer-data-sources-source-id");const{id:c}=t.subsourceEntry;c!=="default"&&(l.textContent=c),s.appendChild(l),r.classList.add("neuroglancer-layer-data-sources-source-type");const d=this.registerDisposer(new N0(this.loadedSubsource.messages));n.appendChild(s),s.appendChild(r),n.appendChild(d.element);let u="";const{subsource:h}=t.subsourceEntry,{volume:f}=h;if(f instanceof Ht)u=`${I[f.dataType].toLowerCase()} volume`;else if(h.mesh instanceof pi)u="meshes (single-res.)";else if(h.mesh instanceof ba)u="meshes (multi-res.)";else if(h.mesh instanceof Br)u="skeletons";else if(h.segmentPropertyMap!==void 0)u="segment property map";else if(h.local!==void 0)switch(h.local){case ks.annotations:u="Local annotations";break;case ks.equivalences:u="local segmentation graph";break}else h.staticAnnotations!==void 0?u="default annotations":h.annotation!==void 0?u="annotations":h.singleMesh!==void 0?u="single mesh":h.segmentationGraph!==void 0&&(u="segmentation graph");r.textContent=u}}class oN extends D.O8{constructor(e){super(),this.source=e,this.element=document.createElement("div");const{element:t}=this,n=document.createElement("label");n.classList.add("neuroglancer-layer-data-sources-source-default"),n.appendChild(this.registerDisposer(new Un({changed:e.enabledSubsourcesChanged,get value(){return e.enableDefaultSubsources},set value(r){if(e.enableDefaultSubsources!==r){if(e.enableDefaultSubsources=r,r)for(const o of e.subsources)o.enabled=o.subsourceEntry.default;e.enabledSubsourcesChanged.dispatch()}}})).element),n.appendChild(document.createTextNode("Enable default subsource set")),n.title="Enable the default set of subsources for this data source.",t.appendChild(n);for(const r of e.subsources)t.appendChild(this.registerDisposer(new rN(e,r)).element);const{transform:s}=e;if(s.mutableSourceRank||s.value.sourceRank!==0){const r=this.registerDisposer(new QM(e.transform,e.layer.localCoordinateSpaceCombiner,e.layer.manager.root.coordinateSpaceCombiner));this.element.appendChild(r.element)}this.registerDisposer(()=>lt(this.element))}}class aN extends D.O8{constructor(e,t){super(),this.tab=e,this.source=t,this.element=document.createElement("div"),this.seenGeneration=0,this.generation=-1;const n=this.urlInput=this.registerDisposer(new sN(this)),s=(o,a)=>{const{source:l}=this,c=l.spec,d=this.source.layer;if(o=d.manager.dataSourceProviderRegistry.normalizeUrl({url:o}),o!==n.value&&(n.disableCompletion(),n.setValueAndSelection(o,{begin:o.length,end:o.length})),n.dirty.value=!1,o&&o===c.url){a&&e.detectedLayerConstructor!==void 0&&O0(l.layer);return}if(d instanceof Hn)try{const u=d.manager.dataSourceProviderRegistry.suggestLayerName(o);Bg(d.managedLayer,u)}catch{}l.spec={...c,url:o}};n.onCommit.add(s);const{element:r}=this;r.classList.add("neuroglancer-layer-data-source"),r.appendChild(n.element),r.appendChild(this.registerDisposer(new N0(t.messages)).element),this.updateView()}updateView(){const e=this.source.changed.count;if(e===this.generation)return;this.generation=e,this.urlInput.value=this.source.spec.url,this.urlInput.dirty.value=!1;const{loadState:t}=this.source;let{loadedView:n}=this;if(n!==void 0){if(n.source===t)return;n.dispose(),n=this.loadedView=void 0}t instanceof Bc&&(n=this.loadedView=new oN(t),this.element.appendChild(n.element))}disposed(){const{loadedView:e}=this;e!==void 0&&e.dispose(),lt(this.element),super.disposed()}}function O0(i){if(i instanceof Hn){const e=i.detectedLayerConstructor;if(e!==void 0)return zc(i.managedLayer,e),!0}return!1}class lN extends Gt{constructor(e){super(),this.layer=e,this.generation=-1,this.sourceViews=new Map,this.addDataSourceIcon=Qv({title:"Add additional data source"}),this.layerTypeDetection=document.createElement("div"),this.layerTypeElement=document.createElement("span"),this.dataSourcesContainer=document.createElement("div"),this.detectedLayerConstructor=void 0;const{element:t,dataSourcesContainer:n}=this;t.classList.add("neuroglancer-layer-data-sources-tab"),n.classList.add("neuroglancer-layer-data-sources-container");const{addDataSourceIcon:s}=this;if(s.style.alignSelf="start",s.addEventListener("click",()=>{const o=this.layer.addDataSource(void 0);this.updateView();const a=this.sourceViews.get(o);a!==void 0&&a.urlInput.inputElement.focus()}),t.appendChild(this.dataSourcesContainer),e instanceof Hn){const{layerTypeDetection:o,layerTypeElement:a}=this;o.style.display="none",a.classList.add("neuroglancer-layer-data-sources-tab-type-detection-type"),o.appendChild(document.createTextNode("Create as ")),o.appendChild(a),o.appendChild(document.createTextNode(" layer")),t.appendChild(o),o.classList.add("neuroglancer-layer-data-sources-tab-type-detection"),o.addEventListener("click",()=>{O0(e)})}const r=this.reRender=(0,je.t)(()=>this.updateView());this.registerDisposer(e.dataSourcesChanged.add(r)),this.registerDisposer(this.visibility.changed.add(r)),this.updateView()}updateLayerTypeDetection(){const e=(()=>{const n=this.layer;if(!(n instanceof Hn))return;const s=n.detectedLayerConstructor;if(s!==void 0){for(const r of this.sourceViews.values())if(r.urlInput.dirty.value)return;return s}})();if(e===this.detectedLayerConstructor)return;const{layerTypeDetection:t}=this;if(this.detectedLayerConstructor=e,e!==void 0){const{layerTypeElement:n}=this;n.textContent=e.type,t.title=`Click here or press enter in the data source URL input box to create as ${e.type} layer`,t.style.display=""}else t.style.display="none"}disposed(){const{sourceViews:e}=this;for(const t of e.values())t.dispose();e.clear(),super.disposed()}updateView(){if(!this.visible)return;const e=this.layer.dataSourcesChanged.count;if(e!==this.generation){this.generation=e;const t=Date.now(),{sourceViews:n}=this,{layer:s}=this;function*r(){let o=!0;const{dataSources:a}=s;for(const l of a){let c=n.get(l);c===void 0&&(c=new aN(this,l),c.registerDisposer(c.urlInput.dirty.changed.add(this.reRender)),n.set(l,c)),c.seenGeneration=t,c.updateView();const d=l.spec.url;a.length===1&&d===""&&setTimeout(()=>{c.urlInput.inputElement.focus()},0),o=l.spec.url.length===0,yield c.element}o||(yield this.addDataSourceIcon)}Zt(this.dataSourcesContainer,r.call(this));for(const[o,a]of n)a.seenGeneration!==t&&(a.dispose(),n.delete(o))}this.updateLayerTypeDetection()}}Eg.push({id:"source",label:"Source",order:-100,getter:i=>new lN(i)});var V0=G(9783),cN=G(8085),dN=G(2027),uN=G(6984);/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const _0=new DA;/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function on(i,e){return t=>{t.style.flex=i,e(t)}}function Y_(i,e){return t=>{Object.assign(t.style,i),e(t)}}function Q_(i,e){return t=>{Object.assign(t,i),e(t)}}function es(i,e){return t=>{t.style.display="flex",t.style.flexDirection=i;for(const n of e){const s=t.ownerDocument.createElement("div");t.appendChild(s),n(s)}}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const hN=w.pB.create();function B0(i,e){const t=w.pB.identity(hN),{globalPosition:n,displayDimensionRenderInfo:{canonicalVoxelFactors:s,displayDimensionIndices:r}}=i;for(let o=0;o<3;++o){const a=r[o];t[12+o]=a===-1?0:n[a],t[5*o]=e/s[o]}return w.pB.multiply(t,i.viewProjectionMat,t),t}class rl extends D.O8{constructor(e){super(),this.gl=e,this.vertexBuffer=this.registerDisposer(At.fromData(e,new Float32Array([0,0,0,1,1,0,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,1,1]),e.ARRAY_BUFFER,e.STATIC_DRAW));const t=.5;this.colorBuffer=this.registerDisposer(At.fromData(e,new Float32Array([1,0,0,t,1,0,0,t,0,1,0,t,0,1,0,t,0,0,1,t,0,0,1,t]),e.ARRAY_BUFFER,e.STATIC_DRAW)),this.trivialColorShader=this.registerDisposer(oC(e))}static get(e){return e.memoize.get("SliceViewPanel:AxesLineHelper",()=>new rl(e))}draw(e,t=!0){const n=this.trivialColorShader,s=this.gl;n.bind(),s.uniformMatrix4fv(n.uniform("uProjectionMatrix"),!1,e);const r=n.attribute("aVertexPosition");this.vertexBuffer.bindToVertexAttrib(r,4);const o=n.attribute("aColor");this.colorBuffer.bindToVertexAttrib(o,4),t&&(s.colorMask(!1,!1,!1,!0),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.colorMask(!0,!0,!0,!0),s.enable(s.BLEND),s.blendFunc(s.ONE_MINUS_DST_ALPHA,s.DST_ALPHA)),s.lineWidth(1),s.drawArrays(s.LINES,0,6),t&&s.disable(s.BLEND),s.disableVertexAttribArray(r),s.disableVertexAttribArray(o)}}var pN=G(4373);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const F0=!1;class U0{constructor(){this.renderLayers=[null],this.pickData=[null],this.values=[0,0,0],this.nextPickID=1}clear(){this.renderLayers.length=1,this.pickData.length=1,this.values.length=3,this.nextPickID=1}registerUint64(e,t,n=1,s=null){return this.register(e,n,t.low,t.high,s)}register(e,t=1,n=0,s=0,r=null){const{renderLayers:o,values:a}=this,l=this.nextPickID;this.nextPickID+=t;const c=o.length;o[c]=e;const d=c*3;return a[d]=l,a[d+1]=n,a[d+2]=s,this.pickData[c]=r,l}setMouseState(e,t){const{renderLayers:n,values:s}=this;let r=0,o=n.length-1;for(;r<o;){const h=Math.ceil(r+(o-r)/2);s[h*3]>t?o=h-1:r=h}const a=e.pickedRenderLayer=n[r],l=r*3,c=e.pickedOffset=t-s[l];F0&&console.log(`Looking up pick ID ${t}: renderLayer`,a,`offset=${c}`);const{pickedValue:d}=e;d.low=s[l+1],d.high=s[l+2],e.pickedAnnotationId=void 0,e.pickedAnnotationLayer=void 0,e.pickedAnnotationBuffer=void 0,e.pickedAnnotationBufferBaseOffset=void 0,e.pickedAnnotationIndex=void 0,e.pickedAnnotationCount=void 0,e.pickedAnnotationType=void 0;const u=this.pickData[r];a!==null&&(F0&&console.log(`Picked value=${d}, offset=${c}, data=${this.pickData[r]}`),a.updateMouseState(e,d,c,u))}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const $0=10,fN=1e3,gN=400,mN=500,vN=Math.PI/20,yN=20,SN=10;function G0(i,e){return Math.sqrt(i*i+e*e)}function z0(i){let[e,t]=i;e.identifier>t.identifier&&([t,e]=[e,t]);const n=e.clientX-t.clientX,s=e.clientY-t.clientY,r=G0(n,s),o=Math.atan2(n,s);return{distance:r,angle:o}}function bN(i,e){const t=Math.PI*2,n=Math.abs(i-e)%t;return Math.min(n,t-n)}class wN extends D.O8{constructor(e,t){super(),this.target=e,this.eventMap=t,this.prevTouches=new Map,this.moved=!1,this.prevAngle=0,this.rotated=!1,this.prevDistance=0,this.pinched=!1,this.prevCenterX=0,this.prevCenterY=0,this.translated=!1,this.startHold=this.registerCancellable((0,Ls.A)((n,s,r,o)=>{const a={event:n,centerX:r,centerY:o};this.dispatch(`touchhold${n.targetTouches.length}`,n,a,s)},fN,{leading:!1,trailing:!0})),this.numPriorTaps=0,this.priorTapNumTouches=0,this.tapStartTime=0,this.tapEndTime=0,this.curTapNumTouches=0,this.registerEventListener(e,"touchstart",n=>{this.handleTouchEvent(n)}),this.registerEventListener(e,"touchmove",n=>{this.handleTouchEvent(n)}),this.registerEventListener(e,"touchend",n=>{this.handleTouchEvent(n)})}dispatch(e,t,n,s=t.eventPhase){tf(e,t,s,n,this.eventMap)}handleTouchEvent(e){if(e.target===this.target)e.preventDefault();else return;const t=new Map,{prevTouches:n,prevEvent:s}=this;let r=0,o=0;for(const h of e.targetTouches)t.set(h.identifier,h),r+=h.clientX,o+=h.clientY;r/=t.size,o/=t.size;for(const[h,f]of n.entries()){const m=t.get(h);if(m===void 0)n.delete(h);else{const g=m.clientX-f.clientX,v=m.clientY-f.clientY;(Math.abs(g)>=$0||Math.abs(v)>=$0)&&(this.moved=!0)}}if(s===void 0||s.targetTouches.length!==t.size||t.size===0){if(this.moved=!1,e.type==="touchstart")this.startHold(e,e.eventPhase,r,o),(s===void 0||s.targetTouches.length===0)&&(this.tapStartTime=Date.now(),this.curTapNumTouches=0),this.curTapNumTouches=Math.max(this.curTapNumTouches,e.targetTouches.length);else{if(e.type==="touchend"){const h=Date.now();if(e.targetTouches.length===0&&h-this.tapStartTime<gN){(this.curTapNumTouches!==this.priorTapNumTouches||h-this.tapEndTime>=mN)&&(this.numPriorTaps=0),++this.numPriorTaps,this.tapEndTime=h,this.priorTapNumTouches=this.curTapNumTouches;const f={event:e,centerX:r,centerY:o};this.dispatch(`touchtap${this.curTapNumTouches}x${this.numPriorTaps}`,e,f)}}this.startHold.cancel()}if(this.prevTouches=t,this.prevEvent=e,this.prevCenterX=r,this.prevCenterY=o,this.translated=!1,t.size===2){const{distance:h,angle:f}=z0(t.values());this.prevDistance=h,this.prevAngle=f,this.rotated=!1,this.pinched=!1}return}if(!this.moved)return;this.tapStartTime=0,this.startHold.cancel(),this.prevTouches=t,this.prevEvent=e;let{prevCenterX:a,prevCenterY:l,translated:c}=this;const d=r-a,u=o-l;if(c===!1&&G0(d,u)>=SN&&(c=this.translated=!0),c===!0&&(d!==0||u!==0)){this.prevCenterX=r,this.prevCenterY=o;const h={event:e,deltaX:d,deltaY:u,centerX:r,centerY:o};this.dispatch(`touchtranslate${t.size}`,e,h)}if(t.size===2){const{distance:h,angle:f}=z0(t.values());let{pinched:m,rotated:g,prevDistance:v,prevAngle:y}=this;m===!1&&Math.abs(h-v)>=yN&&(this.pinched=m=!0);const S=bN(f,y);if(g===!1&&S>=vN&&(this.rotated=g=!0),m===!0&&h!==v){this.prevDistance=h;const x={event:e,distance:h,prevDistance:v,centerX:r,centerY:o};this.dispatch("touchpinch",e,x)}g===!0&&f!==y&&(this.prevAngle=f,this.dispatch("touchrotate",e,{event:e,centerX:r,centerY:o,angle:f,prevAngle:y}))}}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Uu=w.eR.create();class W0{constructor(){this.pickIDs=new U0,this.viewportWidth=0,this.viewportHeight=0,this.invTransform=w.pB.create(),this.frameNumber=-1}}class H0{constructor(){this.buffer=null,this.glWindowX=0,this.glWindowY=0}}const CN=30,bt=5,He=1+bt*2,ol=(()=>{const i=bt**2,e=(s,r)=>(s-bt)**2+(r-bt)**2;let t=new Uint32Array(He*He),n=0;for(let s=0;s<He;++s)for(let r=0;r<He;++r)e(s,r)>i||(t[n++]=r*He+s);return t=t.subarray(0,n),t.sort((s,r)=>{const o=s%He,a=(s-o)/He,l=r%He,c=(r-l)/He;return e(o,a)-e(l,c)}),t})();function J0(i,e,t,n,s,r,o){const a=n-bt,l=s-bt;if(!(a>=0&&l>=0&&a+He<=r&&l+He<=o))for(let c=0;c<He;++c)for(let d=0;d<He;++d){const u=a+d,h=l+c;(u<0||h<0||u>=r||h>=o)&&(i[e+(h*He+u)*t]=0)}}class j0 extends Zh{constructor(e,t,n){super(e,t,n.visibility),this.viewer=n,this.mouseX=-1,this.mouseY=-1,this.pickRequestPending=!1,this.mouseStateForcer=()=>this.blockOnPickRequest(),this.isMovingToMousePosition=!1,this.pickingData=[new W0,new W0],this.pickRequests=[new H0,new H0],this.pickBufferContents=new Float32Array(8*He*He),this.pickTimerId=-1,this.nextPickRequestTime=0,this.pendingPickRequestTimerId=-1,this.pendingPickRequestTimerExpired=()=>{this.pendingPickRequestTimerId=-1,this.pickRequestPending&&this.attemptToIssuePickRequest()},this.isMovingToMousePositionOnPick=!1,this.inputEventMap=n.inputEventMap,t.classList.add("neuroglancer-rendered-data-panel"),t.classList.add("neuroglancer-panel"),t.classList.add("neuroglancer-noselect"),typeof NEUROGLANCER_SHOW_OBJECT_SELECTION_TOOLTIP<"u"&&NEUROGLANCER_SHOW_OBJECT_SELECTION_TOOLTIP===!0&&(t.title="Double click to toggle display of object under mouse pointer.  Control+rightclick to pin/unpin selection."),this.registerDisposer(new Na(t)),this.registerDisposer(new mn(t,this.inputEventMap)),this.registerDisposer(new fn(t,this.inputEventMap,s=>{this.onMousemove(s)})),this.registerDisposer(new wN(t,this.inputEventMap)),this.registerEventListener(t,"mousemove",this.onMousemove.bind(this)),this.registerEventListener(t,"touchstart",this.onTouchstart.bind(this)),this.registerEventListener(t,"mouseleave",()=>this.onMouseout()),this.registerEventListener(t,"mouseover",s=>{s.target!==t&&this.onMouseout()},!0),X(t,"select-position",()=>{this.viewer.selectionDetailsState.select()}),X(t,"snap",()=>{this.navigationState.pose.snap()}),X(t,"zoom-in",()=>{this.context.flagContinuousCameraMotion(),this.navigationState.zoomBy(.5)}),X(t,"zoom-out",()=>{this.context.flagContinuousCameraMotion(),this.navigationState.zoomBy(2)}),X(t,"depth-range-decrease",()=>{this.context.flagContinuousCameraMotion(),this.navigationState.depthRange.value*=.5}),X(t,"depth-range-increase",()=>{this.context.flagContinuousCameraMotion(),this.navigationState.depthRange.value*=2});for(let s=0;s<3;++s){const r=w.p9[s];for(const o of[-1,1]){const a=o<0?"-":"+";X(t,`rotate-relative-${r}${a}`,()=>{this.context.flagContinuousCameraMotion(),this.navigationState.pose.rotateRelative(w.T2[s],o*.1)});const l=w.eR.create();X(t,`${r}${a}`,()=>{this.context.flagContinuousCameraMotion();const{navigationState:c}=this,d=l;d[0]=0,d[1]=0,d[2]=0,d[s]=o,c.pose.translateVoxelsRelative(d)})}}X(t,"zoom-via-wheel",s=>{this.context.flagContinuousCameraMotion();const r=s.detail;this.onMousemove(r,!1),this.zoomByMouse(gs(r))}),X(t,"adjust-depth-range-via-wheel",s=>{this.context.flagContinuousCameraMotion();const r=s.detail;this.navigationState.depthRange.value*=gs(r)}),X(t,"translate-via-mouse-drag",s=>{$t(s.detail,(r,o,a)=>{this.context.flagContinuousCameraMotion(),this.translateByViewportPixels(o,a)})}),X(t,"translate-in-plane-via-touchtranslate",s=>{this.context.flagContinuousCameraMotion();const{detail:r}=s;this.translateByViewportPixels(r.deltaX,r.deltaY)}),X(t,"translate-z-via-touchtranslate",s=>{this.context.flagContinuousCameraMotion();const{detail:r}=s,{navigationState:o}=this,a=Uu;a[0]=0,a[1]=0,a[2]=r.deltaY+r.deltaX,o.pose.translateVoxelsRelative(a)});for(const s of[1,10])X(t,`z+${s}-via-wheel`,r=>{this.context.flagContinuousCameraMotion();const o=r.detail,{navigationState:a}=this,l=Uu,c=o.deltaY!==0?o.deltaY:o.deltaX;l[0]=0,l[1]=0,l[2]=(c>0?-1:1)*s,a.pose.translateVoxelsRelative(l)});X(t,"move-to-mouse-position",()=>{const{mouseState:s}=this.viewer;s.updateUnconditionally()&&(this.navigationState.position.value=s.position)}),X(t,"snap",()=>this.navigationState.pose.snap()),X(t,"move-annotation",s=>{const{mouseState:r}=this.viewer,o=r.pickedAnnotationId,a=r.pickedAnnotationLayer;if(a!==void 0&&o!==void 0){s.stopPropagation();const l=a.source.getReference(o),c=l.value,d=wr(c.type),u=r.pickedOffset,{chunkTransform:{value:h}}=a;if(h.error!==void 0)return;const{layerRank:f}=h,m=new Float32Array(f);d.getRepresentativePoint(m,c,r.pickedOffset);const g=w.Zc.set(w.Zc.create(),0,0);r.updateUnconditionally()&&$t(s.detail,(v,y,S)=>{w.Zc.add(g,g,[y,S]);const x=new Float32Array(f);we.vo(x,h.chunkToLayerTransform,f+1,m,f);const b=Uu,{displayDimensionIndices:E}=this.navigationState.pose.displayDimensions.value;xw(b,x,h.modelTransform,E),this.translateDataPointByViewportPixels(b,b,g[0],g[1]),Ew(x,b,h.modelTransform,E);const C=new Float32Array(f);we.vo(C,h.layerToChunkTransform,f+1,x,f);const k=d.updateViaRepresentativePoint(c,C,u);a.source.update(l,k)},v=>{a.source.commit(l),l.dispose()})}}),X(t,"delete-annotation",()=>{const{mouseState:s}=this.viewer,r=s.pickedAnnotationId,o=s.pickedAnnotationLayer;if(o!==void 0&&!o.source.readonly&&r!==void 0){const a=o.source.getReference(r);try{o.source.delete(a)}finally{a.dispose()}}}),X(t,"zoom-via-touchpinch",s=>{this.context.flagContinuousCameraMotion();const{detail:r}=s;this.handleMouseMove(r.centerX,r.centerY);const o=r.prevDistance/r.distance;o>.1&&o<10&&this.zoomByMouse(o)})}cancelPickRequests(){const{gl:e}=this;for(const t of this.pickRequests){const{sync:n}=t;n!==null&&e.deleteSync(n),t.sync=null}clearTimeout(this.pickTimerId),this.pickTimerId=-1}issuePickRequestInternal(e){const{gl:t}=this;let{buffer:n}=e;n===null?(n=e.buffer=t.createBuffer(),t.bindBuffer(WebGL2RenderingContext.PIXEL_PACK_BUFFER,n),t.bufferData(WebGL2RenderingContext.PIXEL_PACK_BUFFER,32*He*He,WebGL2RenderingContext.STREAM_READ)):t.bindBuffer(WebGL2RenderingContext.PIXEL_PACK_BUFFER,n);const{renderViewport:s}=this,r=this.mouseX-s.visibleLeftFraction*s.logicalWidth,o=s.height-(this.mouseY-s.visibleTopFraction*s.logicalHeight);this.issuePickRequest(r,o),e.sync=t.fenceSync(WebGL2RenderingContext.SYNC_GPU_COMMANDS_COMPLETE,0),e.frameNumber=this.context.frameNumber,e.glWindowX=r,e.glWindowY=o,t.flush(),t.bindBuffer(WebGL2RenderingContext.PIXEL_PACK_BUFFER,null),this.pickTimerId===-1&&this.scheduleCheckForPickRequestCompletion(),this.pickRequestPending=!1;const{pickRequests:a}=this;e!==a[0]&&(a[1]=a[0],a[0]=e),this.nextPickRequestTime=Date.now()+CN}completePickInternal(e){const{gl:t}=this,{pickBufferContents:n}=this;t.bindBuffer(WebGL2RenderingContext.PIXEL_PACK_BUFFER,e.buffer),t.getBufferSubData(WebGL2RenderingContext.PIXEL_PACK_BUFFER,0,n),t.bindBuffer(WebGL2RenderingContext.PIXEL_PACK_BUFFER,null);const{pickingData:s}=this,{frameNumber:r}=e;this.completePickRequest(e.glWindowX,e.glWindowY,n,s[0].frameNumber===r?s[0]:s[1])}scheduleCheckForPickRequestCompletion(){this.pickTimerId=window.setTimeout(()=>{this.pickTimerId=-1,this.checkForPickRequestCompletion()},0)}checkForPickRequestCompletion(e=!1,t=!1){let n=this.context.frameNumber,s=-1;e&&(--n,s=n-1);const{pickRequests:r}=this,{gl:o}=this;let a=!1,l=!1,c;for(const u of r){const{sync:h}=u;if(h===null)continue;const{frameNumber:f}=u;if(!l&&f>=n-1){if(t||o.getSyncParameter(h,WebGL2RenderingContext.SYNC_STATUS)===WebGL2RenderingContext.SIGNALED)this.completePickInternal(u),l=!0;else if(f!==s){a=!0;continue}}o.deleteSync(h),u.sync=null,c=u}const{pickTimerId:d}=this;a&&d===-1?this.scheduleCheckForPickRequestCompletion():!a&&d!==-1&&(window.clearTimeout(d),this.pickTimerId=-1),!e&&c!==void 0&&this.pickRequestPending&&this.canIssuePickRequest()&&this.issuePickRequestInternal(c)}blockOnPickRequest(){this.pickRequestPending&&(this.cancelPickRequests(),this.nextPickRequestTime=0,this.attemptToIssuePickRequest()),this.checkForPickRequestCompletion(!1,!0)}draw(){const{width:e,height:t}=this.renderViewport;this.checkForPickRequestCompletion(!0);const{pickingData:n}=this;n[0]=n[1];const s=this.context.frameNumber,r=n[1];if(r.frameNumber=s,r.viewportWidth=e,r.viewportHeight=t,r.pickIDs.clear(),!this.drawWithPicking(r)){r.frameNumber=-1;return}this.nextPickRequestTime=0,this.mouseX>=0&&this.attemptToIssuePickRequest()}canIssuePickRequest(){const e=Date.now(),{nextPickRequestTime:t,pendingPickRequestTimerId:n}=this;return e<t?(n===-1&&(this.pendingPickRequestTimerId=window.setTimeout(this.pendingPickRequestTimerExpired,t-e)),!1):!0}attemptToIssuePickRequest(){if(!this.canIssuePickRequest())return;const e=this.context.frameNumber,{gl:t}=this,{pickRequests:n}=this;for(const s of n){const{sync:r}=s;if(r!==null)if(s.frameNumber<e-1)t.deleteSync(r);else continue;this.issuePickRequestInternal(s);return}}updateMousePosition(e,t){if(e===this.mouseX&&t===this.mouseY)return;if(this.mouseX=e,this.mouseY=t,e<0){this.pickRequestPending=!1,this.cancelPickRequests();return}const n=this.context.frameNumber,s=this.pickingData[1];s.frameNumber!==n||this.renderViewport.width!==s.viewportWidth||this.renderViewport.height!==s.viewportHeight||(this.pickRequestPending=!0,this.attemptToIssuePickRequest())}onMouseout(){this.updateMousePosition(-1,-1),this.viewer.mouseState.setForcer(void 0)}handleMouseMove(e,t){const{element:n}=this,s=n.getBoundingClientRect(),r=e-(s.left+n.clientLeft),o=t-(s.top+n.clientTop),{mouseState:a}=this.viewer;a.pageX=e+window.scrollX,a.pageY=t+window.scrollY,a.setForcer(this.mouseStateForcer),this.updateMousePosition(r,o)}onMousemove(e,t=!0){const{element:n}=this;t&&e.target!==n||this.handleMouseMove(e.clientX,e.clientY)}onTouchstart(e){const{element:t}=this;if(e.target!==t||e.targetTouches.length!==1)return;const{clientX:n,clientY:s}=e.targetTouches[0];this.handleMouseMove(n,s)}disposed(){const{mouseState:e}=this.viewer;e.removeForcer(this.mouseStateForcer);const{gl:t}=this;this.cancelPickRequests();const{pendingPickRequestTimerId:n}=this;n!==-1&&window.clearTimeout(n);for(const s of this.pickRequests)t.deleteBuffer(s.buffer);super.disposed()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const xN=[1.5,2,3,5,7.5,10],js=[{unit:"km",lengthInNanometers:1e12},{unit:"m",lengthInNanometers:1e9},{unit:"mm",lengthInNanometers:1e6},{unit:"\xB5m",lengthInNanometers:1e3},{unit:"nm",lengthInNanometers:1},{unit:"pm",lengthInNanometers:.001}];function q_(i){const e=js.length;let t=js[e-1];for(let n=0;n<e;++n){const s=js[n];if(i>=s.lengthInNanometers){t=s;break}}return t}function K_(i){const e=js.length;let t=js[e-1];for(let n=0;n<e;++n){const s=js[n];if(i>=s.lengthInNanometers**3){t=s;break}}return t}class EN{constructor(){this.allowedSignificands=xN,this.targetLengthInPixels=0,this.physicalSizePerPixel=0,this.prevPhysicalSizePerPixel=0,this.prevTargetLengthInPixels=0,this.prevPhysicalUnit="\0"}update(){const{physicalSizePerPixel:e,targetLengthInPixels:t}=this;if(this.prevPhysicalSizePerPixel===e&&this.prevTargetLengthInPixels===t&&this.prevPhysicalUnit===this.physicalUnit)return!1;this.prevPhysicalSizePerPixel=e,this.prevTargetLengthInPixels=t,this.prevPhysicalUnit=this.physicalUnit;const n=t*e,s=Math.floor(Math.log10(n)),r=10**s,o=n/r;let a=1;for(const d of this.allowedSignificands)if(Math.abs(d-o)<Math.abs(a-o))a=d;else break;const l=a*r,c=xh(l);return this.lengthInPixels=Math.round(l/e),this.physicalUnit=`${c.prefix}${this.physicalBaseUnit}`,this.physicalLength=a*10**(s-c.exponent),!0}}function TN(i,e,t,n,s){const r=document.createElement("canvas"),o=r.getContext("2d"),a=s.textHeightInPixels*s.scaleFactor,l=`bold ${a}px ${s.fontName}`;o.font=l,o.fillStyle="white";const c=`${n}${i.physicalLength} ${i.physicalUnit}`,d=o.measureText(c),u=Math.max(i.lengthInPixels,d.width),h=s.barHeightInPixels*s.scaleFactor,f=s.barTopMarginInPixels*s.scaleFactor,m=h+f+a,g=s.paddingInPixels*s.scaleFactor,v=m+2*g,y=u+2*g;return r.width=y,r.height=v,o.font=l,o.textAlign="center",o.fillStyle="rgba(0, 0, 0, 0.3)",o.fillRect(0,0,y,v),o.fillStyle="white",o.fillText(c,y/2,v-g-h-f),o.fillRect(g,v-g-h,i.lengthInPixels,h),rC(e,t,r),{width:y,height:v}}class DN extends D.O8{constructor(e,t=new EN){super(),this.gl=e,this.dimensions=t,this.texture=null,this.width=0,this.height=0,this.label="",this.factor=1,this.priorOptions=void 0,this.prevLabel=""}update(e){const{dimensions:t,label:n}=this;let{texture:s}=this;if(!t.update()&&s!==null&&e===this.priorOptions&&n===this.prevLabel)return;s===null&&(s=this.texture=this.gl.createTexture());const{width:r,height:o}=TN(t,this.gl,s,n,e);this.priorOptions=e,this.prevLabel=n,this.width=r,this.height=o}disposed(){this.gl.deleteTexture(this.texture),this.texture=null,super.disposed()}}class Y0 extends D.O8{constructor(e){super(),this.gl=e,this.scaleBarCopyHelper=this.registerDisposer(En.get(this.gl)),this.scaleBars=[];for(let t=0;t<3;++t)this.scaleBars.push(this.registerDisposer(new DN(e)))}draw(e,t,n,s,r){const{scaleBars:o}=this,{displayRank:a,displayDimensionIndices:l,canonicalVoxelFactors:c,globalDimensionNames:d,displayDimensionUnits:u,displayDimensionScales:h}=t,{factors:f}=n,m=Math.min(r.maxWidthFraction*e.logicalWidth,r.maxWidthInPixels*r.scaleFactor);let g=0;for(let x=0;x<a;++x){const b=l[x],E=u[x],C=f[b];let k,T,L;for(k=0;k<g&&(T=o[k],L=T.dimensions,!(L.physicalBaseUnit===E&&T.factor===C));++k);k===g&&(++g,T=o[k],T.label="",L=T.dimensions,T.factor=C,L.physicalBaseUnit=E,L.targetLengthInPixels=m,L.physicalSizePerPixel=h[x]*s/c[x]),T.label+=`${d[b]} `}const{gl:v,scaleBarCopyHelper:y}=this;let S=r.bottomPixelOffset*r.scaleFactor;for(let x=g-1;x>=0;--x){const b=o[x];g===1?b.label="":b.label+=": ",b.update(r),v.viewport(r.leftPixelOffset*r.scaleFactor-e.visibleLeftFraction*e.logicalWidth,S-(1-(e.visibleTopFraction+e.visibleHeightFraction))*e.logicalHeight,b.width,b.height),y.draw(b.texture),S+=b.height+r.marginPixelsBetweenScaleBars*r.scaleFactor}}}const Q0={...{scaleFactor:1,textHeightInPixels:15,barHeightInPixels:8,barTopMarginInPixels:5,fontName:"sans-serif",paddingInPixels:2},maxWidthInPixels:100,maxWidthFraction:.25,leftPixelOffset:10,bottomPixelOffset:10,marginPixelsBetweenScaleBars:5};function IN(i){const e={...Q0};for(const t of["textHeightInPixels","barTopMarginInPixels","barHeightInPixels","paddingInPixels","scaleFactor","maxWidthInPixels","maxWidthFraction","leftPixelOffset","bottomPixelOffset"])(0,p.cQ)(i,t,n=>{n!==void 0&&(e[t]=(0,p._D)(n))});return(0,p.cQ)(i,"fontName",t=>{t!==void 0&&(e.fontName=(0,p.zr)(t))}),e}class RN extends A.DN{constructor(){super(Q0,IN)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var kN=(i=>(i[i.COLOR=0]="COLOR",i[i.Z=1]="Z",i[i.PICK=2]="PICK",i[i.NUM_TEXTURES=3]="NUM_TEXTURES",i))(kN||{}),LN=(i=>(i[i.TRANSPARENT=0]="TRANSPARENT",i[i.VOLUME_RENDERING=1]="VOLUME_RENDERING",i[i.MAX_PROJECTION=2]="MAX_PROJECTION",i))(LN||{});const PN=`
void emit(vec4 color, highp uint pickId) {
  out_color = color;
  float zValue = 1.0 - gl_FragCoord.z;
  out_z = vec4(zValue, zValue, zValue, 1.0);
  float pickIdFloat = float(pickId);
  out_pickId = vec4(pickIdFloat, pickIdFloat, pickIdFloat, 1.0);
}
`,q0=[`
float computeOITWeight(float alpha, float depth) {
  float a = min(1.0, alpha) * 8.0 + 0.01;
  float b = -depth * 0.95 + 1.0;
  return a * a * a * b * b * b;
}
`,`
void emitAccumAndRevealage(vec4 accum, float revealage, highp uint pickId) {
  v4f_fragData0 = vec4(accum.rgb, revealage);
  v4f_fragData1 = vec4(accum.a, 0.0, 0.0, 0.0);
}
void emit(vec4 color, highp uint pickId) {
  float weight = computeOITWeight(color.a, gl_FragCoord.z);
  vec4 accum = color * weight;
  emitAccumAndRevealage(accum, color.a, pickId);
}
`];function $u(i){i.addOutputBuffer("vec4","out_color",0),i.addOutputBuffer("highp vec4","out_z",1),i.addOutputBuffer("highp vec4","out_pickId",2),i.addFragmentCode(PN)}function Gu(i){i.addOutputBuffer("vec4","v4f_fragData0",0),i.addOutputBuffer("vec4","v4f_fragData1",1),i.addFragmentCode(q0)}function AN(i){i.addOutputBuffer("vec4","out_color",0),i.addOutputBuffer("highp vec4","out_z",1),i.addOutputBuffer("highp vec4","out_intensity",2),i.addOutputBuffer("highp vec4","out_pickId",3),i.addFragmentCode(`
void emit(vec4 color, float depth, float intensity, highp uint pickId) {
  float pickIdFloat = float(pickId);
  float bufferDepth = 1.0 - depth;
  out_color = color;
  out_z = vec4(bufferDepth, bufferDepth, bufferDepth, 1.0);
  out_intensity = vec4(intensity, intensity, intensity, 1.0);
  out_pickId = vec4(pickIdFloat, pickIdFloat, pickIdFloat, 1.0);
}`)}const qn=w.eR.create(),K0=w.ln.create(),MN=w.pB.create();function NN(i){i.addOutputBuffer("vec4","v4f_fragColor",null),i.setFragmentMain(`
vec4 v0 = getValue0();
vec4 v1 = getValue1();
vec4 accum = vec4(v0.rgb, v1.r);
float revealage = v0.a;

v4f_fragColor = vec4(accum.rgb / accum.a, revealage);
`)}function ON(i){i.addOutputBuffer("vec4","v4f_fragData0",0),i.addOutputBuffer("vec4","v4f_fragData1",1),i.setFragmentMain(`
  v4f_fragData0 = vec4(0.0, 0.0, 0.0, 1.0);
  v4f_fragData1 = vec4(0.0, 0.0, 0.0, 1.0);
  vec4 v0 = getValue0();
  gl_FragDepth = 1.0 - v0.r;
`)}function VN(i){i.addOutputBuffer("vec4","v4f_fragData0",0),i.addOutputBuffer("vec4","v4f_fragData1",1),i.addFragmentCode(q0),i.setFragmentMain(`
vec4 color = getValue0();
float bufferDepth = getValue1().r;
float weight = computeOITWeight(color.a, 1.0 - bufferDepth);
vec4 accum = color * weight;
float revealage = color.a;

emitAccumAndRevealage(accum, revealage, 0u);
`)}function _N(i){i.addOutputBuffer("vec4","out_color",0),i.addOutputBuffer("highp vec4","out_z",1),i.addOutputBuffer("highp vec4","out_pickId",2),i.setFragmentMain(`
out_color = vec4(0.0);
out_z = getValue0();
out_pickId = getValue1();
`)}function BN(i){i.addOutputBuffer("highp vec4","out_z",0),i.addOutputBuffer("highp vec4","out_pickId",1),i.setFragmentMain(`
out_z = getValue0();
out_pickId = getValue2();
gl_FragDepth = getValue1().r;
`)}const FN=ir(un);class UN extends FN{constructor(e){super(),this.panel=e}initializeCounterpart(e,t){this.sharedProjectionParameters=this.registerDisposer(new fo(e,this.panel.projectionParameters)),t.projectionParameters=this.sharedProjectionParameters.rpcId,super.initializeCounterpart(e,t)}}class zu extends j0{constructor(e,t,n){super(e,t,n),this.frameRateCalculator=new Aw(6,4,8,60),this.isCameraInContinuousMotion=!1,this.hasVolumeRendering=!1,this.hasTransparent=!1,this.sliceViews=this.registerDisposer(new Yl((r,o,a)=>{r.registerDisposer(a),r.registerDisposer(a.visibility.add(this.visibility))})),this.axesLineHelper=this.registerDisposer(rl.get(this.gl)),this.sliceViewRenderHelper=this.registerDisposer(qo.get(this.gl,$u)),this.offscreenFramebuffer=this.registerDisposer(new $n(this.gl,{colorBuffers:[new pn(this.gl,WebGL2RenderingContext.RGBA8,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.UNSIGNED_BYTE),new pn(this.gl,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT),new pn(this.gl,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT)],depthBuffer:new yo(this.gl)})),this.offscreenCopyHelper=this.registerDisposer(En.get(this.gl)),this.transparencyCopyHelper=this.registerDisposer(En.get(this.gl,NN,2)),this.maxProjectionColorCopyHelper=this.registerDisposer(En.get(this.gl,VN,2)),this.offscreenDepthCopyHelper=this.registerDisposer(En.get(this.gl,ON,1)),this.maxProjectionPickCopyHelper=this.registerDisposer(En.get(this.gl,_N,2)),this.maxProjectionToPickCopyHelper=this.registerDisposer(En.get(this.gl,BN,3)),this.scaleBars=this.registerDisposer(new Y0(this.gl)),this.projectionParameters=this.registerDisposer(new hp({navigationState:this.navigationState,update:(r,o)=>{const{invViewMatrix:a,projectionMat:l,logicalWidth:c,logicalHeight:d}=r,u=c/d,h=Math.PI/4;let{relativeDepthRange:f}=o,g=o.zoomFactor.value/2;if(this.viewer.orthographicProjection.value){const v=Math.max(.1,1-f),y=1+f;w.pB.ortho(l,-u,u,-1,1,v,y)}else{const v=1/Math.tan(h/2);f/=v;const y=Math.max(.1,1-f),S=1+f;g*=v,w.pB.perspective(l,h,u,y,S)}Kh(r,l),o.pose.toMat4(a,g),w.pB.scale(a,a,w.eR.set(qn,1,-1,-1)),w.pB.translate(a,a,w.T2[2]),tp(r)}})),this.projectionParameters.changed.add(()=>this.context.scheduleRedraw());const s=this.sharedObject=this.registerDisposer(new UN(this));if(s.RPC_TYPE_ID=pN.l,s.initializeCounterpart(n.rpc,{}),s.visibility.add(this.visibility),this.visibleLayerTracker=Rg(this.viewer.layerManager,$i,this.viewer.visibleLayerRoles,this),this.registerDisposer(this.context.continuousCameraMotionFinished.add(()=>{this.isCameraInContinuousMotion=!1,this.hasVolumeRendering&&(this.scheduleRedraw(),this.frameRateCalculator.resetForNewFrameSet())})),this.registerDisposer(this.context.continuousCameraMotionStarted.add(()=>{this.isCameraInContinuousMotion=!0})),X(t,"rotate-via-mouse-drag",r=>{$t(r.detail,(o,a,l)=>{this.context.flagContinuousCameraMotion(),this.navigationState.pose.rotateRelative(w.T2[1],a/4*Math.PI/180),this.navigationState.pose.rotateRelative(w.T2[0],-l/4*Math.PI/180)})}),X(t,"rotate-in-plane-via-touchrotate",r=>{this.context.flagContinuousCameraMotion();const{detail:o}=r;this.navigationState.pose.rotateRelative(w.T2[2],o.angle-o.prevAngle)}),X(t,"rotate-out-of-plane-via-touchtranslate",r=>{this.context.flagContinuousCameraMotion();const{detail:o}=r;this.navigationState.pose.rotateRelative(w.T2[1],o.deltaX/4*Math.PI/180),this.navigationState.pose.rotateRelative(w.T2[0],-o.deltaY/4*Math.PI/180)}),n.showSliceViewsCheckbox){const r=this.registerDisposer(new Un(n.showSliceViews));r.element.className="perspective-panel-show-slice-views neuroglancer-noselect";const o=document.createElement("label");o.className="perspective-panel-show-slice-views neuroglancer-noselect",o.appendChild(document.createTextNode("Sections")),o.appendChild(r.element),this.element.appendChild(o)}this.registerDisposer(n.orthographicProjection.changed.add(()=>{this.projectionParameters.update(),this.scheduleRedraw()})),this.registerDisposer(n.showScaleBar.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.scaleBarOptions.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.showSliceViews.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.showAxisLines.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.crossSectionBackgroundColor.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.perspectiveViewBackgroundColor.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.wireFrame.changed.add(()=>this.scheduleRedraw())),this.sliceViews.changed.add(()=>this.scheduleRedraw())}get rpc(){return this.sharedObject.rpc}get rpcId(){return this.sharedObject.rpcId}get displayDimensionRenderInfo(){return this.navigationState.displayDimensionRenderInfo}get shouldDownsample(){return this.viewer.enableAdaptiveDownsampling.value&&this.isCameraInContinuousMotion&&this.hasVolumeRendering}flushBackendProjectionParameters(){this.sharedObject.sharedProjectionParameters.flush()}translateByViewportPixels(e,t){const n=qn,{viewProjectionMat:s,invViewProjectionMat:r,logicalWidth:o,logicalHeight:a}=this.projectionParameters.value,{pose:l}=this.viewer.navigationState;l.updateDisplayPosition(c=>{w.eR.transformMat4(n,c,s),n[0]+=-2*e/o,n[1]+=2*t/a,w.eR.transformMat4(c,n,r)})}get navigationState(){return this.viewer.navigationState}ensureBoundsUpdated(){super.ensureBoundsUpdated(),this.projectionParameters.setViewport(this.renderViewport)}isReady(){if(!this.visible)return!0;for(const[o,a]of this.sliceViews)if((a||this.viewer.showSliceViews.value)&&!o.isReady())return!1;this.ensureBoundsUpdated();const{width:e,height:t}=this.renderViewport;if(e===0||t===0)return!0;const s={projectionParameters:this.projectionParameters.value},{visibleLayers:r}=this.visibleLayerTracker;for(const[o,a]of r)if(!o.isReady(s,a))return!1;return!0}disposed(){this.sliceViews.clear(),super.disposed()}getDepthArray(){if(!this.navigationState.valid)return;const{offscreenFramebuffer:e,renderViewport:{width:t,height:n}}=this,s=t*n,r=new Float32Array(s*4);try{e.bindSingle(1),this.gl.readPixels(0,0,t,n,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.FLOAT,r)}finally{e.framebuffer.unbind()}const o=new Float32Array(s);for(let a=0;a<s;++a)o[a]=r[a*4];return o}issuePickRequest(e,t){const{offscreenFramebuffer:n}=this;n.readPixelFloat32IntoBuffer(1,e-bt,t-bt,0,He,He),n.readPixelFloat32IntoBuffer(2,e-bt,t-bt,16*He*He,He,He)}completePickRequest(e,t,n,s){const{mouseState:r}=this.viewer;r.pickedRenderLayer=null,J0(n,0,4,e,t,s.viewportWidth,s.viewportHeight);const o=ol.length;for(let a=0;a<o;++a){const l=ol[a],c=n[4*l];if(c===0)continue;const d=l%He,u=(l-d)/He,h=1-c;qn[0]=2*(e+d-bt)/s.viewportWidth-1,qn[1]=2*(t+u-bt)/s.viewportHeight-1,qn[2]=2*h-1,w.eR.transformMat4(qn,qn,s.invTransform);let{position:f,unsnappedPosition:m}=r;const{value:g}=this.navigationState.position,v=g.length;f.length!==v&&(f=r.position=new Float32Array(v)),m.length!==v&&(m=r.unsnappedPosition=new Float32Array(v)),f.set(g),r.coordinateSpace=this.navigationState.coordinateSpace.value;const y=this.navigationState.pose.displayDimensions.value,{displayDimensionIndices:S}=y;for(let b=0,E=S.length;b<E;++b)f[S[b]]=qn[b];m.set(f);const x=n[4*He*He+4*l];s.pickIDs.setMouseState(r,x),r.displayDimensions=y,r.setActive(!0);return}r.setActive(!1)}translateDataPointByViewportPixels(e,t,n,s){const r=qn,{viewProjectionMat:o,invViewProjectionMat:a,width:l,height:c}=this.projectionParameters.value;return w.eR.transformMat4(r,t,o),r[0]+=2*n/l,r[1]+=-2*s/c,w.eR.transformMat4(e,r,a)}get transparentConfiguration(){let e=this.transparentConfiguration_;return e===void 0&&(e=this.transparentConfiguration_=this.registerDisposer(new $n(this.gl,{colorBuffers:cs(this.gl,2,this.gl.RGBA32F,this.gl.RGBA,this.gl.FLOAT),depthBuffer:this.offscreenFramebuffer.depthBuffer.addRef()}))),e}get volumeRenderingConfiguration(){let e=this.volumeRenderingConfiguration_;return e===void 0&&(e=this.volumeRenderingConfiguration_=this.registerDisposer(new $n(this.gl,{colorBuffers:cs(this.gl,2,this.gl.RGBA32F,this.gl.RGBA,this.gl.FLOAT),depthBuffer:new yo(this.gl)}))),e}get maxProjectionConfiguration(){let e=this.maxProjectionConfiguration_;return e===void 0&&(e=this.maxProjectionConfiguration_=this.registerDisposer(new $n(this.gl,{colorBuffers:[new pn(this.gl,WebGL2RenderingContext.RGBA8,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.UNSIGNED_BYTE),new pn(this.gl,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT),new pn(this.gl,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT),new pn(this.gl,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT)],depthBuffer:new yo(this.gl)}))),e}get maxProjectionPickConfiguration(){let e=this.maxProjectionPickConfiguration_;return e===void 0&&(e=this.maxProjectionPickConfiguration_=this.registerDisposer(new $n(this.gl,{colorBuffers:cs(this.gl,2,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT),depthBuffer:new yo(this.gl)}))),e}drawWithPicking(e){if(!this.navigationState.valid)return!1;const{width:t,height:n}=this.renderViewport,s=this.viewer.showSliceViews.value;for(const[S,x]of this.sliceViews)(x||s)&&S.updateRendering();const r=this.gl,o=()=>{r.drawBuffers(this.offscreenFramebuffer.singleAttachmentList)},a=()=>{this.offscreenFramebuffer.bind(t,n)};a(),r.disable(r.SCISSOR_TEST),r.enable(WebGL2RenderingContext.STENCIL_TEST),r.stencilMask(4294967295),r.clearStencil(0),r.clear(WebGL2RenderingContext.STENCIL_BUFFER_BIT),r.stencilOp(WebGL2RenderingContext.KEEP,WebGL2RenderingContext.KEEP,WebGL2RenderingContext.REPLACE),r.stencilFunc(WebGL2RenderingContext.ALWAYS,1,1);const l=this.viewer.perspectiveViewBackgroundColor.value;this.gl.clearColor(l[0],l[1],l[2],0),r.clear(r.DEPTH_BUFFER_BIT),r.clearBufferfv(WebGL2RenderingContext.COLOR,0,[l[0],l[1],l[2],0]),r.clearBufferfv(WebGL2RenderingContext.COLOR,1,w.yb),r.clearBufferfv(WebGL2RenderingContext.COLOR,2,w.yb),r.enable(r.DEPTH_TEST);const c=this.projectionParameters.value,d=w.eR.create();w.eR.transformQuat(d,w.T2[2],this.navigationState.pose.orientation.orientation),w.eR.scale(d,d,-1);const u=.2,h=1-u,f={wireFrame:this.viewer.wireFrame.value,projectionParameters:c,lightDirection:d,ambientLighting:u,directionalLighting:h,pickIDs:e.pickIDs,emitter:$u,emitColor:!0,emitPickID:!0,alreadyEmittedPickID:!1,bindFramebuffer:a,frameNumber:this.context.frameNumber,sliceViewsPresent:this.sliceViews.size>0,isContinuousCameraMotionInProgress:this.context.isContinuousCameraMotionInProgress};w.pB.copy(e.invTransform,c.invViewProjectionMat);const{visibleLayers:m}=this.visibleLayerTracker;this.hasTransparent=!1;let g=!1,v=!1,y=!1;for(const[S,x]of m)S.isTransparent?(this.hasTransparent=!0,S.isVolumeRendering&&(y=!0,g=g||Fy(S))):S.isAnnotation?v=!0:S.draw(f,x);if(this.hasVolumeRendering=y,this.drawSliceViews(f),v){r.enable(WebGL2RenderingContext.BLEND),r.depthFunc(WebGL2RenderingContext.LEQUAL),r.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA);for(const[S,x]of m)if(S.isAnnotation){const b=S;b.base.state.displayState.disablePicking.value?(o(),b.draw(f,x),f.bindFramebuffer()):b.draw(f,x)}r.depthFunc(WebGL2RenderingContext.LESS),r.disable(WebGL2RenderingContext.BLEND)}if(this.viewer.showAxisLines.value&&this.drawAxisLines(),r.stencilOp(WebGL2RenderingContext.KEEP,WebGL2RenderingContext.KEEP,WebGL2RenderingContext.KEEP),this.hasTransparent){let S=t,x=n;if(this.shouldDownsample){this.frameRateCalculator.setFrameDeltas(this.context.getLastFrameTimesInMs(this.frameRateCalculator.numberOfStoredFrameDeltas));const L=this.frameRateCalculator.calculateDownsamplingRate(qh.MEAN);if(L>1){const _=t/n;S=Math.round(t/L),x=Math.round(S/_)}}let b=()=>{},E=()=>{};if(g){const{maxProjectionConfiguration:L}=this;b=()=>{L.bind(S,x)},r.depthMask(!0),b(),f.bindMaxProjectionBuffer=b,r.clearColor(0,0,0,0),r.clearDepth(0),r.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT|WebGL2RenderingContext.DEPTH_BUFFER_BIT);const{maxProjectionPickConfiguration:_}=this;E=()=>{_.bind(S,x)},E(),r.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT|WebGL2RenderingContext.DEPTH_BUFFER_BIT)}let C=()=>{};y&&(C=()=>{this.volumeRenderingConfiguration.bind(S,x)},C(),r.depthMask(!0),r.clearDepth(1),r.clearColor(0,0,0,1),r.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT|WebGL2RenderingContext.DEPTH_BUFFER_BIT),this.offscreenDepthCopyHelper.draw(this.offscreenFramebuffer.colorBuffers[1].texture));const{transparentConfiguration:k}=this;f.bindFramebuffer=()=>{k.bind(t,n)},f.bindFramebuffer(),r.depthMask(!1),r.enable(WebGL2RenderingContext.BLEND),r.clearColor(0,0,0,1),r.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT),f.emitter=Gu,r.blendFuncSeparate(WebGL2RenderingContext.ONE,WebGL2RenderingContext.ONE,WebGL2RenderingContext.ZERO,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),f.emitPickID=!1;let T=0;for(const[L,_]of m)L.isTransparent&&(f.depthBufferTexture=this.offscreenFramebuffer.colorBuffers[1].texture),L.isVolumeRendering&&Fy(L)?(r.depthMask(!0),r.disable(WebGL2RenderingContext.BLEND),r.depthFunc(WebGL2RenderingContext.GREATER),T!==2&&(f.emitter=AN,b()),L.draw(f,_),E(),this.maxProjectionToPickCopyHelper.draw(this.maxProjectionConfiguration.colorBuffers[1].texture,this.maxProjectionConfiguration.colorBuffers[2].texture,this.maxProjectionConfiguration.colorBuffers[3].texture),C(),r.depthMask(!1),r.disable(WebGL2RenderingContext.DEPTH_TEST),r.enable(WebGL2RenderingContext.BLEND),r.blendFuncSeparate(WebGL2RenderingContext.ONE,WebGL2RenderingContext.ONE,WebGL2RenderingContext.ZERO,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),this.maxProjectionColorCopyHelper.draw(this.maxProjectionConfiguration.colorBuffers[0].texture,this.maxProjectionConfiguration.colorBuffers[1].texture),b(),r.depthMask(!0),r.clearColor(0,0,0,0),r.clearDepth(0),r.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT|WebGL2RenderingContext.DEPTH_BUFFER_BIT),r.clearDepth(1),r.clearColor(0,0,0,1),r.depthMask(!1),r.enable(WebGL2RenderingContext.DEPTH_TEST),r.depthFunc(WebGL2RenderingContext.LESS),T=2):L.isVolumeRendering?(T!==1&&(f.emitter=Gu,C()),T=1,L.draw(f,_)):L.isTransparent&&(T!==0&&(f.emitter=Gu,f.bindFramebuffer()),T=0,L.draw(f,_));r.disable(WebGL2RenderingContext.DEPTH_TEST),r.viewport(0,0,t,n),this.offscreenFramebuffer.bindSingle(0),r.blendFunc(WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA,WebGL2RenderingContext.SRC_ALPHA),y&&this.transparencyCopyHelper.draw(this.volumeRenderingConfiguration.colorBuffers[0].texture,this.volumeRenderingConfiguration.colorBuffers[1].texture),this.transparencyCopyHelper.draw(k.colorBuffers[0].texture,k.colorBuffers[1].texture),r.depthMask(!0),r.disable(WebGL2RenderingContext.BLEND),r.enable(WebGL2RenderingContext.DEPTH_TEST),f.bindFramebuffer=a,a(),r.enable(WebGL2RenderingContext.STENCIL_TEST),r.drawBuffers([r.NONE,r.COLOR_ATTACHMENT1,r.COLOR_ATTACHMENT2]),f.emitter=$u,f.emitPickID=!0,f.emitColor=!1,r.stencilFunc(WebGL2RenderingContext.NOTEQUAL,3,1),r.stencilOp(WebGL2RenderingContext.KEEP,WebGL2RenderingContext.KEEP,WebGL2RenderingContext.REPLACE),r.stencilMask(2),g&&this.maxProjectionPickCopyHelper.draw(this.maxProjectionPickConfiguration.colorBuffers[0].texture,this.maxProjectionPickConfiguration.colorBuffers[1].texture);for(const[L,_]of m)!L.isTransparent||!L.transparentPickEnabled||L.isVolumeRendering||L.draw(f,_);r.stencilFunc(WebGL2RenderingContext.EQUAL,0,3),r.stencilOp(WebGL2RenderingContext.KEEP,WebGL2RenderingContext.KEEP,WebGL2RenderingContext.KEEP),r.stencilMask(0);for(const[L,_]of m)!L.isTransparent||L.transparentPickEnabled||L.draw(f,_)}if(r.stencilMask(4294967295),r.disable(WebGL2RenderingContext.STENCIL_TEST),this.viewer.showScaleBar.value&&this.viewer.orthographicProjection.value){r.drawBuffers([r.COLOR_ATTACHMENT0]),r.disable(WebGL2RenderingContext.DEPTH_TEST),r.enable(WebGL2RenderingContext.BLEND),r.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA);const{scaleBars:S}=this,x=this.viewer.scaleBarOptions.value;S.draw(this.renderViewport,this.navigationState.displayDimensionRenderInfo.value,this.navigationState.relativeDisplayScales.value,this.navigationState.zoomFactor.value/this.renderViewport.logicalHeight,x),r.disable(WebGL2RenderingContext.BLEND)}return this.offscreenFramebuffer.unbind(),this.setGLClippedViewport(),this.offscreenCopyHelper.draw(this.offscreenFramebuffer.colorBuffers[0].texture),!0}drawSliceViews(e){const{sliceViewRenderHelper:t}=this,{lightDirection:n,ambientLighting:s,directionalLighting:r,projectionParameters:{viewProjectionMat:o}}=e,a=this.viewer.showSliceViews.value;for(const[l,c]of this.sliceViews){if(!c&&!a)continue;const{width:d,height:u,invViewMatrix:h,viewportNormalInCanonicalCoordinates:f}=l.projectionParameters.value;if(d===0||u===0||!l.valid)continue;const m=Math.abs(w.eR.dot(n,f)),g=s+m*r,v=MN;w.pB.identity(v),v[0]=d/2,v[5]=-u/2,w.pB.multiply(v,h,v),w.pB.multiply(v,o,v);const y=K0,S=this.viewer.crossSectionBackgroundColor.value;y[0]=S[0],y[1]=S[1],y[2]=S[2],y[3]=1,t.draw(l.offscreenFramebuffer.colorBuffers[0].texture,v,w.ln.fromValues(g,g,g,1),K0,0,0,1,1)}}drawAxisLines(){const{zoomFactor:{value:e}}=this.viewer.navigationState,t=this.projectionParameters.value,n=Math.min(t.logicalWidth,t.logicalHeight)/this.renderViewport.logicalHeight/4,s=e*n,{gl:r}=this;r.drawBuffers([r.COLOR_ATTACHMENT0]),this.axesLineHelper.draw(B0(t,s),!1)}zoomByMouse(e){this.navigationState.zoomBy(e)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var $N=(i=>(i[i.COLOR=0]="COLOR",i[i.PICK=1]="PICK",i[i.NUM_TEXTURES=2]="NUM_TEXTURES",i))($N||{});function GN(i){i.addOutputBuffer("vec4","out_fragColor",0),i.addOutputBuffer("highp vec4","out_pickId",1),i.addFragmentCode(`
void emit(vec4 color, highp uint pickId) {
  out_fragColor = color;
  float pickIdFloat = float(pickId);
  out_pickId = vec4(pickIdFloat, pickIdFloat, pickIdFloat, 1.0);
}
`)}function zN(i){i.addOutputBuffer("vec4","out_fragColor",null),i.addFragmentCode(`
void emit(vec4 color, highp uint pickId) {
  out_fragColor = color;
}
`)}const ts=w.eR.create(),WN=w.eR.create(),HN=w.ln.create();class al extends j0{constructor(e,t,n,s){super(e,t,s),this.sliceView=n,this.axesLineHelper=this.registerDisposer(rl.get(this.gl)),this.sliceViewRenderHelper=this.registerDisposer(qo.get(this.gl,zN)),this.colorFactor=w.ln.fromValues(1,1,1,1),this.pickIDs=new U0,this.offscreenFramebuffer=this.registerDisposer(new $n(this.gl,{colorBuffers:[new pn(this.gl,WebGL2RenderingContext.RGBA8,WebGL2RenderingContext.RGBA,WebGL2RenderingContext.UNSIGNED_BYTE),new pn(this.gl,WebGL2RenderingContext.R32F,WebGL2RenderingContext.RED,WebGL2RenderingContext.FLOAT)]})),this.offscreenCopyHelper=this.registerDisposer(En.get(this.gl)),this.scaleBars=this.registerDisposer(new Y0(this.gl)),s.wireFrame.changed.add(()=>this.scheduleRedraw()),X(t,"rotate-via-mouse-drag",r=>{const{mouseState:o}=this.viewer;if(o.updateUnconditionally()){const a=Float32Array.from(o.position);$t(r.detail,(l,c,d)=>{this.context.flagContinuousCameraMotion();const{pose:u}=this.navigationState,h=w.eR.transformQuat(ts,w.T2[0],u.orientation.orientation),f=w.eR.transformQuat(WN,w.T2[1],u.orientation.orientation);this.viewer.navigationState.pose.rotateAbsolute(f,-c/4*Math.PI/180,a),this.viewer.navigationState.pose.rotateAbsolute(h,-d/4*Math.PI/180,a)})}}),X(t,"rotate-in-plane-via-touchrotate",r=>{const{detail:o}=r,{mouseState:a}=this.viewer;this.handleMouseMove(o.centerX,o.centerY),a.updateUnconditionally()&&(this.context.flagContinuousCameraMotion(),this.navigationState.pose.rotateAbsolute(this.sliceView.projectionParameters.value.viewportNormalInCanonicalCoordinates,o.angle-o.prevAngle,a.position))}),this.registerDisposer(n),this.visibleLayerTracker=Rg(this.viewer.layerManager,Bi,this.viewer.visibleLayerRoles,this),this.registerDisposer(s.crossSectionBackgroundColor.changed.add(()=>this.scheduleRedraw())),this.registerDisposer(n.visibility.add(this.visibility)),this.registerDisposer(n.viewChanged.add(()=>{this.visible&&e.scheduleRedraw()})),this.registerDisposer(s.showAxisLines.changed.add(()=>{this.visible&&this.scheduleRedraw()})),this.registerDisposer(s.showScaleBar.changed.add(()=>{this.visible&&this.context.scheduleRedraw()})),this.registerDisposer(s.scaleBarOptions.changed.add(()=>{this.visible&&this.context.scheduleRedraw()}))}flushBackendProjectionParameters(){this.sliceView.flushBackendProjectionParameters()}get displayDimensionRenderInfo(){return this.navigationState.displayDimensionRenderInfo}get rpc(){return this.sliceView.rpc}get rpcId(){return this.sliceView.rpcId}get navigationState(){return this.sliceView.navigationState}translateByViewportPixels(e,t){const{pose:n}=this.viewer.navigationState;n.updateDisplayPosition(s=>{w.eR.set(s,-e,-t,0),w.eR.transformMat4(s,s,this.sliceView.projectionParameters.value.invViewMatrix)})}translateDataPointByViewportPixels(e,t,n,s){const r=this.sliceView.projectionParameters.value;return w.eR.transformMat4(e,t,r.viewMatrix),w.eR.set(e,e[0]+n,e[1]+s,e[2]),w.eR.transformMat4(e,e,r.invViewMatrix),e}isReady(){if(!this.visible)return!1;const{sliceView:e}=this;if(this.ensureBoundsUpdated(),!e.isReady())return!1;const t={projectionParameters:e.projectionParameters.value,sliceView:e};for(const[n,s]of this.visibleLayerTracker.visibleLayers)if(!n.isReady(t,s))return!1;return!0}drawWithPicking(e){const{sliceView:t}=this;if(!t.valid)return!1;t.updateRendering();const n=t.projectionParameters.value,{width:s,height:r,invViewProjectionMat:o}=n;w.pB.copy(e.invTransform,o);const{gl:a}=this;this.offscreenFramebuffer.bind(s,r),a.disable(WebGL2RenderingContext.SCISSOR_TEST),this.gl.clearColor(0,0,0,0),a.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT);const l=HN,c=this.viewer.crossSectionBackgroundColor.value;l[0]=c[0],l[1]=c[1],l[2]=c[2],l[3]=1,this.offscreenFramebuffer.bindSingle(0),this.sliceViewRenderHelper.draw(t.offscreenFramebuffer.colorBuffers[0].texture,w.r3,this.colorFactor,l,0,0,1,1);const{visibleLayers:d}=this.visibleLayerTracker,{pickIDs:u}=this;u.clear();const h=()=>{a.disable(WebGL2RenderingContext.SCISSOR_TEST),a.enable(WebGL2RenderingContext.BLEND),a.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),this.offscreenFramebuffer.bind(s,r)};h();const f={wireFrame:this.viewer.wireFrame.value,projectionParameters:n,pickIDs:u,emitter:GN,emitColor:!0,emitPickID:!0,sliceView:t,bindFramebuffer:h,frameNumber:this.context.frameNumber};for(const[m,g]of d)m.draw(f,g);if(a.disable(WebGL2RenderingContext.BLEND),this.viewer.showAxisLines.value||this.viewer.showScaleBar.value){if(this.offscreenFramebuffer.bindSingle(0),this.viewer.showAxisLines.value){const m=Math.min(n.logicalWidth,n.logicalHeight)/4*1.5,{zoomFactor:{value:g}}=this.viewer.navigationState;this.axesLineHelper.draw((0,w.Qi)(B0(n,m*g)))}this.viewer.showScaleBar.value&&(a.enable(WebGL2RenderingContext.BLEND),a.blendFunc(WebGL2RenderingContext.SRC_ALPHA,WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA),this.scaleBars.draw(n,this.navigationState.displayDimensionRenderInfo.value,this.navigationState.relativeDisplayScales.value,this.navigationState.zoomFactor.value,this.viewer.scaleBarOptions.value),a.disable(WebGL2RenderingContext.BLEND))}return this.offscreenFramebuffer.unbind(),this.setGLClippedViewport(),this.offscreenCopyHelper.draw(this.offscreenFramebuffer.colorBuffers[0].texture),!0}ensureBoundsUpdated(){super.ensureBoundsUpdated(),this.sliceView.projectionParameters.setViewport(this.renderViewport)}issuePickRequest(e,t){const{offscreenFramebuffer:n}=this;n.readPixelFloat32IntoBuffer(1,e-bt,t-bt,0,He,He)}completePickRequest(e,t,n,s){const{mouseState:r}=this.viewer;r.pickedRenderLayer=null,J0(n,0,4,e,t,s.viewportWidth,s.viewportHeight);const{viewportWidth:o,viewportHeight:a}=s,l=ol.length,{value:c}=this.navigationState.position,d=c.length,u=this.navigationState.pose.displayDimensions.value,{displayRank:h,displayDimensionIndices:f}=u,m=(y,S,x)=>{const b=e+y,E=t+S;ts[0]=2*b/o-1,ts[1]=2*E/a-1,ts[2]=0,w.eR.transformMat4(ts,ts,s.invTransform),x.set(c);for(let C=0;C<h;++C)x[f[C]]=ts[C]};let{unsnappedPosition:g}=r;g.length!==d&&(g=r.unsnappedPosition=new Float32Array(d)),r.coordinateSpace=this.navigationState.coordinateSpace.value,r.displayDimensions=u,m(0,0,g);const v=(y,S,x)=>{let{position:b}=r;b.length!==d&&(b=r.position=new Float32Array(d)),m(y-bt,S-bt,b),this.pickIDs.setMouseState(r,x),r.setActive(!0)};for(let y=0;y<l;++y){const S=ol[y],x=n[4*y];if(x===0)continue;const b=S%He,E=(S-b)/He;v(b,E,x);return}v(bt,bt,0)}zoomByMouse(e){const{navigationState:t}=this;if(!t.valid)return;const{sliceView:n}=this,{width:s,height:r,invViewMatrix:o,displayDimensionRenderInfo:{displayDimensionIndices:a,displayRank:l}}=n.projectionParameters.value;let{mouseX:c,mouseY:d}=this;c-=s/2,d-=r/2;const u=this.navigationState.position.value;for(let h=0;h<l;++h){const f=a[h],m=o[h]*c+o[4+h]*d;u[f]+=m*(1-e)}this.navigationState.position.changed.dispatch(),t.zoomBy(e)}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const JN=["#f00","#0f0","#99f"],X0=Pe.fromObject({arrowup:{action:"move-up"},arrowdown:{action:"move-down"},wheel:{action:"adjust-via-wheel"},enter:{action:"commit"},escape:{action:"cancel"}});function jN(i){if(i<1||i>1024){const e=Math.log2(i)|0,t=i/2**e;return`${Xg(t,1)}p${e}`}return i.toString()}const YN=[i=>i.name,i=>i.scaleFactor],QN=2e3;class qN extends D.O8{constructor(e,t,n,s="px"){super(),this.displayDimensionRenderInfo=e,this.zoom=t,this.depthRange=n,this.displayUnit=s,this.element=document.createElement("div"),this.dimensionGridContainer=document.createElement("div"),this.depthGridContainer=document.createElement("div"),this.defaultCheckbox=document.createElement("input"),this.dimensionElements=Array.from(Array(3),(g,v)=>{const y=document.createElement("div");y.classList.add("neuroglancer-display-dimensions-widget-dimension"),y.style.display="contents",X(y,"adjust-via-wheel",k=>{const T=k.detail,{deltaY:L}=T;L!==0&&this.zoomDimension(v,Math.sign(L))});const S=document.createElement("input");S.classList.add("neuroglancer-display-dimensions-widget-name"),S.title="Change display dimensions",S.spellcheck=!1,S.autocomplete="off",S.style.color=JN[v],S.style.gridColumn="1",S.style.gridRow=`${v+1}`,S.addEventListener("focus",()=>{S.select()}),y.appendChild(S);const x=document.createElement("span");x.classList.add("neuroglancer-display-dimensions-widget-scale-factor");const b=document.createElement("input");b.spellcheck=!1,b.title="Change relative scale at which dimension is displayed",b.autocomplete="off",x.style.gridColumn="2",x.style.gridRow=`${v+1}`,b.addEventListener("focus",()=>{b.select()}),x.appendChild(b),y.appendChild(x);const E=document.createElement("span");E.classList.add("neuroglancer-display-dimensions-widget-scale"),E.style.gridColumn="3",E.style.gridRow=`${v+1}`,y.appendChild(E),this.dimensionGridContainer.appendChild(y);const C={name:S,container:y,scaleFactor:b,scale:E,scaleFactorModified:!1};S.addEventListener("input",()=>{Ft(S),this.updateNameValidity()}),X(S,"commit",()=>{this.updateNames()}),S.addEventListener("blur",k=>{const{relatedTarget:T}=k;this.dimensionElements.some(L=>L.name===T)||this.updateNames()||this.updateView()}),x.addEventListener("click",k=>{const{target:T}=k;T!==b&&(b.focus(),k.preventDefault())}),b.addEventListener("input",()=>{Ft(b),C.scaleFactorModified=!0}),X(b,"commit",()=>{this.updateScaleFactors()}),b.addEventListener("blur",()=>{this.updateScaleFactors()||this.updateView()});for(const k of YN)X(k(C),"move-up",()=>{v!==0&&k(this.dimensionElements[v-1]).focus()}),X(k(C),"move-down",()=>{v!==2&&k(this.dimensionElements[v+1]).focus()});return C}),this.scheduleUpdateView=(0,je.t)(()=>this.updateView());const{element:r,dimensionGridContainer:o,defaultCheckbox:a}=this,l=document.createElement("label"),c=this.registerCancellable((0,xe.A)(()=>{r.dataset.active="false"},QN)),d=()=>{r.dataset.active="true",c()};this.registerDisposer(t.changed.add(d)),this.registerDisposer(e.relativeDisplayScales.changed.add(d)),this.registerDisposer(n.changed.add(d)),r.classList.add("neuroglancer-display-dimensions-widget"),r.appendChild(o),o.classList.add("neuroglancer-display-dimensions-widget-dimension-grid"),r.addEventListener("pointerleave",()=>{const g=document.activeElement;g instanceof HTMLElement&&r.contains(g)&&g.blur()}),a.type="checkbox",l.appendChild(a),l.appendChild(document.createTextNode("Default")),l.title="Display first 3 dimensions",l.classList.add("neuroglancer-display-dimensions-widget-default"),a.addEventListener("change",()=>{this.updateDefault()}),o.appendChild(l),this.registerDisposer(e),this.registerDisposer(n),this.registerDisposer(t.changed.add(this.scheduleUpdateView)),this.registerDisposer(e.changed.add(this.scheduleUpdateView));const u=this.registerDisposer(new mn(r,X0));u.allShortcutsAreGlobal=!0,this.registerDisposer(new fn(r,X0)),X(o,"cancel",()=>{this.updateView();const g=document.activeElement;g instanceof HTMLElement&&r.contains(g)&&g.blur()});const{depthGridContainer:h}=this;h.classList.add("neuroglancer-depth-range-widget-grid"),r.appendChild(h);const f=document.createElement("label"),m=document.createElement("input");m.type="checkbox",f.classList.add("neuroglancer-depth-range-relative-checkbox-label"),m.classList.add("neuroglancer-depth-range-relative-checkbox"),f.appendChild(m),f.appendChild(document.createTextNode("Zoom-relative")),m.addEventListener("change",()=>{const g=m.checked;let v=this.depthRange.value;g!==v<0&&(g?v=-v/this.zoom.value:v=-v*this.zoom.value,this.depthRange.value=v)}),f.title="Depth range is multiplied by scale",r.appendChild(f),X(h,"adjust-via-wheel",g=>{const v=g.detail,{deltaY:y}=v;if(y===0)return;const S=this.depthRange.value;this.depthRange.value=S*2**Math.sign(y)}),this.registerDisposer((0,A.no)((g,v,{factors:y})=>{Ae(h);const{displayRank:S,globalDimensionNames:x,displayDimensionIndices:b,displayDimensionUnits:E,displayDimensionScales:C,canonicalVoxelFactors:k}=v,T=[],L=()=>{m.checked=this.depthRange.value<0;let P=this.depthRange.value;P<0&&(P*=-this.zoom.value);for(const V of T){const{input:$}=V;$.value=Ci(P*V.scale,V.unit,{precision:2,elide1:!1}),Ft($)}},_=P=>{const V=Zs(P.input.value);if(V===void 0||V.unit!==P.unit)return!1;let $=V.scale/P.scale;return this.depthRange.value<0&&($=-$/this.zoom.value),this.depthRange.value=$,!0};for(let P=0;P<S;++P){const V=b[P],$=x[V],Q=E[P],K=y[V];let ee=T.find(ce=>ce.unit===Q&&ce.factor===K);if(ee===void 0){const ce=document.createElement("div");ce.title="Visible depth range",ce.style.display="contents",h.appendChild(ce);const fe=document.createElement("span");fe.textContent="\xB1",ce.appendChild(fe);const le=document.createElement("input");le.spellcheck=!1,le.autocomplete="off",le.addEventListener("focus",()=>{le.select()}),X(le,"commit",()=>{_(ee)}),le.addEventListener("change",()=>{_(ee)||L()}),le.addEventListener("input",()=>{Ft(le)}),ce.appendChild(le);const ve=document.createElement("span");ve.classList.add("neuroglancer-depth-range-widget-dimension-names"),ce.appendChild(ve),ee={unit:Q,factor:K,dimensionNames:[],input:le,label:ve,scale:C[P]/k[P]},T.push(ee)}ee.dimensionNames.push($)}for(const P of T)P.dimensionNames.length!==S&&(P.label.textContent=P.dimensionNames.join(" "));g.registerDisposer(X(h,"cancel",()=>{L();const P=document.activeElement;P instanceof HTMLElement&&h.contains(P)&&P.blur()}));const R=g.registerCancellable((0,je.t)(L));g.registerDisposer(this.depthRange.changed.add(R)),g.registerDisposer(this.zoom.changed.add(R)),L()},e,this.relativeDisplayScales)),this.updateView()}zoomDimension(e,t){this.updateScaleFactors();const{displayDimensions:n}=this,{relativeDisplayScales:s}=this,{displayDimensionIndices:r}=n.value,o=r[e];if(o===-1)return;const{factors:a}=s.value,l=new Float64Array(a);l[o]*=2**-t,s.setFactors(l)}updateNameValidity(){const{dimensionElements:e}=this,{displayDimensionIndices:t}=this.displayDimensions.value,n=e.map(l=>l.name.value),s=_l(n),r=this.displayDimensions.coordinateSpace.value,{names:o}=r,a=n.length;for(let l=0;l<a;++l){let c=s[l];const d=n[l];let u=-1;d.length===0?c=!0:(u=o.indexOf(d),u===-1&&(c=!1));const h=e[l];h.name.dataset.isValid=c.toString(),h.container.dataset.isModified=(u!==t[l]).toString()}}get displayDimensions(){return this.displayDimensionRenderInfo.displayDimensions}get relativeDisplayScales(){return this.displayDimensionRenderInfo.relativeDisplayScales}updateNames(){const e=this.dimensionElements.map(a=>a.name.value).filter(a=>a.length>0);if(!oo(e))return!1;const{displayDimensions:t}=this.displayDimensionRenderInfo;if(e.length===0)return t.reset(),!0;const n=new Int32Array(3);n.fill(-1);const s=t.coordinateSpace.value,{names:r}=s,o=e.length;for(let a=0;a<o;++a){const l=r.indexOf(e[a]);if(l===-1)return!1;n[a]=l}return(0,z.r1)(n,t.value.displayDimensionIndices)||t.setDimensionIndices(o,n),!0}updateDefault(){this.displayDimensions.default=this.defaultCheckbox.checked}updateScaleFactors(){const{displayDimensions:e}=this,{relativeDisplayScales:t}=this,{displayDimensionIndices:n,displayRank:s}=e.value,{factors:r}=t.value,{dimensionElements:o}=this,a=new Float64Array(r);for(let l=0;l<s;++l){const c=o[l];if(!c.scaleFactorModified)continue;const d=Number(c.scaleFactor.value),u=n[l];!Number.isFinite(d)||d<=0||(a[u]=d)}return(0,z.r1)(a,r)||t.setFactors(a),!0}updateView(){const{dimensionElements:e,displayDimensions:{default:t}}=this,{displayDimensionIndices:n,canonicalVoxelFactors:s,displayDimensionUnits:r,displayDimensionScales:o,globalDimensionNames:a}=this.displayDimensionRenderInfo.value,{factors:l}=this.relativeDisplayScales.value;this.defaultCheckbox.checked=t;const c=this.zoom.value,d=n[0];let u=!0;if(d!==-1){const h=r[0],f=l[d];for(let m=1;m<3;++m){const g=n[m];if(g!==-1&&(r[m]!==h||l[g]!==f)){u=!1;break}}}for(let h=0;h<3;++h){const f=n[h],m=e[h];if(m.name.dataset.isValid=void 0,m.container.dataset.isModified=(f===-1).toString(),f===-1)m.name.value="",m.scale.textContent="",m.scaleFactor.value="";else{m.name.value=a[f];const g=o[h]*c/s[h];if(h===0||!u){const v=Ci(g,r[h],{precision:2,elide1:!1});m.scale.textContent=`${v}/${this.displayUnit}`}else m.scale.textContent="";m.scaleFactor.value=jN(l[f])}Ft(m.name),Ft(m.scaleFactor)}}disposed(){lt(this.element),super.disposed()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class KN{constructor(){this.perspectiveView=new Pe,this.sliceView=new Pe}}const Z0=new Map([["xy",void 0],["xz",w.Yu.rotateX(w.Yu.create(),w.Yu.create(),Math.PI/2)],["yz",w.Yu.rotateY(w.Yu.create(),w.Yu.create(),Math.PI/2)]]),eb="\u25FB",Wu=new Map([["4panel","\u25F1"],["3d",eb]]);function XN(i,e){let t;return e===void 0?t=i.navigationState.addRef():t=new fs(new ps(i.navigationState.pose.position.addRef(),i.navigationState.pose.displayDimensionRenderInfo.addRef(),hs.makeRelative(i.navigationState.pose.orientation,e)),i.navigationState.zoomFactor.addRef(),i.navigationState.depthRange.addRef()),new Qo(i.chunkManager,i.layerManager,t,i.wireFrame)}function qr(i,e){return XN(i,Z0.get(e))}function ZN(i){return new Map([["xy",qr(i,"xy")],["xz",qr(i,"xz")],["yz",qr(i,"yz")]])}function tb(i){return{crossSectionBackgroundColor:i.crossSectionBackgroundColor,perspectiveViewBackgroundColor:i.perspectiveViewBackgroundColor,selectionDetailsState:i.selectionDetailsState,mouseState:i.mouseState,layerManager:i.layerManager,showAxisLines:i.showAxisLines,wireFrame:i.wireFrame,enableAdaptiveDownsampling:i.enableAdaptiveDownsampling,visibleLayerRoles:i.visibleLayerRoles,selectedLayer:i.selectedLayer,visibility:i.visibility,scaleBarOptions:i.scaleBarOptions}}function Hu(i){const{viewer:e}=i;return{...tb(e),navigationState:e.perspectiveNavigationState,inputEventMap:e.inputEventBindings.perspectiveView,orthographicProjection:i.specification.orthographicProjection,showScaleBar:e.showScaleBar,rpc:e.chunkManager.rpc}}function ll(i){return{...tb(i),navigationState:i.navigationState,inputEventMap:i.inputEventBindings.sliceView}}function Ys(i,e){const{navigationState:t}=e;e.element.appendChild(i.registerDisposer(new qN(t.pose.displayDimensionRenderInfo.addRef(),t.zoomFactor,t.depthRange.addRef(),e instanceof al?"px":"vh")).element)}function Qs(i,e,t){const n=document.createElement("div");n.className="neuroglancer-data-panel-layout-controls",i.registerDisposer(()=>lt(n));for(let s=0;s<2;++s){const r=t[Math.min(t.length-1,s)];i.registerDisposer(X(e.element,s===0?"toggle-layout":"toggle-layout-alternative",o=>{i.container.name=r,o.stopPropagation()}))}for(const s of t){const r=document.createElement("button"),o=document.createElement("div");r.appendChild(o),o.textContent=Wu.get(s),r.title=`Switch to ${s} layout.`,r.addEventListener("click",()=>{i.container.name=s}),n.appendChild(r)}e.element.appendChild(n)}function eO(i,e){const t=new Qo(i.chunkManager,i.layerManager,e.navigationState.addRef(),i.wireFrame),n=()=>{const{width:{value:s},height:{value:r}}=e;t.projectionParameters.setViewport({width:s,height:r,logicalWidth:s,logicalHeight:r,visibleLeftFraction:0,visibleTopFraction:0,visibleWidthFraction:1,visibleHeightFraction:1})};return t.registerDisposer(e.width.changed.add(n)),t.registerDisposer(e.height.changed.add(n)),n(),t}function Ju(i,e,t){const n=new Map;(()=>{const r=new Set;for(const o of t.values()){if(r.add(o),n.has(o))continue;const a=eO(i,o);e.sliceViews.set(a,!0),n.set(o,a)}for(const[o,a]of n)r.has(o)||e.sliceViews.delete(a)})()}class tO extends D.O8{constructor(e,t,n,s){super(),this.container=e,this.rootElement=t,this.viewer=n;const r=ZN(n),{display:o}=n,a={...Hu(e),showSliceViews:n.showPerspectiveSliceViews,showSliceViewsCheckbox:!0},l={...ll(n),showScaleBar:n.showScaleBar},c={...ll(n),showScaleBar:new rt(!1,!1)},d=(h,f,m,g)=>{const v=this.registerDisposer(new al(o,f,r.get(h),m));return g&&Ys(this,v),Qs(this,v,[h,`${h}-3d`]),v},u=[on(1,es("column",[on(1,es("row",[on(1,h=>{d("xy",h,l,!0)}),on(1,h=>{d("xz",h,c,!1)})])),on(1,es("row",[on(1,h=>{const f=this.registerDisposer(new zu(o,h,a));for(const m of r.values())f.sliceViews.set(m.addRef(),!1);Ys(this,f),Ju(n,f,s),Qs(this,f,["3d"])}),on(1,h=>{d("yz",h,c,!1)})]))]))];es("row",u)(t)}disposed(){Ae(this.rootElement),super.disposed()}}class nO extends D.O8{constructor(e,t,n,s,r,o){super(),this.container=e,this.rootElement=t,this.viewer=n,this.direction=s;const a=qr(n,r),{display:l}=n,c={...Hu(e),showSliceViews:n.showPerspectiveSliceViews,showSliceViewsCheckbox:!0},d={...ll(n),showScaleBar:n.showScaleBar};on(1,es(s,[on(1,u=>{const h=this.registerDisposer(new al(l,u,a,d));Ys(this,h),Qs(this,h,[r,"4panel"])}),on(1,u=>{const h=this.registerDisposer(new zu(l,u,c));h.sliceViews.set(a.addRef(),!1),Ju(n,h,o),Ys(this,h),Qs(this,h,["3d","4panel"])})]))(t)}disposed(){Ae(this.rootElement),super.disposed()}}class iO extends D.O8{constructor(e,t,n,s){super(),this.container=e,this.rootElement=t,this.viewer=n;const r=qr(n,s),o={...ll(n),showScaleBar:n.showScaleBar};es("row",[on(1,a=>{const l=this.registerDisposer(new al(n.display,a,r,o));Ys(this,l),Qs(this,l,["4panel",`${s}-3d`])})])(t)}disposed(){Ae(this.rootElement),super.disposed()}}class sO extends D.O8{constructor(e,t,n,s){super(),this.container=e,this.rootElement=t,this.viewer=n;const r={...Hu(e),showSliceViews:new rt(!1,!1)};es("row",[on(1,o=>{const a=this.registerDisposer(new zu(n.display,o,r));Ju(n,a,s),Ys(this,a),Qs(this,a,["4panel"])})])(t)}disposed(){Ae(this.rootElement),super.disposed()}}const ju=new Map([["4panel",{factory:(i,e,t,n)=>new tO(i,e,t,n)}],["3d",{factory:(i,e,t,n)=>new sO(i,e,t,n)}]]);for(const i of Z0.keys()){ju.set(i,{factory:(t,n,s)=>new iO(t,n,s,i)});const e=`${i}-3d`;Wu.set(i,eb),Wu.set(e,"\u25EB"),ju.set(e,{factory:(t,n,s,r)=>new nO(t,n,s,"row",i,r)})}function nb(i){const e=ju.get(i);if(e===void 0)throw new Error(`Invalid layout name: ${JSON.stringify(i)}.`);return e}function rO(i){return nb(i),i}class oO extends D.O8{constructor(e){super(),this.width=new A.DN(1e3,p.We),this.height=new A.DN(1e3,p.We),this.changed=new j.IY,this.position=new Gp(e.position.addRef()),this.position.changed.add(this.changed.dispatch),this.orientation=new oc(e.pose.orientation.addRef()),this.orientation.changed.add(this.changed.dispatch),this.width.changed.add(this.changed.dispatch),this.height.changed.add(this.changed.dispatch),this.scale=new ac(e.zoomFactor.addRef(),e.zoomFactor.displayDimensionRenderInfo.addRef()),this.scale.changed.add(this.changed.dispatch),this.navigationState=this.registerDisposer(new fs(new ps(this.position.value,e.pose.displayDimensionRenderInfo.addRef(),this.orientation.value),this.scale.value,e.depthRange.addRef()))}restoreState(e){(0,p.Rf)(e),Mt(e,"width",this.width),Mt(e,"height",this.height),Mt(e,"position",pr(this.position)),Mt(e,"orientation",this.orientation),Mt(e,"scale",this.scale),Mt(e,"zoom",pr(this.scale))}reset(){this.width.reset(),this.height.reset(),this.position.reset(),this.orientation.reset(),this.scale.reset()}toJSON(){return{width:this.width.toJSON(),height:this.height.toJSON(),position:this.position.toJSON(),orientation:this.orientation.toJSON(),scale:this.scale.toJSON()}}}class aO extends Yl{constructor(e){super((t,n)=>t.registerDisposer(t.registerDisposer(n).changed.add(this.changed.dispatch))),this.parentNavigationState=e,this.registerDisposer(e)}restoreState(e){(0,p.Rf)(e);for(const t of Object.keys(e)){const n=new oO(this.parentNavigationState);try{this.set(t,n.addRef()),n.restoreState(e[t])}finally{n.dispose()}}}reset(){this.clear()}toJSON(){if(this.size===0)return;const e={};for(const[t,n]of this)e[t]=n.toJSON();return e}}class lO extends D.O8{constructor(e,t){super(),this.changed=new j.IY,this.orthographicProjection=new rt(!1),this.type=new A.DN(t,rO),this.type.changed.add(this.changed.dispatch),this.crossSections=this.registerDisposer(new aO(e.addRef())),this.crossSections.changed.add(this.changed.dispatch),this.orthographicProjection.changed.add(this.changed.dispatch),this.registerDisposer(e)}reset(){this.crossSections.clear(),this.orthographicProjection.reset(),this.type.reset()}restoreState(e){this.crossSections.clear(),this.orthographicProjection.reset(),typeof e=="string"?this.type.restoreState(e):((0,p.Rf)(e),(0,p.cQ)(e,"type",t=>this.type.restoreState(t)),(0,p.cQ)(e,"orthographicProjection",t=>this.orthographicProjection.restoreState(t)),(0,p.cQ)(e,"crossSections",t=>t!==void 0&&this.crossSections.restoreState(t)))}toJSON(){const{type:e,crossSections:t,orthographicProjection:n}=this,s=n.toJSON();return t.size===0&&s===void 0?e.value:{type:e.value,crossSections:t.toJSON(),orthographicProjection:s}}}class cO extends D.O8{constructor(e,t){super(),this.viewer=e,this.element=document.createElement("div"),this.specification=this.registerDisposer(new lO(this.viewer.navigationState.addRef(),t)),this.element.style.flex="1";const n=this.registerCancellable((0,xe.A)(()=>this.updateLayout(),0));this.specification.type.changed.add(n),X(this.element,"toggle-orthographic-projection",()=>this.specification.orthographicProjection.toggle()),this.registerDisposer(this.viewer.display.updateStarted.add(()=>n.flush())),n()}get name(){return this.specification.type.value}set name(e){this.specification.type.value=e}get changed(){return this.specification.changed}toJSON(){return this.specification.toJSON()}restoreState(e){this.specification.restoreState(e)}reset(){this.specification.reset()}disposeLayout(){const{layout:e}=this;e!==void 0&&(e.dispose(),this.layout=void 0)}updateLayout(){this.disposeLayout(),this.layout=nb(this.name).factory(this,this.element,this.viewer,this.specification.crossSections)}disposed(){this.disposeLayout(),super.disposed()}}const dO=typeof STATE_SERVERS<"u"&&Object.keys(STATE_SERVERS).length>0;class uO extends D.O8{constructor(e){if(super(),this.element=document.createElement("div"),this.button=_e({text:"Share",title:"Share State"}),typeof STATE_SERVERS>"u")throw new Error("Cannot construct StateSare without defining STATE_SERVERS");if(Object.keys(STATE_SERVERS).length>1){const t=document.createElement("select");t.style.marginRight="5px",this.registerDisposer(e.selectedStateServer.changed.add(()=>{const n=e.selectedStateServer.value;Object.values(STATE_SERVERS).map(s=>s.url).includes(n)&&(t.value=n)})),this.registerEventListener(t,"change",()=>{e.selectedStateServer.value=t.value});for(const[n,s]of Object.entries(STATE_SERVERS)){const r=document.createElement("option");r.textContent=n,r.value=s.url,r.selected=!!s.default,t.appendChild(r)}this.element.appendChild(t),this.selectStateServerElement=t}this.element.appendChild(this.button),this.registerEventListener(this.button,"click",()=>{const t=this.selectStateServerElement?this.selectStateServerElement.value:Object.values(STATE_SERVERS)[0].url,n=new URL(t).protocol,{url:s,credentialsProvider:r}=bn(t,_0);Se.forPromise(rn(r,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.state.toJSON())},Me.cj).then(o=>{const a=new URL(o).protocol,l=o.substring(a.length),c=`${window.location.origin}/#!${n}${l}`;navigator.clipboard.writeText(c).then(()=>{Se.showTemporaryMessage("Share link copied to clipboard")})}).catch(()=>{Se.showTemporaryMessage("Could not access state server.",4e3)}),{initialMessage:`Posting state to ${t}.`,delay:!0,errorPrefix:""})})}disposed(){this.element.remove(),super.disposed()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function hO(i){return i.startsWith("key")?i.substring(3):i.startsWith("digit")||i.startsWith("arrow")?i.substring(5):i}function pO(i){return i.split("+").map(hO).join("+")}const fO={...Fi,side:"left",row:1};class gO{constructor(){this.location=new ci(fO)}get changed(){return this.location.changed}toJSON(){return(0,p.Zu)(this.location.toJSON())}reset(){this.location.reset()}restoreState(e){this.location.restoreState(e)}}class mO extends Ji{constructor(e,t,n,s,r){super(e,t.location),this.bindings=n,this.toolBinder=r,this.scroll=document.createElement("div"),this.addTitleBar({title:"Help"});const o=document.createElement("div");o.classList.add("neuroglancer-help-body");const{scroll:a}=this;a.classList.add("neuroglancer-help-scroll-container"),o.appendChild(a),this.addBody(o);const l=this.registerCancellable((0,je.t)(()=>this.updateView()));this.registerDisposer(r.changed.add(l)),this.registerDisposer(s.layersChanged.add(l)),this.updateView()}updateView(){const{scroll:e,bindings:t,toolBinder:n}=this;if(Ae(e),typeof{tag:"v2.40.1",url:"https://github.com/google/neuroglancer/commit/23218f95a6e8d5f614e00f0ba964eecc3ec7e9dc",timestamp:"Tue Jul 23 20:14:46 UTC 2024"}<"u"){const d=document.createElement("h2");d.textContent="Build info";const u=document.createElement("div");u.classList.add("neuroglancer-build-info");const h=document.createElement("a"),{tag:f,url:m,timestamp:g}={tag:"v2.40.1",url:"https://github.com/google/neuroglancer/commit/23218f95a6e8d5f614e00f0ba964eecc3ec7e9dc",timestamp:"Tue Jul 23 20:14:46 UTC 2024"};if(h.textContent=f,h.target="_blank",m!==void 0&&(h.href=m),e.appendChild(d),u.appendChild(h),g!==void 0){const v=document.createElement("div");v.classList.add("neuroglancer-build-timestamp");const y=Intl.DateTimeFormat("en",{hour12:!1,dateStyle:"medium",timeStyle:"long"}).format(new Date(g));v.textContent=`Built at ${y}`,u.append(v)}e.appendChild(u)}const s=new Map;function r(d,u){for(const h of d.parents)h.label!==void 0?o(h.label,h):r(h,u);for(const[h,f]of d.bindings.entries()){const m=h.indexOf(":"),g=h.substring(m+1);u.set(g,f.action)}}function o(d,u){if(s.has(u))return;const h={label:d,entries:new Map};r(u,h.entries),s.set(u,h)}for(const[d,u]of t)o(d,u);const a=(d,u)=>{const h=document.createElement("h2");h.textContent=d,e.appendChild(h);for(const[f,m]of u){const g=document.createElement("div");g.className="dt",g.textContent=pO(f);const v=document.createElement("div");v.className="dd",v.textContent=m,e.appendChild(g),e.appendChild(v)}},l=new Map;for(const[d,u]of n.bindings)if(u.context instanceof Ln){let h=l.get(u.context);h===void 0&&(h=[],l.set(u.context,h)),h.push([`shift+key${d.toLowerCase()}`,u.description])}const c=Array.from(l.entries());c.length>0&&(c[0][0].manager.root.layerManager.updateNonArchivedLayerIndices(),c.sort((d,u)=>d[0].managedLayer.nonArchivedLayerIndex-u[0].managedLayer.nonArchivedLayerIndex));for(const[d,u]of c)u.sort(),a(`Tool bindings for layer ${d.managedLayer.nonArchivedLayerIndex+1}: ${d.managedLayer.name}`,u);for(const d of s.values())a(d.label,d.entries)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function vO(i,e){i.style.display="block";const{offsetWidth:t,offsetHeight:n}=i,s=document.documentElement.clientWidth,r=document.documentElement.clientHeight,o=document.documentElement.scrollLeft+Math.min(s-t,e.clientX),a=document.documentElement.scrollTop+Math.min(r-n,e.clientY);i.style.left=o+"px",i.style.top=a+"px"}class yO extends D.O8{constructor(e){super(),this.element=document.createElement("div"),this.parentDisposers=new Map,this.disabledValue=!1,this.opened=new j.IY,this.closed=new j.IY;const{element:t}=this;t.className="neuroglancer-context-menu",t.style.display="none",t.tabIndex=-1,document.body.appendChild(t),e!==void 0&&this.registerParent(e)}get disabled(){return this.disabledValue}set disabled(e){this.disabledValue!==e&&(this.disabledValue=e,e&&this.hide())}get open(){return this.menuDisposer!==void 0}registerParent(e){const{parentDisposers:t}=this;t.has(e)||t.set(e,(0,D.K6)(e,"contextmenu",n=>{this.show(n),n.stopPropagation(),n.preventDefault()}))}show(e){if(this.disabledValue)return;this.hide();const{element:t}=this,n=(0,D.K6)(document,"mousedown",o=>{o.target instanceof Node&&!t.contains(o.target)&&this.hide()},!0),s=(0,D.K6)(document,"keydown",o=>{o.code==="Escape"&&this.hide()},!0),r=()=>{s(),n(),t.style.display="none"};this.opened.dispatch(),vO(t,e),this.menuDisposer=r}unregisterParent(e){const{parentDisposers:t}=this,n=t.get(e);n!==void 0&&(n(),t.delete(e))}disposed(){const{parentDisposers:e}=this;for(const t of e.values())t();e.clear(),lt(this.element)}hide(){this.menuDisposer!==void 0&&(this.menuDisposer(),this.menuDisposer=void 0,this.closed.dispatch())}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ib(i){return Ee(new TextEncoder().encode(i))}function SO(i){return new TextDecoder().decode(Ge(i))}function e2(i,e){return i+ib(JSON.stringify(e))}function bO(i,e){if(i.startsWith(e))try{const t=SO(i.substring(e.length));return JSON.parse(t)}catch{return}}function wO(i,e){return i+ib(JSON.stringify(e))}function CO(i,e){for(const t of i){const n=bO(t,e);if(n!==void 0)return{parameters:n,dragType:t}}}let sb;function Yu(i,e){return i.dataTransfer.dropEffect=e,sb=e,e}function Qu(){return sb}function xO(i){return i.draggable=!0,(0,D.K6)(i,"dragstart",e=>{e.stopPropagation(),e.preventDefault()})}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const rb="neuroglancer-layer\0";let an;function ob(i,e){i.dataTransfer.setData(wO(rb,e.layers.map(s=>({name:s.name,visible:s.visible}))),JSON.stringify({layers:e.layers.map(s=>s.toJSON()),layout:e.layoutSpec})),an!==void 0&&an.disposer();let t;const n=()=>{e.manager.unregisterDisposer(n);for(const s of e.layers)s.dispose();e.manager.dispose(),an===t&&(an=void 0)};an=t={manager:e.manager.addRef(),layers:e.layers.map(s=>s.addRef()),layoutSpec:e.layoutSpec,isLayerListPanel:e.isLayerListPanel??!1,disposer:n}}function cl(i="none"){if(an!==void 0){if(i==="move"){const e=new Set(an.layers);an.manager.layerManager.filter(t=>!e.has(t))}an.disposer()}}function dl(i){return CO(i.dataTransfer.types,rb)}function ab(i){if(an!==void 0&&an.manager.rootLayers===i.rootLayers)return an}class lb{initializeExternalLayers(e){const{dragType:t}=this;if(t!==void 0)try{const{layers:n,layout:s}=JSON.parse(e.dataTransfer.getData(t));if(!Array.isArray(n)||this.numSourceLayers!==n.length)throw new Error("Invalid layer drop data");this.layoutSpec=s;for(const[r,o]of this.layers)RT(r,n[o])}catch{return!1}return!0}updateArchiveStates(e){const{targetIsLayerListPanel:t}=this,n=e.dataTransfer.dropEffect;for(const s of this.layers.keys()){let r=t;t&&!s.archived&&n!=="copy"&&this.sourceIsLayerListPanel&&(r=!1),(s.archived!==r||r&&s.visible)&&(s.archived=r,r&&(s.visible=!1),s.layerChanged.dispatch())}}get method(){return this.sourceManager!==void 0?this.manager===this.sourceManager&&this.sourceIsLayerListPanel===this.targetIsLayerListPanel?"move":"link":"copy"}compatibleWithMethod(e){return this.method===e?!0:this.forceCopy&&e!=="copy"?!1:!this.moveSupported&&e==="move"}}function cb(i,e,t){let n;i.shiftKey?n="copy":i.ctrlKey&&t?n="move":n=e;let s="";const r=o=>{s!==""&&(s+=", "),s+=o};return e!=="none"&&n!==e&&(i.shiftKey?r(`release SHIFT to ${e}`):r(`release CONTROL to ${e}`)),n!=="copy"&&r("hold SHIFT to copy"),n!=="move"&&t&&e!=="move"&&r("hold CONTROL to move"),{dropEffect:n,dropEffectMessage:s}}function db(i,e,t,n){const s=ab(e);let r=!1,o;return s===void 0?o="copy":n?(s.isLayerListPanel||(r=!0),o="link"):s.manager===e&&s.isLayerListPanel===t?(o="move",r=!0):t?o="none":(s.isLayerListPanel||(r=!0),o="link"),cb(i,o,r)}function EO(i,e,t,n){const s=db(i,e,t,n);return Yu(i,s.dropEffect),s}function qu(i,e,t){const{forceCopy:n,newTarget:s,isLayerListPanel:r=!1}=t,o=ab(e);if(!n&&o!==void 0){const l=!s&&o.manager===e&&(o.isLayerListPanel===r||o.isLayerListPanel),c=new lb;return c.manager=e,c.numSourceLayers=o.layers.length,c.sourceManager=o.manager,c.targetIsLayerListPanel=r,c.sourceIsLayerListPanel=o.isLayerListPanel,c.moveSupported=l,c.layers=new Map,c.forceCopy=!1,c.layoutSpec=o.layoutSpec,l?o.layers.forEach((d,u)=>{c.layers.set(d,u)}):o.layers.forEach((d,u)=>{(s||!e.layerManager.has(d))&&c.layers.set(d.addRef(),u)}),c}const a=dl(i);if(a!==void 0)try{const l=(0,p.$v)(a.parameters,(d,u)=>{const h=(0,p.cQ)(d,"name",p.zr);let f=(0,p.cQ)(d,"visible",p.aO);const m=new Uc(h,e);return r&&(f=!1),m.visible=f,m.archived=r,[m,u]}),c=new lb;return c.numSourceLayers=l.length,c.targetIsLayerListPanel=r,c.sourceIsLayerListPanel=!1,c.sourceManager=void 0,c.moveSupported=!1,c.forceCopy=o!==void 0,c.manager=e,c.dragType=a.dragType,c.layers=new Map(l),c}catch{}}function Ku(i,e){return i.moveSupported?!1:(i.manager.layerManager.filter(t=>!i.layers.has(t)),e!==void 0&&i.layers.has(e))}function ul(i,e,t,n=!1){function s(r,o){let a=i.dropLayers;const{dropEffect:l,dropEffectMessage:c}=o?db(r,i.manager,n,!1):{dropEffect:Qu(),dropEffectMessage:""};if(l===void 0)return;Yu(r,l);let d=!0;if(!(a!==void 0&&!a.compatibleWithMethod(l)&&(i.dropLayers=void 0,Ku(a,t)))){if(a===void 0){if(a=i.dropLayers=qu(r,i.manager,{forceCopy:l==="copy",newTarget:!1,isLayerListPanel:n}),a===void 0)return;d=a.method==="move"}if(t!==void 0&&a.layers.has(t))return{dropLayers:a,dropEffect:l,dropEffectMessage:c};if(d){const{layerManager:u}=i.manager,h=new Set;let f=Number.POSITIVE_INFINITY;const m=u.managedLayers=u.managedLayers.filter((v,y)=>a.layers.has(v)?(f===Number.POSITIVE_INFINITY&&(f=y),h.add(v),!1):!0);let g;t!==void 0?(g=m.indexOf(t),f<=g&&++g):g=m.length;for(const v of a.layers.keys())h.has(v)||a.layers.delete(v);m.splice(g,0,...a.layers.keys()),u.layersChanged.dispatch()}else{let u;t!==void 0&&(u=i.manager.layerManager.managedLayers.indexOf(t));for(const h of a.layers.keys())i.manager.add(h,u)}return{dropLayers:a,dropEffect:l,dropEffectMessage:c}}}e.addEventListener("dragenter",r=>{s(r,!0)!==void 0?r.preventDefault():Dt(i.element,"drop")}),e.addEventListener("drop",r=>{r.preventDefault(),i.dragEnterCount=0,Dt(i.element,"drop");const o=s(r,!1)?.dropLayers;if(i.dropLayers=void 0,o!==void 0){if(!o.initializeExternalLayers(r)){Ku(o);return}o.updateArchiveStates(r),cl(o.method==="move"?void 0:r.dataTransfer.dropEffect)}}),e.addEventListener("dragover",r=>{const o=s(r,!0);if(o===void 0){Dt(i.element,"drop");return}const{dropLayers:a,dropEffect:l,dropEffectMessage:c}=o,d=a.layers.size;let u="";const h=a.numSourceLayers===1?"":"s",f=a.numSourceLayers;if(l==="none")u=`Cannot link dragged layer${h} here`;else{const m=f===d?`${f}`:`${d}/${f}`;u=`Drop to ${l} ${m} layer${h}`}c&&(u+=` (${c})`),Sn(i.element,"drop",u),r.preventDefault(),r.stopPropagation()})}function ub(i,e,t,n){e.draggable=!0,e.addEventListener("dragstart",s=>{Sn(e,"drag","Drag layer to another layer bar/panel (including in another Neuroglancer window), or to the left/top/right/bottom edge of a layer group"),ob(s,{manager:i.manager,layers:[t],layoutSpec:n.getLayoutSpec(),isLayerListPanel:n.isLayerListPanel}),s.stopPropagation()}),e.addEventListener("dragend",()=>{Dt(e,"drag"),cl()})}function hb(i){i.element.addEventListener("dragenter",()=>{++i.dragEnterCount}),i.element.addEventListener("dragleave",()=>{if(--i.dragEnterCount!==0)return;Dt(i.element,"drop");const{dropLayers:e}=i;e!==void 0&&(Ku(e),i.manager.layerManager.layersChanged.dispatch(),i.dropLayers=void 0)})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class TO extends D.O8{constructor(e,t){super(),this.layer=e,this.panel=t,this.element=document.createElement("div"),this.layerNumberElement=document.createElement("div"),this.labelElement=document.createElement("div"),this.visibleProgress=document.createElement("div"),this.prefetchProgress=document.createElement("div"),this.labelElementText=document.createTextNode(""),this.valueElement=document.createElement("div"),this.maxLength=0,this.prevValueText="";const{element:n,labelElement:s,layerNumberElement:r,valueElement:o,visibleProgress:a,prefetchProgress:l,labelElementText:c}=this;n.className="neuroglancer-layer-item neuroglancer-noselect",n.appendChild(a),n.appendChild(l),s.className="neuroglancer-layer-item-label",s.appendChild(c),a.className="neuroglancer-layer-item-visible-progress",l.className="neuroglancer-layer-item-prefetch-progress",r.className="neuroglancer-layer-item-number",o.className="neuroglancer-layer-item-value";const d=document.createElement("div");d.className="neuroglancer-layer-item-value-container";const u=document.createElement("div");u.className="neuroglancer-layer-item-button-container";const h=md();h.title="Remove layer from this layer group",h.addEventListener("click",g=>{this.panel.layerManager===this.panel.manager.rootLayers?this.layer.setArchived(!0):this.layer.containers.size>2?this.panel.layerManager.removeManagedLayer(this.layer):this.layer.setArchived(!0),g.stopPropagation()});const f=Yn();f.title="Delete this layer",f.addEventListener("click",g=>{Ps(this.layer),g.stopPropagation()}),n.appendChild(r),d.appendChild(o),d.appendChild(u),u.appendChild(h),u.appendChild(f),n.appendChild(s),n.appendChild(d);const m=this.registerDisposer(new bs(e.localPosition,e.localCoordinateSpaceCombiner,{copyButton:!1,velocity:e.localVelocity,getToolBinder:()=>e.layer?.toolBinder}));n.appendChild(m.element),m.element.addEventListener("click",g=>{g.stopPropagation()}),m.element.addEventListener("dblclick",g=>{g.stopPropagation()}),n.addEventListener("click",g=>{g.ctrlKey?t.selectedLayer.toggle(e):g.altKey?e.pickEnabled=!e.pickEnabled:e.setVisible(!e.visible)}),n.addEventListener("contextmenu",g=>{t.selectedLayer.layer=e,t.selectedLayer.visible=!0,g.stopPropagation(),g.preventDefault()}),ub(t,n,e,{getLayoutSpec:()=>t.getLayoutSpecForDrag()}),ul(this.panel,n,this.layer)}update(){const{layer:e,element:t}=this;this.labelElementText.textContent=e.name,t.dataset.visible=e.visible.toString(),t.dataset.selected=(e===this.panel.selectedLayer.layer).toString(),t.dataset.pick=e.pickEnabled.toString();let n=`Click to ${e.visible?"hide":"show"}, control+click to show side panel`;e.supportsPickOption&&(n+=`, alt+click to ${e.pickEnabled?"disable":"enable"} spatial object selection`),n+=", drag to move, shift+drag to copy",t.title=n}disposed(){this.element.remove(),super.disposed()}}class DO extends D.O8{constructor(e,t,n){super(),this.layerGroupViewer=e,this.getLayoutSpecForDrag=t,this.showLayerHoverValues=n,this.layerWidgets=new Map,this.element=document.createElement("div"),this.layerUpdateNeeded=!0,this.valueUpdateNeeded=!1,this.layerWidgetInsertionPoint=document.createElement("div"),this.positionWidget=this.registerDisposer(new bs(this.viewerNavigationState.position.value,this.manager.root.coordinateSpaceCombiner,{velocity:this.viewerNavigationState.velocity.velocity,getToolBinder:()=>this.layerGroupViewer.toolBinder})),this.dragEnterCount=0,this.scheduleUpdate=this.registerCancellable((0,je.t)(()=>this.update()));const{element:s,manager:r,selectedLayer:o}=this;s.className="neuroglancer-layer-panel",this.registerDisposer(r.layerSelectedValues.changed.add(()=>{this.handleLayerValuesChanged()})),this.registerDisposer(r.layerManager.layersChanged.add(()=>{this.handleLayersChanged()})),this.registerDisposer(o.changed.add(()=>{this.handleLayersChanged()})),this.registerDisposer(n.changed.add(()=>{this.handleLayerItemValueChanged()})),this.element.dataset.showHoverValues=this.showLayerHoverValues.value.toString(),this.layerWidgetInsertionPoint.style.display="none",this.element.appendChild(this.layerWidgetInsertionPoint);const a=_e({svg:ka,title:"Click to add layer, control+click/right click/\u2318+click to add local annotation layer."});a.classList.add("neuroglancer-layer-add-button");const l=this.dropZone=document.createElement("div");l.className="neuroglancer-layer-panel-drop-zone";const c=u=>{if(u.ctrlKey||u.metaKey||u.type==="contextmenu"){const h=Mg(this.manager,"annotation",{type:"annotation",source:"local://annotations"});this.manager.add(h),this.selectedLayer.layer=h,this.selectedLayer.visible=!0}else this.addLayerMenu()};this.registerEventListener(a,"click",c),this.registerEventListener(a,"contextmenu",c),s.appendChild(a),s.appendChild(l),this.registerDisposer(xO(a)),s.appendChild(this.positionWidget.element);const d=()=>{const u=this.viewerNavigationState.position.link.value;this.positionWidget.element.style.display=u===xo.LINKED?"none":""};this.registerDisposer(this.viewerNavigationState.position.link.changed.add(d)),d(),this.update(),this.updateChunkStatistics(),hb(this),ul(this,l,void 0),this.registerDisposer(this.display.updateStarted.add(()=>this.updateLayers())),this.registerDisposer(r.chunkManager.layerChunkStatisticsUpdated.add(this.registerCancellable((0,je.t)(()=>this.updateChunkStatistics()))))}get layerManager(){return this.manager.layerManager}get manager(){return this.layerGroupViewer.layerSpecification}get display(){return this.layerGroupViewer.display}get selectedLayer(){return this.layerGroupViewer.selectedLayer}get viewerNavigationState(){return this.layerGroupViewer.viewerNavigationState}disposed(){this.layerWidgets.forEach(e=>e.dispose()),this.layerWidgets=void 0,lt(this.element),super.disposed()}handleLayersChanged(){this.layerUpdateNeeded=!0,this.handleLayerValuesChanged()}handleLayerValuesChanged(){this.valueUpdateNeeded||(this.valueUpdateNeeded=!0,this.scheduleUpdate())}handleLayerItemValueChanged(){this.element.dataset.showHoverValues=this.showLayerHoverValues.value.toString()}update(){if(this.valueUpdateNeeded=!1,this.updateLayers(),this.showLayerHoverValues.value===!1)return;const e=this.manager.layerSelectedValues;for(const[t,n]of this.layerWidgets){const s=t.layer;let r="";if(s!==null){const o=e.get(s);if(o!==void 0){const{value:a}=o;a!==void 0&&(r=""+a)}}if(r!==n.prevValueText){if(n.prevValueText=r,r.length>n.maxLength){const o=n.maxLength=r.length;n.valueElement.style.width=`${o}ch`}n.valueElement.textContent=r}}}updateChunkStatistics(){for(const[e,t]of this.layerWidgets){let n=0,s=0,r=0,o=0;const a=e.layer;if(a!==null)for(const{layerChunkProgressInfo:l}of a.renderLayers)n+=l.numVisibleChunksNeeded,s+=l.numVisibleChunksAvailable,r+=l.numPrefetchChunksNeeded,o+=l.numPrefetchChunksAvailable;t.visibleProgress.style.width=`${s/Math.max(1,n)*100}%`,t.prefetchProgress.style.width=`${o/Math.max(1,r)*100}%`}}updateLayers(){if(!this.layerUpdateNeeded)return;this.layerUpdateNeeded=!1;const e=this.element,t=new Set;let n=this.layerWidgetInsertionPoint.nextElementSibling;this.manager.rootLayers.updateNonArchivedLayerIndices();for(const s of this.manager.layerManager.managedLayers){if(s.archived&&!this.dropLayers?.layers.has(s))continue;t.add(s);let r=this.layerWidgets.get(s);const o=s.nonArchivedLayerIndex;r===void 0&&(r=new TO(s,this),this.layerWidgets.set(s,r)),r.layerNumberElement.textContent=""+(1+o),r.update();const{element:a}=r;a!==n&&e.insertBefore(r.element,n),n=a.nextElementSibling}for(const[s,r]of this.layerWidgets)t.has(s)||(this.layerWidgets.delete(s),r.dispose())}addLayerMenu(){$g(this.manager,this.selectedLayer)}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function pb(i,e){const t=(0,D.K6)(i,"drop",o=>{if(o.preventDefault(),o.dataTransfer.types.indexOf(Ao)!==-1){o.stopPropagation();const a=(0,p.Rf)(JSON.parse(o.dataTransfer.getData(Ao))),l=(0,p.cQ)(a,"dimensions",Bl),c=(0,p.cQ)(a,"position",f=>(0,p.$v)(f,p.zo));if(c.length!==l.length)throw new Error("length mismatch between position and dimensions");const d=c.length,{coordinateSpace:{value:{names:u}},value:h}=e;for(let f=0;f<d;++f){const m=u.indexOf(l[f]);m!==-1&&(h[m]=c[f])}e.changed.dispatch()}}),n=o=>{o.dataTransfer.types.indexOf(Ao)!==-1&&(o.dataTransfer.dropEffect="link",o.preventDefault(),o.stopPropagation())},s=(0,D.K6)(i,"dragenter",n),r=(0,D.K6)(i,"dragover",n);return()=>{s(),r(),t()}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Xu="neuroglancer-layer-group-viewer";function fb(i){return i.dataTransfer.types.indexOf(Xu)!==-1}let On;function IO(i){if(On&&On.viewer.layerSpecification.rootLayers===i.rootLayers)return On.viewer}function RO(i,e){const t=IO(e);let n,s=!1;return t===void 0||t.layerSpecification===t.layerSpecification.root?n="copy":(s=!0,n="move"),cb(i,n,s)}class kO extends D.O8{constructor(e){super(),this.relativeDisplayScales=new _C(e.navigationState.pose.relativeDisplayScales.addRef()),this.displayDimensions=new FC(e.navigationState.pose.displayDimensions.addRef()),this.position=new Gp(e.navigationState.position.addRef()),this.velocity=this.registerDisposer(new OC(e.velocity,this.position.link)),this.crossSectionOrientation=new oc(e.navigationState.pose.orientation.addRef()),this.displayDimensionRenderInfo=this.registerDisposer(new jp(this.relativeDisplayScales.value,this.displayDimensions.value)),this.crossSectionScale=new ac(e.navigationState.zoomFactor.addRef(),this.displayDimensionRenderInfo.addRef()),this.crossSectionDepthRange=new qp(e.navigationState.depthRange.addRef(),this.displayDimensionRenderInfo),this.projectionDepthRange=new qp(e.perspectiveNavigationState.depthRange.addRef(),this.displayDimensionRenderInfo),this.navigationState=this.registerDisposer(new fs(new ps(this.position.value,this.displayDimensionRenderInfo.addRef(),this.crossSectionOrientation.value),this.crossSectionScale.value,this.crossSectionDepthRange.value)),this.projectionOrientation=new oc(e.perspectiveNavigationState.pose.orientation.addRef()),this.projectionScale=new ac(e.perspectiveNavigationState.zoomFactor.addRef(),this.displayDimensionRenderInfo.addRef()),this.projectionNavigationState=this.registerDisposer(new fs(new ps(this.position.value.addRef(),this.displayDimensionRenderInfo.addRef(),this.projectionOrientation.value),this.projectionScale.value,this.projectionDepthRange.value))}copyToParent(){for(const e of[this.relativeDisplayScales,this.displayDimensions,this.position,this.velocity,this.crossSectionOrientation,this.crossSectionScale,this.projectionOrientation,this.projectionScale])e.copyToPeer()}register(e){e.add("dimensionRenderScales",this.relativeDisplayScales),e.add("displayDimensions",this.displayDimensions),e.add("position",pr(this.position)),e.add("velocity",this.velocity),e.add("crossSectionOrientation",this.crossSectionOrientation),e.add("crossSectionScale",this.crossSectionScale),e.add("crossSectionDepth",this.crossSectionDepthRange),e.add("projectionOrientation",this.projectionOrientation),e.add("projectionScale",this.projectionScale),e.add("projectionDepth",this.projectionDepthRange)}}function LO(i,e){const t=new yO(i),n=t.element;n.classList.add("neuroglancer-layer-group-viewer-context-menu");const s=document.createElement("button");s.textContent="Remove layer group",n.appendChild(s),t.registerEventListener(s,"click",()=>{e.layerSpecification.layerManager.clear()});const{viewerNavigationState:r}=e;for(const[o,a]of[["Render scale factors",r.relativeDisplayScales.link],["Render dimensions",r.displayDimensions.link],["Position",r.position.link],["Cross-section orientation",r.crossSectionOrientation.link],["Cross-section zoom",r.crossSectionScale.link],["Cross-section depth range",r.crossSectionDepthRange.link],["3-D projection orientation",r.projectionOrientation.link],["3-D projection zoom",r.projectionScale.link],["3-D projection depth range",r.projectionDepthRange.link]]){const l=t.registerDisposer(new Po(a)),c=document.createElement("label");c.style.display="flex",c.style.flexDirection="row",c.style.whiteSpace="nowrap",c.textContent=o,c.appendChild(l.element),n.appendChild(c)}return t}class Kr extends D.O8{constructor(e,t,n={}){super(),this.element=e,this.viewerState=t,this.state=new Ai,this.options={showLayerPanel:new rt(!0),showViewerMenu:!1,showLayerHoverValues:new rt(!0),...n},this.layerSpecification=this.registerDisposer(t.layerSpecification),this.toolBinder=this.registerDisposer(new gc(this,this.layerSpecification.root.toolBinder)),this.viewerNavigationState=this.registerDisposer(new kO(t)),this.viewerNavigationState.register(this.state),this.registerDisposer((0,A.no)((s,r)=>{r===xo.UNLINKED&&s.registerDisposer(new rc(this.layerSpecification.root.display,this.viewerNavigationState.position.value,this.viewerNavigationState.velocity.velocity))},this.viewerNavigationState.position.link)),this.layerSpecification instanceof Og?this.state.add("layers",this.layerSpecification):this.state.add("layers",{changed:this.layerSpecification.changed,toJSON:()=>this.layerSpecification.layerManager.managedLayers.map(s=>s.name),reset:()=>{throw new Error("not implemented")},restoreState:()=>{throw new Error("not implemented")}}),e.classList.add("neuroglancer-layer-group-viewer"),this.registerDisposer(new Na(e)),this.layout=this.registerDisposer(new cO(this,"xy")),this.state.add("layout",this.layout),this.state.add("toolBindings",this.toolBinder),this.registerActionBindings(),this.registerDisposer(this.layerManager.useDirectly()),this.registerDisposer(pb(e,this.navigationState.position)),this.registerDisposer(this.options.showLayerPanel.changed.add(this.registerCancellable((0,xe.A)(()=>this.updateUI(),0)))),this.makeUI()}get perspectiveNavigationState(){return this.viewerNavigationState.projectionNavigationState}get navigationState(){return this.viewerNavigationState.navigationState}get selectionDetailsState(){return this.layerSpecification.root.selectionState}get display(){return this.viewerState.display}get selectedLayer(){return this.viewerState.selectedLayer}get layerManager(){return this.layerSpecification.layerManager}get chunkManager(){return this.layerSpecification.chunkManager}get mouseState(){return this.viewerState.mouseState}get showAxisLines(){return this.viewerState.showAxisLines}get wireFrame(){return this.viewerState.wireFrame}get enableAdaptiveDownsampling(){return this.viewerState.enableAdaptiveDownsampling}get showScaleBar(){return this.viewerState.showScaleBar}get showPerspectiveSliceViews(){return this.viewerState.showPerspectiveSliceViews}get inputEventBindings(){return this.viewerState.inputEventBindings}get visibility(){return this.viewerState.visibility}get visibleLayerRoles(){return this.viewerState.visibleLayerRoles}get crossSectionBackgroundColor(){return this.viewerState.crossSectionBackgroundColor}get perspectiveViewBackgroundColor(){return this.viewerState.perspectiveViewBackgroundColor}get scaleBarOptions(){return this.viewerState.scaleBarOptions}get changed(){return this.state.changed}bindAction(e,t){this.registerDisposer(X(this.element,e,t))}registerActionBindings(){this.bindAction("add-layer",()=>{this.layerPanel&&this.layerPanel.addLayerMenu()}),this.bindAction("t-",()=>{this.navigationState.pose.translateNonDisplayDimension(0,-1)}),this.bindAction("t+",()=>{this.navigationState.pose.translateNonDisplayDimension(0,1)})}toJSON(){return{type:"viewer",...this.state.toJSON()}}reset(){this.state.reset()}restoreState(e){this.state.restoreState(e),Mt(e,"crossSectionZoom",pr(this.viewerNavigationState.crossSectionScale)),Mt(e,"perspectiveZoom",pr(this.viewerNavigationState.projectionScale)),Mt(e,"perspectiveOrientation",this.viewerNavigationState.projectionOrientation)}makeUI(){this.element.style.flex="1",this.element.style.display="flex",this.element.style.flexDirection="column",this.element.appendChild(this.layout.element),this.updateUI()}updateUI(){const{options:e}=this,t=e.showLayerPanel.value;if(this.layerPanel!==void 0&&!t){this.layerPanel.dispose(),this.layerPanel=void 0;return}if(t&&this.layerPanel===void 0){const n=this.layerPanel=new DO(this,()=>this.layout.toJSON(),this.options.showLayerHoverValues);if(e.showViewerMenu?(n.registerDisposer(LO(n.element,this)),n.element.title="Right click for options, drag to move/copy layer group."):n.element.title="Drag to move/copy layer group.",typeof NEUROGLANCER_SHOW_LAYER_BAR_EXTRA_BUTTONS<"u"&&NEUROGLANCER_SHOW_LAYER_BAR_EXTRA_BUTTONS===!0){{const r=document.createElement("button");r.textContent="Clear segments",r.title='De-select all objects ("x")',r.addEventListener("click",o=>{ef(o,o,{action:"clear-segments"})}),n.element.appendChild(r)}for(const r of["3d","xy","xz","yz"]){const o=document.createElement("button");o.textContent=r,o.title=`Switch to ${r} layout`,o.addEventListener("click",()=>{let a;this.layout.name===r?r!=="3d"?a=`${r}-3d`:a="4panel":a=r,this.layout.name=a}),n.element.appendChild(o)}}n.element.draggable=!0;const s=n.element;s.addEventListener("dragstart",r=>{Sn(n.element,"drag","Drag layer group to the left/top/right/bottom edge of a layer group, or to another layer bar/panel (including in another Neuroglancer window)"),ob(r,{manager:this.layerSpecification,layers:this.layerManager.managedLayers,layoutSpec:this.layout.toJSON()});const o=()=>{On&&On.viewer===this&&(On=void 0),this.unregisterDisposer(o)};On={viewer:this,disposer:o},this.registerDisposer(o);const a=this.toJSON();a.layers=void 0,r.dataTransfer.setData(Xu,JSON.stringify(a)),n.element.style.backgroundColor="black",setTimeout(()=>{n.element.style.backgroundColor=""},0)}),n.element.addEventListener("dragend",()=>{Dt(s,"drag"),cl(),On!==void 0&&On.viewer===this&&On.disposer()}),this.element.insertBefore(s,this.element.firstChild)}}disposed(){Ae(this.element);const{layerPanel:e}=this;e!==void 0&&(e.dispose(),this.layerPanel=void 0),super.disposed()}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const gb=Symbol("layoutComponentContainer");class qs extends D.O8{constructor(e,t,n){super(),this.viewer=e,this.parent=n,this.changed=new j.IY,this.flex=new A.DN(1,p.Mo),this.element=document.createElement("div");const{element:s}=this;s.style.display="flex",s.style.flex="1",s.style.position="relative",s.style.alignItems="stretch",s[gb]=this,this.flex.changed.add(()=>{s.style.flexGrow=""+this.flex.value,this.changed.dispatch()}),this.setSpecification(t);const r=[],o=l=>{const c=document.createElement("div");c.className="neuroglancer-layout-split-drop-zone";let d;switch(c.style[l]="0",l){case"left":case"right":d="row",c.style.width="10px",c.style.height="100%";break;case"top":case"bottom":d="column",c.style.height="10px",c.style.width="100%";break}c.style.display="none",r.push({element:c,direction:d,orientation:l}),s.appendChild(c),vb(c,this.viewer.layerSpecification,()=>this.split(l).newContainer.component,d==="row"?"column":"row")};o("left"),o("right"),o("top"),o("bottom");let a=!1;s.addEventListener("dragenter",l=>{if(!a&&dl(l)!==void 0){a=!0;for(const{element:c,direction:d,orientation:u}of r){if(n!==void 0&&d===n.direction&&((u==="left"||u==="top")&&n.get(0)!==this||(u==="bottom"||u==="right")&&n.get(n.length-1)!==this))continue;const{component:h}=this;h instanceof hl&&h.direction===d||(c.style.display="block")}}},!0),s.addEventListener("drop",l=>{if(a){a=!1;for(const{element:c}of r)c.style.display="none"}},!0),s.addEventListener("dragleave",l=>{const{relatedTarget:c}=l;if(a&&!(c instanceof HTMLElement&&this.element.contains(c))){a=!1;for(const{element:d}of r)d.style.display="none"}},!0)}unsetComponent(){const e=this.componentValue;e!==void 0&&(e.changed.remove(this.changed.dispatch),this.element.removeChild(e.element),e.dispose())}get component(){return this.componentValue}setComponent(e){if(this.unsetComponent(),this.componentValue=e,e.changed.add(this.changed.dispatch),this.element.appendChild(e.element),e instanceof Kr){const{layerManager:t}=e,n=e.registerCancellable((0,xe.A)(()=>{t.managedLayers.length===0&&this.dispose()},0));e.registerDisposer(t.layersChanged.add(()=>{t.managedLayers.length===0&&n()})),n()}else if(e instanceof hl){const t=e.registerCancellable((0,xe.A)(()=>{const{length:n}=e;if(n===0&&this.parent!==void 0)this.dispose();else if(n===1){const s=e.get(0).component;let r;if(this.parent===void 0&&s instanceof Kr){r=s.layout.specification.toJSON(),s.viewerNavigationState.copyToParent();const o=s.layerManager.managedLayers,a=new Set(o),{layerSpecification:l}=s;l.rootLayers.filter(u=>a.has(u)||u.archived);const c=[],{managedLayers:d}=l.rootLayers;for(let u=0,h=d.length;u<h;++u)a.has(d[u])&&c.push(u);for(let u=0,h=o.length;u<h;++u)d[c[u]]=o[u];l.rootLayers.layersChanged.dispatch()}else r=s.toJSON();this.setSpecification(r)}},0));e.registerDisposer(e.changed.add(()=>{e.length<2&&t()})),t()}this.changed.dispatch()}toJSON(){const e=this.component.toJSON();return this.parent instanceof hl&&(e.flex=this.flex.toJSON()),e}setSpecification(e){this.setComponent(PO(this,e)),this.flex.value=(0,p.MM)(e,"flex",p.Mo,1)}static getFromElement(e){return e[gb]}disposed(){this.unsetComponent(),this.componentValue=void 0,super.disposed()}split(e){const t={type:"viewer"},{parent:n}=this;if(n!==void 0){if(e==="left"&&n.direction==="row"||e==="top"&&n.direction==="column")return{newContainer:n.insertChild(t,this),existingContainer:this};if(e==="right"&&n.direction==="row"||e==="bottom"&&n.direction==="column")return{newContainer:n.insertChild(t),existingContainer:this}}let s;const r=this.component;r instanceof Zu?s=r.layerGroupViewer.toJSON():s=r.toJSON();let o,a;const l=e==="left"||e==="right"?"row":"column";switch(e){case"left":case"top":o={type:l,children:[t,s]},a=0;break;case"right":case"bottom":o={type:l,children:[s,t]},a=1;break}this.setSpecification(o);const c=this.component;return{newContainer:c.get(a),existingContainer:c.get(1-a)}}}function mb(i){return{mouseState:i.mouseState,showAxisLines:i.showAxisLines,wireFrame:i.wireFrame,enableAdaptiveDownsampling:i.enableAdaptiveDownsampling,showScaleBar:i.showScaleBar,scaleBarOptions:i.scaleBarOptions,showPerspectiveSliceViews:i.showPerspectiveSliceViews,inputEventBindings:i.inputEventBindings,visibility:i.visibility,selectedLayer:i.selectedLayer,visibleLayerRoles:i.visibleLayerRoles,navigationState:i.navigationState.addRef(),perspectiveNavigationState:i.perspectiveNavigationState.addRef(),velocity:i.velocity.addRef(),crossSectionBackgroundColor:i.crossSectionBackgroundColor,perspectiveViewBackgroundColor:i.perspectiveViewBackgroundColor}}class Zu extends D.O8{constructor(e,t,n){super(),this.element=e,this.layerGroupViewer=this.registerDisposer(new Kr(e,{display:n.display,layerSpecification:n.layerSpecification.addRef(),...mb(n)},{showLayerPanel:n.uiControlVisibility.showLayerPanel,showViewerMenu:!1,showLayerHoverValues:n.uiControlVisibility.showLayerHoverValues})),this.layerGroupViewer.layout.restoreState(t)}toJSON(){return this.layerGroupViewer.layout.specification.toJSON()}get changed(){return this.layerGroupViewer.layout.changed}}function vb(i,e,t,n){i.addEventListener("dragenter",s=>{dl(s)!==void 0&&i.classList.add("neuroglancer-drag-over")}),i.addEventListener("dragleave",()=>{Dt(i,"drop"),i.classList.remove("neuroglancer-drag-over")}),i.addEventListener("dragover",s=>{const r=(o,a)=>{o.dropEffectMessage&&(a+=` (${o.dropEffectMessage})`),Sn(i,"drop",a),s.stopPropagation(),s.preventDefault()};if(fb(s)){const o=RO(s,e);Yu(s,o.dropEffect),r(o,`Drop to ${o.dropEffect} layer group as new ${n}`);return}if(dl(s)!==void 0){const o=EO(s,e,!1,!0);r(o,`Drop to ${o.dropEffect} layer as new ${n}`);return}}),i.addEventListener("drop",s=>{i.classList.remove("neuroglancer-drag-over"),Dt(i,"drop");let r,o;if(fb(s)){s.stopPropagation();try{o=JSON.parse(s.dataTransfer.getData(Xu))}catch{return}if(r=qu(s,e,{forceCopy:!1,newTarget:!0}),r===void 0)return}else{if(r=qu(s,e,{forceCopy:Qu()==="copy",newTarget:!0}),r===void 0)return;o=r.layoutSpec}if(!r.initializeExternalLayers(s)){if(!r.moveSupported)for(const c of r.layers.keys())c.dispose();return}s.preventDefault();const a=s.dataTransfer.dropEffect=Qu();cl(a);const l=t();r.updateArchiveStates(s);for(const c of r.layers.keys())l.layerSpecification.add(c);try{l.restoreState(o)}catch{l.layout.reset()}})}class hl extends D.O8{constructor(e,t,n,s){super(),this.element=e,this.direction=t,this.container=s,this.changed=new j.IY,e.classList.add("neuroglancer-stack-layout"),e.classList.add(`neuroglancer-stack-layout-${t}`),e.style.display="flex",e.style.flexDirection=t,e.appendChild(this.makeDropPlaceholder(this));for(const r of n)this.insertChild(r)}get length(){return(this.element.childElementCount-1)/2}makeDropPlaceholder(e){const t=document.createElement("div");return t.className="neuroglancer-stack-layout-drop-placeholder",vb(t,this.viewer.layerSpecification,()=>{const n=t.nextElementSibling;let s;return n!==null&&(s=qs.getFromElement(n)),this.insertChild({type:"viewer",layers:[]},s).component},this.direction==="row"?"column":"row"),e.registerDisposer(()=>{lt(t)}),t.addEventListener("pointerdown",n=>{if("button"in n&&n.button!==0)return;const s=t.nextElementSibling;if(s===null)return;const r=qs.getFromElement(s),o=t.previousElementSibling;if(o===null)return;const a=qs.getFromElement(o);n.preventDefault();const l=()=>{Sn(t,"drag",`Drag to resize, current ${Hi[this.direction]} ratio is ${a.flex.value} : ${r.flex.value}`)};l(),$t(n,c=>{const d=a.element.getBoundingClientRect(),u=r.element.getBoundingClientRect(),h=Math.max(.1,Math.min(.9,this.direction==="column"?(c.clientY-d.top)/(u.bottom-d.top):(c.clientX-d.left)/(u.right-d.left))),f=Number(a.flex.value)+Number(r.flex.value);a.flex.value=Math.round(h*f*100)/100,r.flex.value=Math.round((1-h)*f*100)/100,l()},()=>{Dt(t,"drag")})}),t}get viewer(){return this.container.viewer}get(e){return qs.getFromElement(this.element.children[e*2+1])}insertChild(e,t){const n=new qs(this.viewer,e,this),s=this.makeDropPlaceholder(n);n.element.classList.add("neuroglancer-stack-layout-child"),n.registerDisposer(n.changed.add(this.changed.dispatch)),n.registerDisposer(()=>{this.element.removeChild(n.element),this.changed.dispatch()});const r=t!==void 0?t.element:null;return this.element.insertBefore(n.element,r),this.element.insertBefore(s,r),this.changed.dispatch(),n}disposed(){this.clear(),super.disposed()}clear(){for(;this.length!==0;)this.get(0).dispose()}*[Symbol.iterator](){const{length:e}=this;for(let t=0;t<e;++t)yield this.get(t)}toJSON(){return{type:this.direction,children:Array.from(this).map(e=>e.toJSON())}}}function PO(i,e){const t=document.createElement("div");if(t.style.flex="1",t.style.width="0px",typeof e=="string"){if(i.parent!==void 0)throw new Error(`Invalid layout component specification: ${JSON.stringify(e)}`);return new Zu(t,e,i.viewer)}(0,p.Rf)(e);const n=(0,p.cQ)(e,"type",p.zr);switch(n){case"row":case"column":return new hl(t,n,(0,p.cQ)(e,"children",s=>{const r=(0,p.$v)(s,o=>o);if(i.parent===void 0&&r.length===0)throw new Error("Stack layout requires at least one child.");return r}),i);case"viewer":{const s=i.viewer,r=new Og(s.layerSpecification.addRef()),o=new Kr(t,{display:s.display,layerSpecification:r,...mb(s)},{showLayerPanel:s.uiControlVisibility.showLayerPanel,showViewerMenu:!0,showLayerHoverValues:s.uiControlVisibility.showLayerHoverValues});try{o.restoreState(e)}catch(a){throw o.dispose(),a}return o}default:return new Zu(t,e,i.viewer)}}class AO extends D.O8{constructor(e,t){super(),this.viewer=e,this.defaultSpecification=t,this.container=this.registerDisposer(new qs(this.viewer,this.defaultSpecification,void 0))}get changed(){return this.container.changed}get element(){return this.container.element}reset(){this.container.setSpecification(this.defaultSpecification)}restoreState(e){this.container.setSpecification(e)}disposed(){super.disposed()}toJSON(){return this.container.toJSON()}}var MO=G(1152),NO=G(5093);/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const OO=Pe.fromObject({escape:{action:"cancel"}});class yb extends D.O8{constructor(e){super(),this.layer=e,this.element=document.createElement("input");const{element:t}=this;t.classList.add("neuroglancer-layer-side-panel-name"),t.spellcheck=!1,t.autocomplete="off";const n=this.registerDisposer(new mn(t,OO));n.allShortcutsAreGlobal=!0,X(t,"cancel",s=>{this.updateView(),t.blur(),s.stopPropagation(),s.preventDefault()}),t.title="Rename layer",this.registerDisposer(e.layerChanged.add(()=>this.updateView())),t.addEventListener("change",()=>this.updateModel()),t.addEventListener("blur",()=>this.updateModel()),this.updateView()}updateView(){this.element.value=this.layer.name}updateModel(){Bg(this.layer,this.element.value)}}class VO extends D.O8{constructor(e){super(),this.layer=e,this.element=document.createElement("select"),this.measureElement=document.createElement("div");const{element:t,measureElement:n}=this;t.classList.add("neuroglancer-layer-side-panel-type"),n.classList.add("neuroglancer-layer-side-panel-type-measure"),t.title="Change layer type",document.body.appendChild(n);for(const[s,r]of na){if(r.type!==s)continue;const o=document.createElement("option");o.textContent=r.typeAbbreviation,o.value=s,t.appendChild(o)}t.addEventListener("change",()=>{const s=t.value,r=na.get(s);zc(this.layer.managedLayer,r)}),this.updateView()}updateView(){const e=this.layer.type,{element:t,measureElement:n}=this;n.textContent=this.layer.constructor.typeAbbreviation,t.value=e,t.style.width=`${n.offsetWidth}px`}disposed(){this.measureElement.remove()}}class pl extends Ji{constructor(e,t){super(e,t.location),this.panelState=t;const n=this.layer=t.layer,{element:s}=this,{titleBar:r}=this.addTitleBar({});r.classList.add("neuroglancer-layer-side-panel-title"),r.appendChild(this.registerDisposer(new VO(n)).element),r.appendChild(this.registerDisposer(new yb(n.managedLayer)).element),this.registerDisposer((0,A.W1)(l=>{s.dataset.neuroglancerLayerVisible=l.toString()},{get value(){return n.managedLayer.visible},changed:n.managedLayer.layerChanged}));const o=this.registerDisposer(new en({get value(){return n.managedLayer.pickEnabled},set value(l){n.managedLayer.pickEnabled=l},changed:n.managedLayer.layerChanged},{svg:NO,enableTitle:"Spatial object selection: disabled",disableTitle:"Spatial object selection: enabled"}));this.registerDisposer(new Xt({get value(){return n.managedLayer.supportsPickOption},changed:n.managedLayer.layerChanged},o.element)),r.appendChild(o.element);const a={get value(){return t!==n.panels.panels[0]},set value(l){l?t.pin():t.unpin()},changed:n.manager.root.layerManager.layersChanged};r.appendChild(this.registerDisposer(new en(a,{text:"\u{1F4CC}\uFE0E",enableTitle:"Pin panel to this layer",disableTitle:"Unpin panel to this layer"})).element),this.registerDisposer((0,A.W1)(l=>{s.dataset.neuroglancerLayerPanelPinned=l.toString()},a)),r.appendChild(Yn({title:"Delete layer",onClick:()=>{Ps(this.layer.managedLayer)}})),this.tabView=new nx({makeTab:l=>n.tabs.options.get(l).getter(),selectedTab:t.selectedTab,tabs:this.registerDisposer(new A.pz({get value(){return t.tabs.map(l=>{const{label:c,hidden:d}=n.tabs.options.get(l);return{id:l,label:c,hidden:d?.value||!1}})},changed:t.tabsChanged})),handleTabElement:(l,c)=>{c.draggable=!0,c.addEventListener("dragstart",d=>{d.stopPropagation(),d.dataTransfer.setData("neuroglancer-side-panel","");let u="Drag tab to dock as new panel to the left/right/top/bottom of another panel";t.panels.panels.find(f=>f!==t&&f.location.visible)&&(u+=`, or move tab to other ${JSON.stringify(n.managedLayer.name)} panel`),Sn(c,"drag",u),this.sidePanelManager.startDrag({dropAsNewPanel:f=>{this.panelState.splitOffTab(l,{...vg,...f})},canDropAsTabs:f=>f instanceof pl&&f.layer===this.layer&&f!==this?1:0,dropAsTab:f=>{this.panelState.moveTabTo(l,f.panelState)}},d)}),c.addEventListener("dragend",d=>{Dt(c,"drag"),this.sidePanelManager.endDrag()})}},this.visibility),this.tabView.element.style.flex="1",this.tabView.element.classList.add("neuroglancer-layer-side-panel-tab-view"),this.tabView.element.style.position="relative",this.tabView.element.appendChild(this.makeTabDropZone()),this.addBody(this.tabView.element),this.registerDisposer(t.tabsChanged.add(()=>{t.tabs.length===0&&(this.location.visible=!1)}))}makeDragSource(){return{...super.makeDragSource(),canDropAsTabs:e=>e instanceof pl&&e.layer===this.layer&&e!==this?this.panelState.tabs.length:0,dropAsTab:e=>{this.panelState.mergeInto(e.panelState)}}}makeTabDropZone(){const e=document.createElement("div");return e.className="neuroglancer-side-panel-drop-zone",e.style.position="absolute",e.style.left="20px",e.style.right="20px",e.style.bottom="20px",e.style.top="20px",e.addEventListener("dragenter",t=>{const{dragSource:n}=this.sidePanelManager,s=n?.canDropAsTabs?.(this);s&&(e.classList.add(Ns),Sn(e,"drop",`Move ${s} ${s===1?"tab":"tabs"} to this panel`),t.preventDefault())}),e.addEventListener("dragleave",()=>{Dt(e,"drop"),e.classList.remove(Ns)}),e.addEventListener("dragover",t=>{const{dragSource:n}=this.sidePanelManager;n?.canDropAsTabs?.(this)&&t.preventDefault()}),e.addEventListener("drop",t=>{Dt(e,"drop");const{dragSource:n}=this.sidePanelManager;n?.canDropAsTabs?.(this)&&(e.classList.remove(Ns),n.dropAsTab(this),t.preventDefault(),t.stopPropagation())}),e}}class _O extends D.O8{constructor(e,t){super(),this.sidePanelManager=e,this.selectedLayerState=t,this.layerSidePanels=new Map,this.generation=0,this.layersNeedUpdate=!0;const n=()=>{this.layersNeedUpdate=!0,this.sidePanelManager.display.scheduleRedraw()};this.registerDisposer(t.changed.add(n)),this.registerDisposer(t.layerManager.layersChanged.add(n)),this.registerDisposer(e.beforeRender.add(()=>this.update()))}getSelectedUserLayer(){return this.selectedLayerState.layer?.layer??void 0}update(){if(!this.layersNeedUpdate)return;const{layerManager:e}=this.selectedLayerState,t=++this.generation;this.layersNeedUpdate=!1;const{layerSidePanels:n}=this,s=r=>{let o=n.get(r);o===void 0?(o={generation:t,unregister:this.sidePanelManager.registerPanel({location:r.location,makePanel:()=>new pl(this.sidePanelManager,r)})},n.set(r,o)):o.generation=t};{const r=this.getSelectedUserLayer(),{location:o}=this.selectedLayerState;if(r===void 0||!o.visible)this.placeholderSelectedLayerPanel===void 0&&(this.placeholderSelectedLayerPanel=this.sidePanelManager.registerPanel({location:o,makePanel:()=>new Ji(this.sidePanelManager,o)}));else{this.placeholderSelectedLayerPanel?.(),this.placeholderSelectedLayerPanel=void 0;const a=r.panels.panels[0];a.location.value=o.value,s(a)}}for(const r of e.managedLayers){const o=r.layer;if(o===null)continue;const{panels:a}=o.panels;for(let l=1,c=a.length;l<c;++l)s(a[l])}for(const[r,o]of n)o.generation!==t&&(o.unregister(),n.delete(r))}disposed(){this.placeholderSelectedLayerPanel?.();for(const{unregister:e}of this.layerSidePanels.values())e()}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const BO={...Fi,side:"left",row:0};class FO{constructor(){this.location=new ci(BO)}get changed(){return this.location.changed}restoreState(e){e!==void 0&&this.location.restoreState(e)}reset(){this.location.reset()}toJSON(){return(0,p.Zu)(this.location.toJSON())}}class UO extends D.O8{constructor(e){super(),this.layer=e,this.element=document.createElement("div");const{element:t}=this,n=_e({svg:MO,title:"Hide layer",onClick:()=>{this.layer.setVisible(!1)}}),s=_e({svg:Rm,title:"Show layer",onClick:()=>{this.layer.setVisible(!0)}});t.appendChild(s),t.appendChild(n);const r=()=>{const o=this.layer.visible;n.style.display=o?"":"none",s.style.display=o?"none":""};r(),this.registerDisposer(e.layerChanged.add(r))}}function $O(i){const{selectedLayer:e}=i.manager.root,t=new en({get value(){return e.layer===i&&e.visible},set value(n){n?(e.layer=i,e.visible=!0):e.visible=!1},changed:e.changed},{backgroundScheme:"dark",enableTitle:"Show layer side panel",disableTitle:"Hide layer side panel",svg:V0});return t.element.classList.add("neuroglancer-layer-list-panel-item-controls"),t}class GO extends D.O8{constructor(e,t){super(),this.panel=e,this.layer=t,this.element=document.createElement("div"),this.numberElement=document.createElement("div"),this.generation=-1;const{element:n,numberElement:s}=this;n.classList.add("neuroglancer-layer-list-panel-item"),s.classList.add("neuroglancer-layer-list-panel-item-number"),n.appendChild(this.registerDisposer(new Un({get value(){return!t.archived},set value(o){t.setArchived(!o)},changed:t.layerChanged},{enableTitle:"Archive layer (disable and remove from layer groups)",disableTitle:"Unarchive layer (enable and add to all layer groups)"})).element),n.appendChild(s),n.appendChild(this.registerDisposer(new UO(t)).element),n.appendChild(this.registerDisposer(new yb(t)).element),n.appendChild(this.registerDisposer($O(t)).element);const r=Yn({title:"Delete layer",onClick:()=>{Ps(this.layer)}});r.classList.add("neuroglancer-layer-list-panel-item-delete"),n.appendChild(r),ub(e,n,t,{isLayerListPanel:!0,getLayoutSpec:()=>{}}),ul(e,n,t,!0),n.addEventListener("click",o=>{o.ctrlKey?(e.selectedLayer.toggle(t),o.preventDefault()):o.altKey&&(t.pickEnabled=!t.pickEnabled,o.preventDefault())}),n.addEventListener("contextmenu",o=>{e.selectedLayer.toggle(t),o.stopPropagation(),o.preventDefault()})}}class zO extends Ji{constructor(e,t,n){super(e,n.location),this.manager=t,this.state=n,this.items=new Map,this.itemContainer=document.createElement("div"),this.layerDropZone=document.createElement("div"),this.dragEnterCount=0,this.generation=-1;const{itemContainer:s,layerDropZone:r}=this,{titleElement:o}=this.addTitleBar({title:""});this.titleElement=o,s.classList.add("neuroglancer-layer-list-panel-items"),this.addBody(s),r.style.flex="1";const a=this.registerCancellable((0,je.t)(()=>this.render()));this.visibility.changed.add(a),this.registerDisposer(this.layerManager.layersChanged.add(a)),this.registerDisposer(this.selectedLayer.changed.add(a)),hb(this),ul(this,r,void 0,!0),this.render()}get layerManager(){return this.manager.layerManager}get selectedLayer(){return this.manager.selectedLayer}render(){const e=this,t=this.selectedLayer.layer,n=++this.generation;let s=0,r=0,o=0;this.layerManager.updateNonArchivedLayerIndices();function*a(){const{items:c}=e;let d=0;for(const h of e.layerManager.managedLayers)h.archived||++d;const u=`${(d+1).toString().length}ch`;for(const h of e.layerManager.managedLayers){h.visible?++s:h.archived?++o:++r;let f=c.get(h);f===void 0&&(f=e.registerDisposer(new GO(e,h)),c.set(h,f)),f.generation=n;const{nonArchivedLayerIndex:m}=h;f.numberElement.style.width=u,m===-1?f.numberElement.style.visibility="hidden":(f.numberElement.style.visibility="",f.numberElement.textContent=`${m+1}`),f.element.dataset.selected=(h===t).toString(),f.element.dataset.archived=h.archived.toString(),yield f.element}for(const[h,f]of c)n!==f.generation&&(c.delete(h),e.unregisterDisposer(f),f.dispose());yield e.layerDropZone}Zt(this.itemContainer,a());let l="Layers";if(s||r||o){l+=" (";let c="";s+r&&(l+=`${s}/${r+s} visible`,c=", "),o&&(l+=`${c}${o} archived`),l+=")"}this.titleElement.textContent=l}}class WO extends D.O8{constructor(e){super(),this.layerManager=e,this.element=document.createElement("div");const t=this.registerCancellable((0,je.t)(()=>this.render()));this.registerDisposer(e.layersChanged.add(t)),this.render()}render(){let e=0;const{managedLayers:t}=this.layerManager;for(const s of t)s.archived&&++e;const{element:n}=this;if(e!==0){const s=t.length;n.textContent=`${s-e}/${s}`}else n.textContent=""}}var t2=G(6792),n2=G(8948),i2=G(1274),s2=G(795);/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const HO=100;class JO extends $r{constructor(e){super(),this.viewer=e,this.parsedValue=null,this.debouncedValueUpdater=(0,xe.A)(()=>{const r=this.textEditor.getValue();try{const o=JSON.parse(r);this.parsedValue=o,this.applyButton.disabled=!1,this.textEditor.setOption("lint",void 0)}catch(o){this.parsedValue=null,this.applyButton.disabled=!0;let a=0,l=0,c="Unknown parse error";if(o instanceof Error){const d=o.message.match(/^((?:.|\n)*) in JSON at position ([0-9]+)$/);if(d!==null){c=d[1];const u=parseInt(d[2],10),f=r.substring(0,u).split(`
`);a=f.length-1,l=f[f.length-1].length}else c=o.message}this.textEditor.setOption("lint",{getAnnotations:()=>[{message:c,severity:"error",from:vi().Pos(a,l)}]})}},HO),this.content.classList.add("neuroglancer-state-editor");const t=this.applyButton=document.createElement("button");t.textContent="Apply changes",this.content.appendChild(t),t.addEventListener("click",()=>this.applyChanges()),t.disabled=!0;const n=this.closeButton=document.createElement("button");n.classList.add("close-button"),n.textContent="Close",this.content.appendChild(n),n.addEventListener("click",()=>this.dispose());const s=this.downloadButton=document.createElement("button");s.textContent="Download",s.title="Download state as a JSON file",this.content.appendChild(s),s.addEventListener("click",()=>this.downloadState()),this.textEditor=vi()(r=>{},{value:"",mode:{name:"javascript",json:!0},foldGutter:!0,gutters:["CodeMirror-lint-markers","CodeMirror-foldgutter"]}),this.updateView(),this.textEditor.on("change",()=>{this.debouncedValueUpdater()}),this.content.appendChild(this.textEditor.getWrapperElement()),this.textEditor.refresh()}downloadState(){const e=document.createElement("a"),t=new Blob([this.getJson()],{type:"text/json"}),n=URL.createObjectURL(t);e.href=n,e.download="state.json",e.click(),document.body.removeChild(e)}applyChanges(){this.parsedValue!==null&&(this.viewer.state.reset(),this.viewer.state.restoreState(this.parsedValue)),this.applyButton.disabled=!0}updateView(){this.textEditor.setValue(this.getJson()),this.textEditor.execCommand("foldAll"),this.textEditor.execCommand("unfold")}getJson(){return JSON.stringify(ri(this.viewer.state).value,null,"  ")}}/**
 * @license
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const jO={side:"bottom",size:100,minSize:50,row:0,col:0,flex:1,visible:!1};class YO{constructor(){this.location=new ci(jO)}get changed(){return this.location.changed}restoreState(e){this.location.restoreState(e)}reset(){this.location.reset()}toJSON(){return(0,p.Zu)(this.location.toJSON())}}function QO(i){const e=new Map;function t(n,s){if(n==null||typeof n!="object"){e.set(s,""+n);return}for(const r of Object.keys(n))t(n[r],s+"."+r)}return t(i,""),e}function qO(i){const e=new Set;e.add(".type");const t=new Set;function n(s,r){for(const o of e)if(i[s].get(o)!==i[r].get(o))return!0;return!1}for(let s=0,r=i.length;s<r;++s){for(const a of i[s].keys())t.add(a);let o=[];for(let a=0;a<s;++a)n(s,a)||o.push(a);for(;o.length>0;){let a=o,l;for(const c of t){if(e.has(c))continue;const d=[];for(const u of o)i[u].get(c)===i[s].get(c)&&d.push(u);if(d.length<a.length&&(a=d,l=c),d.length===0)break}if(l===void 0)break;o=a,e.add(l)}}return Array.from(e)}function KO(i,e){const t={};for(const n of e){const s=i.get(n);if(s!==void 0){if(n==="")return s;t[n]=s}}return JSON.stringify(t)}function eh(i){return Object.assign({type:i.RPC_TYPE_ID},i.key||{})}function Sb(i){const e=i.map(QO),t=qO(e);return e.map(n=>KO(n,t))}const XO=1e3,Xr=[{label:"Visible chunks/T",key:"visibleChunksTotal",getter:i=>{let e=0;for(let t=0;t<Gl;++t)e+=i[Ti(t,ni.VISIBLE)*Fn+ii.numChunks];return e}},{label:"Visible chunks/D",key:"visibleChunksDownloading",getter:i=>i[Ti(Be.DOWNLOADING,ni.VISIBLE)*Fn+ii.numChunks]},{label:"Visible chunks/M",key:"visibleChunksSystemMemory",getter:i=>i[Ti(Be.SYSTEM_MEMORY,ni.VISIBLE)*Fn+ii.numChunks]+i[Ti(Be.SYSTEM_MEMORY_WORKER,ni.VISIBLE)*Fn+ii.numChunks]},{label:"Visible chunks/G",key:"visibleChunksGpuMemory",getter:i=>i[Ti(Be.GPU_MEMORY,ni.VISIBLE)*Fn+ii.numChunks]},{label:"Visible chunks/F",key:"visibleChunksFailed",getter:i=>i[Ti(Be.FAILED,ni.VISIBLE)*Fn+ii.numChunks]},{label:"Visible memory",key:"visibleGpuMemory",getter:i=>i[Ti(Be.GPU_MEMORY,ni.VISIBLE)*Fn+ii.gpuMemoryBytes]},{label:"Download latency",key:"downloadLatency",getter:i=>i[Qh(Wl.totalTime)]/i[Qh(Wl.totalChunks)]}];class ZO extends Ji{constructor(e,t,n){super(e,n.location),this.chunkQueueManager=t,this.displayState=n,this.data=void 0,this.requestDataTimerId=-1,this.dataRequested=!1,this.body=document.createElement("div"),this.debouncedUpdateView=this.registerCancellable((0,xe.A)(()=>this.updateView(),0));const{body:s}=this;s.classList.add("neuroglancer-statistics-panel-body"),this.addTitleBar({title:"Chunk statistics"}),this.addBody(s),this.requestData()}disposed(){window.clearTimeout(this.requestDataTimerId),super.disposed()}requestData(){if(this.dataRequested)return;const{chunkQueueManager:e}=this;this.dataRequested=!0,e.getStatistics().then(t=>{this.dataRequested=!1,this.data=t,this.debouncedUpdateView(),this.requestDataTimerId=window.setTimeout(()=>{this.requestDataTimerId=-1,this.requestData()},XO)})}updateView(){const{data:e}=this;if(e===void 0)return;const t=document.createElement("table"),n=[];for(const[a,l]of e){const c=[a];for(const{getter:d}of Xr)c.push(d(l));n.push(c)}const s=Sb(n.map(a=>eh(a[0]))),r=new Map;s.forEach((a,l)=>{r.set(n[l][0],a)});{const a=document.createElement("thead");let l=document.createElement("tr");a.appendChild(l);const c=u=>{const h=document.createElement("td");h.textContent=u,l.appendChild(h)};c("Name");let d;for(const{label:u}of Xr){const h=u.indexOf("/");let f=u;if(h!==-1){if(f=u.substring(0,h),f===d){++l.lastElementChild.colSpan;continue}d=f}c(f)}l=document.createElement("tr"),a.appendChild(l);{const u=document.createElement("td");l.appendChild(u)}for(const{label:u}of Xr){const h=u.indexOf("/");let f="";h!==-1&&(f=u.substring(h+1));const m=document.createElement("td");m.textContent=f,l.appendChild(m)}t.appendChild(a)}const o=document.createElement("tbody");for(const[a,...l]of n){const c=document.createElement("tr"),d=u=>{const h=document.createElement("td");h.textContent=u,c.appendChild(h)};d(r.get(a));for(const u of l)d(""+u);o.appendChild(c)}t.appendChild(o),Ae(this.body),this.body.appendChild(t)}}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const eV={...Fi,side:"left",row:2};class tV{constructor(){this.location=new ci(eV)}get changed(){return this.location.changed}toJSON(){return(0,p.Zu)(this.location.toJSON())}reset(){this.location.reset()}restoreState(e){this.location.restoreState(e)}}class nV extends Ji{constructor(e,t,n){super(e,t.location),this.addTitleBar({title:"Settings"});const s=document.createElement("div");s.classList.add("neuroglancer-settings-body");const r=document.createElement("div");r.classList.add("neuroglancer-settings-scroll-container"),s.appendChild(r),this.addBody(s);{const c=this.registerDisposer(new tm(n.title));c.element.placeholder="Title",c.element.classList.add("neuroglancer-settings-title"),r.appendChild(c.element)}const o=(c,d)=>{const u=this.registerDisposer(new mc(d,{label:c}));u.element.classList.add("neuroglancer-settings-limit-widget"),r.appendChild(u.element)};o("GPU memory limit",n.chunkQueueManager.capacities.gpuMemory.sizeLimit),o("System memory limit",n.chunkQueueManager.capacities.systemMemory.sizeLimit),o("Concurrent chunk requests",n.chunkQueueManager.capacities.download.itemLimit);const a=(c,d)=>{const u=document.createElement("label");u.textContent=c;const h=this.registerDisposer(new Un(d));u.appendChild(h.element),r.appendChild(u)};a("Show axis lines",n.showAxisLines),a("Show scale bar",n.showScaleBar),a("Show cross sections in 3-d",n.showPerspectiveSliceViews),a("Show default annotations",n.showDefaultAnnotations),a("Show chunk statistics",n.statisticsDisplayState.location.watchableVisible),a("Wire frame rendering",n.wireFrame),a("Enable prefetching",n.chunkQueueManager.enablePrefetch),a("Enable adaptive downsampling",n.enableAdaptiveDownsampling);const l=(c,d)=>{const u=document.createElement("label");u.textContent=c;const h=this.registerDisposer(new Ro(d));u.appendChild(h.element),r.appendChild(u)};l("Cross-section background",n.crossSectionBackgroundColor),l("Projection background",n.perspectiveViewBackgroundColor)}}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iV extends D.O8{constructor(e,t){super(),this.selectedLayer=e,this.toolBinder=t,this.element=document.createElement("div"),this.viewContext=void 0,this.updateView=this.registerCancellable((0,je.t)(()=>{let{viewContext:s}=this;s!==void 0&&(this.unregisterDisposer(s),s.dispose()),this.viewContext=s=this.registerDisposer(new D.O8),Ae(this.element);const{selectedTool:r}=this;r!==void 0&&this.element.appendChild(this.makeWidget(s,r));const o=Array.from(this.toolBinder.bindings);o.sort(([a],[l])=>(0,Dr.e)(a,l));for(const[,a]of o)this.element.appendChild(this.makeWidget(s,a))}));const{element:n}=this;n.className="neuroglancer-annotation-tool-status",this.registerDisposer(e.changed.add(()=>this.selectedLayerChanged())),this.registerDisposer(t.changed.add(this.updateView)),this.registerDisposer(this.selectedLayer.layerManager.layersChanged.add(this.updateView)),this.selectedLayerChanged()}get selectedTool(){const e=this.selectedLayer.layer;if(e===void 0)return;const t=e.layer;if(t!==null)return t.tool.value}selectedLayerChanged(){const{unbindPreviousLayer:e}=this;e!==void 0&&e();const t=this.selectedLayer.layer;t!==void 0&&(this.unbindPreviousLayer=t.specificationChanged.add(()=>{this.updateView()})),this.updateView()}disposed(){const{unbindPreviousLayer:e}=this;e!==void 0&&e(),this.unbindPreviousLayer=void 0}makeWidget(e,t){const n=document.createElement("div");n.title="dblclick \u2192 unbind",t instanceof ko&&(n.title+=", click \u2192 bind key"),n.className="neuroglancer-annotation-tool-status-widget";const s=document.createElement("div");s.className="neuroglancer-annotation-tool-status-widget-layer-number";const r=document.createElement("div");if(r.className="neuroglancer-annotation-tool-status-widget-description",r.textContent=t.description,n.addEventListener("dblclick",()=>{t instanceof Sf?t.layer.tool.value=void 0:this.toolBinder.set(t.keyBinding,void 0)}),t instanceof ko){const a=document.createElement("div");a.className="neuroglancer-annotation-tool-status-widget-key",a.textContent=t.keyBinding,n.appendChild(a),xf(e,n,l=>t.localBinder.set(l,t.addRef()))}const o=t.context;if(o instanceof Ln){const{managedLayer:a}=o;a.manager.rootLayers.updateNonArchivedLayerIndices();const l=a.nonArchivedLayerIndex;s.textContent=(l+1).toString(),n.appendChild(s)}return n.appendChild(r),n}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sV extends D.O8{constructor(e,t){super(),this.gl=e,this.frameNumberCounter=t,this.worker=new Worker(new URL(G.p+G.u(717),G.b),{type:"module"}),this.chunkQueueManager=this.registerDisposer(new Ic(new Uw(this.worker,!0),this.gl,this.frameNumberCounter,{gpuMemory:new Jo({defaultItemLimit:1e6,defaultSizeLimit:1e9}),systemMemory:new Jo({defaultItemLimit:1e7,defaultSizeLimit:2e9}),download:new Jo({defaultItemLimit:100,defaultSizeLimit:Number.POSITIVE_INFINITY}),compute:new Jo({defaultItemLimit:128,defaultSizeLimit:5e8})})),this.chunkQueueManager.registerDisposer(()=>this.worker.terminate()),this.chunkManager=this.registerDisposer(new Rc(this.chunkQueueManager))}get rpc(){return this.chunkQueueManager.rpc}}class r2 extends KN{constructor(){super(...arguments),this.global=new Pe}}const bb=["showHelpButton","showSettingsButton","showEditStateButton","showLayerListPanelButton","showSelectionPanelButton","showLayerSidePanelButton","showLocation","showAnnotationToolStatus"],wb=[...bb,"showLayerPanel","showLayerHoverValues"],th=[...wb,"showUIControls","showPanelBorders"];function rV(){return Object.fromEntries(th.map(i=>[i,new rt(!0)]))}function oV(i,e){for(const t of th){const n=e[t];n!==void 0&&(i[t].value=n)}}const aV=typeof NEUROGLANCER_OVERRIDE_DEFAULT_VIEWER_OPTIONS<"u"?NEUROGLANCER_OVERRIDE_DEFAULT_VIEWER_OPTIONS:{showLayerDialog:!0,resetStateWhenEmpty:!0};class lV extends Ai{constructor(e){super(),this.viewer=e,this.add("title",e.title),this.add("dimensions",e.coordinateSpace),this.add("relativeDisplayScales",e.relativeDisplayScales),this.add("displayDimensions",e.displayDimensions),this.add("position",e.position),this.add("velocity",e.velocity),this.add("crossSectionOrientation",e.crossSectionOrientation),this.add("crossSectionScale",e.crossSectionScale),this.add("crossSectionDepth",e.crossSectionDepthRange),this.add("projectionOrientation",e.projectionOrientation),this.add("projectionScale",e.projectionScale),this.add("projectionDepth",e.projectionDepthRange),this.add("layers",e.layerSpecification),this.add("showAxisLines",e.showAxisLines),this.add("wireFrame",e.wireFrame),this.add("enableAdaptiveDownsampling",e.enableAdaptiveDownsampling),this.add("showScaleBar",e.showScaleBar),this.add("showDefaultAnnotations",e.showDefaultAnnotations),this.add("showSlices",e.showPerspectiveSliceViews),this.add("gpuMemoryLimit",e.dataContext.chunkQueueManager.capacities.gpuMemory.sizeLimit),this.add("prefetch",e.dataContext.chunkQueueManager.enablePrefetch),this.add("systemMemoryLimit",e.dataContext.chunkQueueManager.capacities.systemMemory.sizeLimit),this.add("concurrentDownloads",e.dataContext.chunkQueueManager.capacities.download.itemLimit),this.add("selectedLayer",e.selectedLayer),this.add("crossSectionBackgroundColor",e.crossSectionBackgroundColor),this.add("projectionBackgroundColor",e.perspectiveViewBackgroundColor),this.add("layout",e.layout),this.add("statistics",e.statisticsDisplayState),this.add("helpPanel",e.helpPanelState),this.add("settingsPanel",e.settingsPanelState),this.add("selection",e.selectionDetailsState),this.add("layerListPanel",e.layerListPanelState),this.add("partialViewport",e.partialViewport),this.add("selectedStateServer",e.selectedStateServer),this.add("toolBindings",e.toolBinder)}restoreState(e){const{viewer:t}=this;super.restoreState(e),(0,p.MM)(e,"navigation",n=>{(0,p.Rf)(n),(0,p.MM)(n,"pose",s=>{(0,p.Rf)(s),(0,p.MM)(s,"position",r=>{(0,p.Rf)(r),Mt(r,"voxelCoordinates",t.position),(0,p.MM)(r,"voxelSize",o=>{const a=(0,p.Xu)(new Float64Array(3),o,p.Mo);for(let l=0;l<3;++l)a[l]*=1e-9;t.coordinateSpace.value=ke({valid:!1,names:["x","y","z"],units:["m","m","m"],scales:a})})}),Mt(s,"orientation",t.crossSectionOrientation)}),Mt(n,"zoomFactor",t.crossSectionScale.legacyJsonView)}),Mt(e,"perspectiveOrientation",t.projectionOrientation),Mt(e,"perspectiveZoom",t.projectionScale.legacyJsonView),Mt(e,"perspectiveViewBackgroundColor",t.perspectiveViewBackgroundColor)}}class nh extends D.O8{constructor(e,t={}){super(),this.display=e,this.title=new A.DN(void 0,p.zr),this.coordinateSpace=new Ml,this.position=this.registerDisposer(new oi(this.coordinateSpace)),this.velocity=this.registerDisposer(new sc(this.coordinateSpace)),this.relativeDisplayScales=this.registerDisposer(new zp(this.coordinateSpace)),this.displayDimensions=this.registerDisposer(new Yp(this.coordinateSpace)),this.displayDimensionRenderInfo=this.registerDisposer(new jp(this.relativeDisplayScales.addRef(),this.displayDimensions.addRef())),this.crossSectionOrientation=this.registerDisposer(new hs),this.crossSectionScale=this.registerDisposer(new UC(this.displayDimensionRenderInfo.addRef())),this.projectionOrientation=this.registerDisposer(new hs),this.crossSectionDepthRange=this.registerDisposer(new lc(-10,this.displayDimensionRenderInfo)),this.projectionDepthRange=this.registerDisposer(new lc(-50,this.displayDimensionRenderInfo)),this.projectionScale=this.registerDisposer(new $C(this.displayDimensionRenderInfo.addRef())),this.navigationState=this.registerDisposer(new fs(new ps(this.position.addRef(),this.displayDimensionRenderInfo.addRef(),this.crossSectionOrientation.addRef()),this.crossSectionScale.addRef(),this.crossSectionDepthRange.addRef())),this.perspectiveNavigationState=this.registerDisposer(new fs(new ps(this.position.addRef(),this.displayDimensionRenderInfo.addRef(),this.projectionOrientation.addRef()),this.projectionScale.addRef(),this.projectionDepthRange.addRef())),this.mouseState=new ST,this.layerManager=this.registerDisposer(new Tg),this.selectedLayer=this.registerDisposer(new DT(this.layerManager.addRef())),this.showAxisLines=new rt(!0,!0),this.wireFrame=new rt(!1,!1),this.enableAdaptiveDownsampling=new rt(!0,!0),this.showScaleBar=new rt(!0,!0),this.showPerspectiveSliceViews=new rt(!0,!0),this.visibleLayerRoles=Yw(),this.showDefaultAnnotations=new rt(!0,!0),this.crossSectionBackgroundColor=new q(w.eR.fromValues(.5,.5,.5)),this.perspectiveViewBackgroundColor=new q(w.eR.fromValues(0,0,0)),this.scaleBarOptions=new RN,this.partialViewport=new Ow,this.statisticsDisplayState=new YO,this.helpPanelState=new gO,this.settingsPanelState=new tV,this.layerSelectedValues=this.registerDisposer(new bT(this.layerManager,this.mouseState)),this.selectionDetailsState=this.registerDisposer(new wT(this.coordinateSpace,this.layerSelectedValues)),this.selectedStateServer=new A.DN("",p.zr),this.layerListPanelState=new FO,this.resetInitiated=new j.IY,this.uiControlVisibility={},this.visible=!0,this.toolInputEventMapBinder=(f,m)=>{m.registerDisposer(this.inputEventBindings.sliceView.addParent(f,Number.POSITIVE_INFINITY)),m.registerDisposer(this.inputEventBindings.perspectiveView.addParent(f,Number.POSITIVE_INFINITY))},this.globalToolBinder=this.registerDisposer(new fx(this.toolInputEventMapBinder)),this.toolBinder=this.registerDisposer(new gc(this,this.globalToolBinder));const{dataContext:n=new sV(e.gl,e),visibility:s=new ht(ht.VISIBLE),inputEventBindings:r={global:new Pe,sliceView:new Pe,perspectiveView:new Pe},element:o=e.makeCanvasOverlayElement(),dataSourceProvider:a=hS({credentialsManager:_0}),uiConfiguration:l=rV()}=t;this.visibility=s,this.inputEventBindings=r,this.element=o,this.dataSourceProvider=a,this.uiConfiguration=l,this.registerDisposer((0,A.W1)(f=>{this.display.applyWindowedViewportToElement(o,f)},this.partialViewport)),this.registerDisposer(()=>lt(this.element)),this.dataContext=this.registerDisposer(n),oV(l,t);const c={...aV,...t},{resetStateWhenEmpty:d,showLayerDialog:u}=c;for(const f of wb)this.uiControlVisibility[f]=this.makeUiControlVisibilityState(f);this.registerDisposer(this.uiConfiguration.showPanelBorders.changed.add(()=>{this.updateShowBorders()})),this.showLayerDialog=u,this.resetStateWhenEmpty=d,this.layerSpecification=new kT(this.display,this.dataSourceProvider,this.layerManager,this.chunkManager,this.selectionDetailsState,this.selectedLayer,this.navigationState.coordinateSpace,this.navigationState.pose.position,this.globalToolBinder),this.registerDisposer(e.updateStarted.add(()=>{this.onUpdateDisplay()})),this.showDefaultAnnotations.changed.add(()=>{this.showDefaultAnnotations.value?this.visibleLayerRoles.add(si.DEFAULT_ANNOTATION):this.visibleLayerRoles.delete(si.DEFAULT_ANNOTATION)}),this.registerDisposer(this.navigationState.changed.add(()=>{this.handleNavigationStateChanged()}));const h=this.registerCancellable((0,xe.A)(()=>{!this.wasDisposed&&this.layerManager.managedLayers.length===0&&this.resetStateWhenEmpty&&(this.navigationState.reset(),this.perspectiveNavigationState.pose.orientation.reset(),this.perspectiveNavigationState.zoomFactor.reset(),this.resetInitiated.dispatch(),!Xd&&this.showLayerDialog&&this.visibility.visible&&$g(this.layerSpecification,this.selectedLayer))}));this.layerManager.layersChanged.add(h),h(),this.registerDisposer(this.dataContext.chunkQueueManager.visibleChunksChanged.add(()=>{this.layerSelectedValues.handleLayerChange()})),this.registerDisposer(this.dataContext.chunkQueueManager.visibleChunksChanged.add(()=>{this.visible&&e.scheduleRedraw()})),this.makeUI(),this.updateShowBorders(),this.registerActionListeners(),this.registerEventActionBindings(),this.registerDisposer(pb(o,this.navigationState.position)),this.state=new lV(this),this.registerDisposer(new rc(this.display,this.position,this.velocity))}get chunkManager(){return this.dataContext.chunkManager}get chunkQueueManager(){return this.dataContext.chunkQueueManager}makeUiControlVisibilityState(e){const t=this.uiConfiguration.showUIControls,n=this.uiConfiguration[e];return this.registerDisposer((0,A.Kk)((s,r)=>s&&r,t,n))}get inputEventMap(){return this.inputEventBindings.global}updateShowBorders(){const{element:e}=this,t="neuroglancer-show-panel-borders";this.uiConfiguration.showPanelBorders.value?e.classList.add(t):e.classList.remove(t)}makeUI(){const e=this.element;e.classList.add("neuroglancer-viewer"),e.classList.add("neuroglancer-noselect"),e.style.display="flex",e.style.flexDirection="column";const t=document.createElement("div");t.classList.add("neuroglancer-viewer-top-row"),t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch";const n=this.registerDisposer(new bs(this.navigationState.position,this.layerSpecification.coordinateSpaceCombiner,{velocity:this.velocity,getToolBinder:()=>this.toolBinder}));this.registerDisposer(new Xt(this.uiControlVisibility.showLocation,n.element)),t.appendChild(n.element);const s=this.registerDisposer(new xx(document.createElement("div"),this.mouseState,this.navigationState.coordinateSpace));if(s.element.style.flex="1",s.element.style.alignSelf="center",this.registerDisposer(new Xt(this.uiControlVisibility.showLocation,s.element)),t.appendChild(s.element),typeof NEUROGLANCER_CREDIT_LINK<"u"){let a=NEUROGLANCER_CREDIT_LINK;Array.isArray(a)||(a=[a]);for(const{url:l,text:c}of a){const d=document.createElement("a");d.style.marginRight="5px",d.href=l,d.textContent=c,d.style.fontFamily="sans-serif",d.style.color="yellow",d.target="_blank",t.appendChild(d)}}const r=this.registerDisposer(new iV(this.selectedLayer,this.globalToolBinder));if(t.appendChild(r.element),this.registerDisposer(new Xt(this.uiControlVisibility.showAnnotationToolStatus,r.element)),dO){const a=this.registerDisposer(new uO(this));t.appendChild(a.element)}{const{layerListPanelState:a}=this,l=this.registerDisposer(new en(a.location.watchableVisible,{svg:cN,backgroundScheme:"dark",enableTitle:"Show layer list panel",disableTitle:"Hide layer list panel"}));l.element.insertAdjacentElement("afterbegin",this.registerDisposer(new WO(this.layerManager)).element),this.registerDisposer(new Xt(this.uiControlVisibility.showLayerListPanelButton,l.element)),t.appendChild(l.element)}{const{selectionDetailsState:a}=this,l=this.registerDisposer(new en(a.location.watchableVisible,{svg:dN,backgroundScheme:"dark",enableTitle:"Show selection details panel",disableTitle:"Hide selection details panel"}));this.registerDisposer(new Xt(this.uiControlVisibility.showSelectionPanelButton,l.element)),t.appendChild(l.element)}{const{selectedLayer:a}=this,l=this.registerDisposer(new en({get value(){return a.visible},set value(c){a.visible=c},changed:a.location.locationChanged},{svg:V0,backgroundScheme:"dark",enableTitle:"Show layer side panel",disableTitle:"Hide layer side panel"}));this.registerDisposer(new Xt(this.uiControlVisibility.showLayerSidePanelButton,l.element)),t.appendChild(l.element)}{const a=_e({text:"{}",title:"Edit JSON state"});this.registerEventListener(a,"click",()=>{this.editJsonState()}),this.registerDisposer(new Xt(this.uiControlVisibility.showEditStateButton,a)),t.appendChild(a)}{const{helpPanelState:a}=this,l=this.registerDisposer(new en(a.location.watchableVisible,{text:"?",backgroundScheme:"dark",enableTitle:"Show help panel",disableTitle:"Hide help panel"}));this.registerDisposer(new Xt(this.uiControlVisibility.showHelpButton,l.element)),t.appendChild(l.element)}{const{settingsPanelState:a}=this,l=this.registerDisposer(new en(a.location.watchableVisible,{svg:uN,backgroundScheme:"dark",enableTitle:"Show settings panel",disableTitle:"Hide settings panel"}));this.registerDisposer(new Xt(this.uiControlVisibility.showSettingsButton,l.element)),t.appendChild(l.element)}this.registerDisposer(new Xt((0,A.Kk)((...a)=>a.reduce((l,c)=>l||c,!1),...bb.map(a=>this.uiControlVisibility[a])),t)),e.appendChild(t),this.layout=this.registerDisposer(new AO(this,"4panel")),this.sidePanelManager=this.registerDisposer(new bD(this.display,this.layout.element,this.visibility)),this.registerDisposer(this.sidePanelManager.registerPanel({location:this.layerListPanelState.location,makePanel:()=>new zO(this.sidePanelManager,this.layerSpecification,this.layerListPanelState)})),this.registerDisposer(new _O(this.sidePanelManager,this.selectedLayer.addRef())),this.registerDisposer(this.sidePanelManager.registerPanel({location:this.selectionDetailsState.location,makePanel:()=>new wD(this.sidePanelManager,this.selectionDetailsState,this.layerSpecification,this.selectedLayer)})),e.appendChild(this.sidePanelManager.element),this.registerDisposer(this.sidePanelManager.registerPanel({location:this.statisticsDisplayState.location,makePanel:()=>new ZO(this.sidePanelManager,this.chunkQueueManager,this.statisticsDisplayState)})),this.registerDisposer(this.sidePanelManager.registerPanel({location:this.helpPanelState.location,makePanel:()=>{const{inputEventBindings:a}=this;return new mO(this.sidePanelManager,this.helpPanelState,[["Global",a.global],["Cross section view",a.sliceView],["3-D projection view",a.perspectiveView]],this.layerManager,this.globalToolBinder)}})),this.registerDisposer(this.sidePanelManager.registerPanel({location:this.settingsPanelState.location,makePanel:()=>new nV(this.sidePanelManager,this.settingsPanelState,this)}));const o=()=>{const a=this.visibility.visible;a!==this.visible&&(e.style.visibility=a?"inherit":"hidden",this.visible=a)};o(),this.registerDisposer(this.visibility.changed.add(o))}registerEventActionBindings(){const{element:e}=this;this.registerDisposer(new mn(e,this.inputEventMap)),this.registerDisposer(new Na(e))}bindAction(e,t){this.registerDisposer(X(this.element,e,t))}registerActionListeners(){for(const e of["recolor","clear-segments"])this.bindAction(e,()=>{this.layerManager.invokeAction(e)});for(const e of["select","star"])this.bindAction(e,()=>{this.mouseState.updateUnconditionally(),this.layerManager.invokeAction(e)});this.bindAction("help",()=>this.toggleHelpPanel());for(let e=1;e<=9;++e)this.bindAction(`toggle-layer-${e}`,()=>{const t=this.layerManager.getLayerByNonArchivedIndex(e-1);t!==void 0&&t.setVisible(!t.visible)}),this.bindAction(`toggle-pick-layer-${e}`,()=>{const t=this.layerManager.getLayerByNonArchivedIndex(e-1);t!==void 0&&(t.pickEnabled=!t.pickEnabled)}),this.bindAction(`select-layer-${e}`,()=>{const t=this.layerManager.getLayerByNonArchivedIndex(e-1);t!==void 0&&(this.selectedLayer.layer=t,this.selectedLayer.visible=!0)});for(let e=0;e<26;++e){const t=String.fromCharCode(65+e);this.bindAction(`tool-${t}`,()=>{this.activateTool(t)})}this.bindAction("annotate",()=>{const e=this.selectedLayer.layer;if(e===void 0){Se.showTemporaryMessage("The annotate command requires a layer to be selected.");return}const t=e.layer;if(t===null||t.tool.value===void 0){Se.showTemporaryMessage(`The selected layer (${JSON.stringify(e.name)}) does not have an active annotation tool.`);return}t.tool.value.trigger(this.mouseState)}),this.bindAction("toggle-axis-lines",()=>this.showAxisLines.toggle()),this.bindAction("toggle-scale-bar",()=>this.showScaleBar.toggle()),this.bindAction("toggle-default-annotations",()=>this.showDefaultAnnotations.toggle()),this.bindAction("toggle-show-slices",()=>this.showPerspectiveSliceViews.toggle()),this.bindAction("toggle-show-statistics",()=>this.showStatistics())}toggleHelpPanel(){this.helpPanelState.location.visible=!this.helpPanelState.location.visible}activateTool(e){this.globalToolBinder.activate(e)}editJsonState(){new JO(this)}showStatistics(e=void 0){e===void 0&&(e=!this.statisticsDisplayState.location.visible),this.statisticsDisplayState.location.visible=e}get gl(){return this.display.gl}onUpdateDisplay(){this.visible&&(this.dataContext.chunkQueueManager.chunkUpdateDeadline=null)}handleNavigationStateChanged(){if(this.visible){const{chunkQueueManager:e}=this.dataContext;e.chunkUpdateDeadline===null&&(e.chunkUpdateDeadline=Date.now()+10)}}isReady(){if(this.chunkQueueManager.flushPendingChunkUpdates(),!this.display.isReady())return!1;for(const e of this.layerManager.managedLayers)if(!e.isReady())return!1;return!0}}Dx(nh),Rx(Kr),Ix(Ln);/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cV extends D.O8{constructor(e,t,n,s){super(),this.display=e,this.dataSourceProvider=t,this.dataContext=n,this.uiConfiguration=s,this.prefetchStates=new Map,this.changed=new j.IY,this.specification=[],this.updatePrefetchStates=this.registerCancellable((0,xe.A)(()=>{const{specification:r,prefetchStates:o}=this,a=new Set;for(const{state:l,priority:c}of r){const d=JSON.stringify(l);a.add(d);let u=o.get(d);u===void 0?(u=this.makePrefetchState(l,c),o.set(d,u)):u.visibility.value=c}for(const[l,c]of o)a.has(l)||(o.delete(l),c.dispose())},0)),this.registerDisposer(n)}makePrefetchState(e,t){const n=new nh(this.display,{showLayerDialog:!1,resetStateWhenEmpty:!1,dataSourceProvider:this.dataSourceProvider,dataContext:this.dataContext.addRef(),visibility:new ht(t),uiConfiguration:this.uiConfiguration});try{n.state.restoreState(e)}catch(s){console.log(`Error setting prefetch state: ${s.message}`)}return n}reset(){this.specification=[],this.changed.dispatch(),this.updatePrefetchStates()}restoreState(e){this.specification=(0,p.$v)(e,t=>{(0,p.Rf)(t);const n=(0,p.cQ)(t,"state",p.Rf),s=(0,p.cQ)(t,"priority",r=>r===void 0?0:(0,p.bX)(r));return{state:n,priority:s}}),this.changed.dispatch(),this.updatePrefetchStates()}toJSON(){const{specification:e}=this;return e.length===0?void 0:this.specification}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class dV extends D.O8{constructor(e){super(),this.viewer=e,this.actionSet=new A.DN(new Set,t=>new Set((0,p.si)(t))),this.actionDisposers=[],this.sendActionRequested=new j.HN,this.actionSet.changed.add((0,xe.A)(()=>this.updateActions(),0))}clearListeners(){for(const e of this.actionDisposers)e();this.actionDisposers.length=0}disposed(){this.clearListeners(),super.disposed()}updateActions(){this.clearListeners();for(const e of this.actionSet.value)this.actionDisposers.push(X(this.viewer.element,e,()=>this.handleAction(e)))}handleAction(e){const{mouseState:t,layerSelectedValues:n}=this.viewer,s={};t.updateUnconditionally()&&(s.mousePosition=Array.prototype.slice.call(t.position)),s.selectedValues=n.toJSON(),s.viewerState=ri(this.viewer.state).value,this.sendActionRequested.dispatch(e,JSON.parse(JSON.stringify(s)))}}/**
 * @license
 * Copyright 2017 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uV extends D.O8{constructor(){super(),this.existingMessages=new Map,this.changed=new j.IY,this.messages=new Map,this.changed.add(this.registerCancellable((0,xe.A)(()=>this.updateMessages(),0)))}reset(){this.messages.clear(),this.changed.dispatch()}restoreState(e){(0,p.Rf)(e),this.messages.clear();for(const t of Object.keys(e)){const n=e[t],s=(0,p.zr)(n);this.messages.set(t,s)}this.changed.dispatch()}disposed(){for(const e of this.existingMessages.values())e.dispose();this.existingMessages.clear()}updateMessages(){const{existingMessages:e}=this,t=this.messages;for(const[n,s]of e){const r=t.get(n);r===void 0?(s.dispose(),e.delete(n)):s.setText(r)}for(const[n,s]of t){if(e.has(n))continue;const r=new Se;r.setText(s),e.set(n,r)}}toJSON(){const e={};for(const[t,n]of this.messages)e[t]=n;return e}}/**
 * @license
 * Copyright 2020 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function hV(i){return new Promise(e=>{const t=new Blob([i],{type:"application/octet-stream"}),n=new FileReader;n.onload=s=>{const r=s.target.result;e(r.substr(r.indexOf(",")+1))},n.readAsDataURL(t)})}/**
 * @license
 * Copyright 2018 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class pV extends D.O8{constructor(e){super(),this.viewer=e,this.sendScreenshotRequested=new j.HN,this.sendStatisticsRequested=new j.HN,this.requestState=new A.DN(void 0,p.z$),this.wasAlreadyVisible=!1,this.previousRequest=void 0,this.debouncedMaybeSendScreenshot=this.registerCancellable((0,xe.A)(()=>this.maybeSendScreenshot(),0)),this.statisticsRequested=!1,this.throttledSendStatistics=this.registerCancellable((0,Ls.A)(async t=>{if(this.requestState.value!==t||this.previousRequest===t||(this.throttledSendStatistics(t),this.statisticsRequested))return;this.statisticsRequested=!0;const n=await this.viewer.chunkQueueManager.getStatistics();if(this.statisticsRequested=!1,this.wasDisposed||this.requestState.value!==t||this.previousRequest===t)return;const s=Sb(Array.from(n,d=>eh(d[0])));let r=0;const o=[],a=new Float64Array(Yh);for(const[d,u]of n){for(let f=0;f<Yh;++f)a[f]+=u[f];const h={};h.id=eh(d),h.distinctId=s[r];for(const f of Xr)h[f.key]=f.getter(u);++r,o.push(h)}const l={};for(const d of Xr)l[d.key]=d.getter(a);const c={viewerState:JSON.parse(JSON.stringify(ri(this.viewer.state).value)),selectedValues:JSON.parse(JSON.stringify(this.viewer.layerSelectedValues)),screenshotStatistics:{id:t,chunkSources:o,total:l}};this.sendStatisticsRequested.dispatch(c)},1e3,{leading:!1,trailing:!0})),this.requestState.changed.add(this.debouncedMaybeSendScreenshot),this.registerDisposer(e.display.updateFinished.add(this.debouncedMaybeSendScreenshot))}async maybeSendScreenshot(){const e=this.requestState.value,{previousRequest:t}=this,{layerSelectedValues:n}=this.viewer;if(e===void 0||e===t){this.wasAlreadyVisible=!1,this.throttledSendStatistics.cancel();return}const{viewer:s}=this;if(!s.isReady()){this.wasAlreadyVisible=!1,this.throttledSendStatistics(e);return}if(!this.wasAlreadyVisible){this.throttledSendStatistics(e),this.wasAlreadyVisible=!0,this.debouncedMaybeSendScreenshot();return}this.wasAlreadyVisible=!1,this.previousRequest=e,this.throttledSendStatistics.cancel(),s.display.draw();const r=s.display.canvas.toDataURL(),{width:o,height:a}=s.display.canvas,l="data:image/png;base64,";let c,d,u;if(!r.startsWith(l))c="",d="";else if(c="image/png",d=r.substring(l.length),e.endsWith("_includeDepth")){const f=s.display.getDepthArray();Cn(f,F.LITTLE),u=await hV(f)}const h={viewerState:JSON.parse(JSON.stringify(ri(this.viewer.state).value)),selectedValues:JSON.parse(JSON.stringify(n)),screenshot:{id:e,image:d,imageType:c,depthData:u,width:o,height:a}};this.sendScreenshotRequested.dispatch(h)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Cb=Symbol("SingleTextureVolumeChunk.textureUnit"),fl=Symbol("SingleTextureVolumeChunk.textureLayout");class xb extends D.O8{constructor(e,t){super(),this.shaderKey=e,this.dataType=t}defineShader(e,t){e.addTextureSampler(this.shaderSamplerType,"uVolumeChunkSampler",Cb)}beginDrawing(e,t){const n=t.textureUnit(Cb);e.activeTexture(WebGL2RenderingContext.TEXTURE0+n),t[fl]=null}endDrawing(e,t){e.bindTexture(or[this.shaderSamplerType],null),t[fl]=null}bindChunk(e,t,n,s,r,o,a){const l=n.textureLayout;(t[fl]!==l||a)&&(t[fl]=l,this.setupTextureLayout(e,t,l,s,r,o)),e.bindTexture(or[this.shaderSamplerType],n.texture)}beginSource(e,t){}}class Eb extends kI{constructor(e,t){super(e,t),this.texture=null,this.data=t.data}copyToGPU(e){if(super.copyToGPU(e),this.data===null)return;const t=this.texture=e.createTexture(),n=or[this.chunkFormat.shaderSamplerType];e.bindTexture(n,t),this.setTextureData(e),e.bindTexture(n,null)}freeGPUMemory(e){super.freeGPUMemory(e),this.data!==null&&(e.deleteTexture(this.texture),this.texture=null,this.textureLayout.dispose(),this.textureLayout=null)}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class gl extends D.O8{constructor(e,t,n){super(),this.chunkDataSize=t,this.textureDims=n,this.textureShape=new Uint32Array(this.textureDims);const s=t.length;let r=0;for(const u of t)u!==1&&++r;const o=this.strides=new Uint32Array(s*n),a=n===3?e.max3dTextureSize:e.maxTextureSize;let l=0,c=1;const{textureShape:d}=this;d.fill(1);for(let u=0;u<s;++u){const h=t[u];if(h===1)continue;const f=h*c;let m;f>a||c!==1&&l+r<n?(++l,c=h,m=1):(m=c,c=f),o[n*u+l]=m,d[l]=c}}static get(e,t,n){return e.memoize.get(`sliceview.UncompressedTextureLayout:${t.join()}:${n}`,()=>new gl(e,t,n))}}let ih=new Uint32Array(3*5);class sh extends xb{constructor(e,t,n,s){super(n,t),this.textureDims=s,zi(this,t),this.shaderSamplerType=`${this.samplerPrefix}sampler${s}D`,this.textureAccessHelper=new oD("chunkData",s)}static get(e,t,n){const s=`sliceview.UncompressedChunkFormat:${t}:${n}`;return e.memoize.get(s,()=>new sh(e,t,s,n))}defineShader(e,t,n=!1){super.defineShader(e,t);const{textureDims:s}=this,r=`ivec${this.textureDims}`,{textureAccessHelper:o}=this,a=(4+t)*s;ih.length<a&&(ih=new Uint32Array(a)),e.addUniform(`highp ${r}`,"uVolumeChunkStrides",4+t);const l=o.getAccessor("readVolumeData","uVolumeChunkSampler",this.dataType);let d=`
${vt(this.dataType)} getDataValueAt(highp ivec3 p`;for(let u=0;u<t;++u)d+=`, highp int channelIndex${u}`;d+=`) {
  highp ${r} offset = uVolumeChunkStrides[0]
                     + p.x * uVolumeChunkStrides[1]
                     + p.y * uVolumeChunkStrides[2]
                     + p.z * uVolumeChunkStrides[3];
`;for(let u=0;u<t;++u)d+=`
  offset += channelIndex${u} * uVolumeChunkStrides[${4+u}];
`;d+=`
  return readVolumeData(offset);
}
`,n?(e.addVertexCode(l),e.addVertexCode(d)):(e.addFragmentCode(l),e.addFragmentCode(d))}setupTextureLayout(e,t,n,s,r,o){const a=ih,l=o.length,{strides:c}=n,d=s.length,{textureDims:u}=this;for(let f=0;f<u;++f){let m=0;for(let g=0;g<d;++g)m+=s[g]*c[g*u+f];a[f]=m}for(let f=0;f<3;++f){const m=r[f];if(!(m>=d))for(let g=0;g<u;++g)a[(f+1)*u+g]=c[m*u+g]}for(let f=0;f<l;++f){const m=o[f];if(m===-1)a.fill(0,(4+f)*u,(4+f+1)*u);else for(let g=0;g<u;++g)a[(4+f)*u+g]=c[m*u+g]}const h=(4+l)*u;u===3?e.uniform3iv(t.uniform("uVolumeChunkStrides"),a,0,h):e.uniform2iv(t.uniform("uVolumeChunkStrides"),a,0,h)}getTextureLayout(e,t){return gl.get(e,t,this.textureDims)}setTextureData(e,t,n){const{textureShape:s}=t;(this.textureDims===3?sD:iD)(e,this,n,s[0],s[1],s[2])}}class fV extends Eb{setTextureData(e){const{source:t}=this,{chunkFormatHandler:n}=t,{chunkFormat:s}=n;let r;this.chunkDataSize===t.spec.chunkDataSize?this.textureLayout=r=n.textureLayout.addRef():this.textureLayout=r=s.getTextureLayout(e,this.chunkDataSize),this.chunkFormat.setTextureData(e,r,this.data)}getValueAt(e){const{data:t}=this;if(t===null)return this.source.spec.fillValue;const{chunkFormat:n}=this,{chunkDataSize:s}=this;let r=0,o=1;const a=e.length;for(let c=0;c<a;++c)r+=o*e[c],o*=s[c];switch(n.dataType){case I.UINT8:case I.INT8:case I.FLOAT32:case I.UINT16:case I.INT16:case I.UINT32:case I.INT32:return t[r];case I.UINT64:{const c=r*2;return new M.R(t[c],t[c+1])}}}}class gV extends D.O8{}function Tb(i,e){const t=new J[i](U[i]);return i===I.UINT64?(t[0]=e.low,t[1]=e.high):t[0]=e,t}function mV(i,e,t,n,s){const{dataType:r}=e,o=Tb(r,t),a=new Uint32Array(n);a.fill(1);const l=new gl(i,a,s);l.strides.fill(0);const c=i.createTexture(),d=or[e.shaderSamplerType];i.bindTexture(d,c),e.setTextureData(i,l,o),i.bindTexture(d,null);const u=new gV;return u.textureLayout=l,u.texture=c,u}class vV extends D.O8{constructor(e,t){super();let n=0;for(const r of t.chunkDataSize)r>1&&++n;const s=n>=3?3:2;this.chunkFormat=this.registerDisposer(sh.get(e,t.dataType,s)),this.textureLayout=this.registerDisposer(this.chunkFormat.getTextureLayout(e,t.chunkDataSize)),this.fillValueChunk=this.registerDisposer(e.memoize.get(`sliceview.UncompressedChunkFormat.fillValue:${t.chunkDataSize.length}:${t.dataType}:${t.fillValue}:${s}`,()=>mV(e,this.chunkFormat,t.fillValue,t.chunkDataSize.length,s)))}getChunk(e,t){const n=new fV(e,t);return n.data===null&&(n.texture=this.fillValueChunk.texture,n.textureLayout=this.fillValueChunk.textureLayout),n}}vv((i,e)=>e.compressedSegmentationBlockSize==null?new vV(i,e):null);/**
 * @license
 * Copyright 2023 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var Db=(i=>(i[i.VOLUME_CHUNK=0]="VOLUME_CHUNK",i[i.VOLUME_INFO=1]="VOLUME_INFO",i))(Db||{});function yV(i){return i===void 0?[]:(0,p.$v)(i,CV)}function SV(i,e){return er(i.dimensions,e.dimensions)&&(0,z.r1)(i.order,e.order)&&(0,z.r1)(i.chunkShape,e.chunkShape)&&(0,z.r1)(i.gridOrigin,e.gridOrigin)&&(0,z.r1)(i.lowerBound,e.lowerBound)&&(0,z.r1)(i.upperBound,e.upperBound)&&i.dataType===e.dataType}function bV(i){const e=(0,p.cQ)(i,"dimensions",Ei),t=(0,p.cQ)(i,"order",p.VH),n=(0,p.cQ)(i,"chunkShape",p.VH),s=(0,p.cQ)(i,"gridOrigin",p.VH),r=(0,p.cQ)(i,"lowerBound",p.VH),o=(0,p.cQ)(i,"upperBound",p.VH),a=(0,p.cQ)(i,"dataType",l=>(0,p.sl)(l,I));return{dimensions:e,order:t,chunkShape:n,gridOrigin:s,lowerBound:r,upperBound:o,dataType:a}}function wV(i){return{dimensions:ro(i.dimensions),order:i.order,chunkShape:i.chunkShape,gridOrigin:i.gridOrigin,lowerBound:i.lowerBound,upperBound:i.upperBound,dataType:I[i.dataType].toLowerCase()}}function CV(i){(0,p.Rf)(i);const e=(0,p.cQ)(i,"id",p.zr),t=(0,p.cQ)(i,"layer",p.zr),n=(0,p.cQ)(i,"kind",s=>(0,p.sl)(s,Db));switch(n){case 1:{const s=(0,p.MM)(i,"dimensions",Ei);return{id:e,layer:t,kind:n,coordinateSpace:s}}case 0:{const s=(0,p.cQ)(i,"volumeInfo",bV),r=(0,p.cQ)(i,"chunkGridPosition",o=>(0,p.Xu)(new Array(s.dimensions.rank),o,p.bX));return{id:e,layer:t,kind:n,volumeInfo:s,chunkGridPosition:r}}}}function xV(i,e){const t=rr(e.transform.value),n=t.layerDimensionNames,{rank:s}=t,r=new Float64Array(s),o=new Array(s),a=(l,c)=>{l.forEach((d,u)=>{d!==-1&&(r[d]=c.scales[u],o[d]=c.units[u])})};return a(t.localToRenderLayerDimensions,i.managedLayer.localCoordinateSpace.value),a(t.channelToRenderLayerDimensions,e.channelCoordinateSpace.value),a(t.globalToRenderLayerDimensions,i.managedLayer.manager.root.coordinateSpace.value),ke({names:n,scales:r,units:o})}function EV(i,e){const t=i.length,n=new Array(t);for(let s=0;s<t;++s){const r=i[s],o=e.indexOf(r);n[s]=o}return n}function TV(i,e,t,n){const{rank:s,unpaddedRank:r}=e,o=new Float32Array((s+1)**2);we.lw(o,s+1,i.chunkToMultiscaleTransform,r+1,e.modelToRenderLayerTransform,s+1,r+1,r+1,r+1),r!==s&&we.C(o.subarray(s+1*(r+1)+r+1),s+1,e.modelToRenderLayerTransform.subarray(s+1*(r+1)+r+1),s+1,s-r,s-r);for(let a=0;a<s;++a){const l=t[a]/n[a];for(let c=0;c<=s;++c)o[c*(s+1)+a]*=l}return o}function DV(i,e,t,n,s){const{rank:r,unpaddedRank:o}=e,a=TV(i,e,n,s),l=new Array(o);l.fill(-1);const c=new Array(r),d=new Array(r),u=new Array(r);for(let h=0;h<r;++h){for(let m=0;m<r;++m){const g=a[m*(r+1)+h];if(g===0)continue;if(g!==1)return null;if(c[m]!==void 0||d[h]!==void 0)throw new Error("Non-invertible transform");if(c[m]=!0,d[h]=!0,m>o)continue;const v=t[h];if(v===-1)throw new Error("Missing request dimension");l[m]=v}let f=a[r*(r+1)+h];if(Number.isInteger(f+.5))f+=.5;else if(!Number.isInteger(f))throw new Error("Non-integer origin");u[h]=f}return{chunkToRequestDimension:l,translation:u}}function IV(i,e,t,n,s){for(const r of i)for(const o of r){const a=DV(o,e,t,n,s);if(a!==null)return{source:o,...a}}return null}class RV extends D.O8{constructor(e){super(),this.viewer=e,this.requestState=new A.DN([],yV),this.sendVolumeInfoResponseRequested=new j.HN,this.sendVolumeChunkResponseRequested=new j.HN,this.alreadyHandledRequests=new Map,this.debouncedMaybeHandleRequests=this.registerCancellable((0,xe.A)(()=>this.maybeHandleRequests(),0)),this.registerDisposer(e.layerManager.layersChanged.add(this.debouncedMaybeHandleRequests)),this.registerDisposer(this.requestState.changed.add(this.debouncedMaybeHandleRequests))}maybeHandleRequests(){if(this.requestState.value.length===0)return;const t=new Set,{alreadyHandledRequests:n}=this;for(const s of this.requestState.value){const{id:r}=s;if(t.add(r),n.has(r))continue;const o=new at.Qi;try{if(!this.maybeHandleRequest(s,o))continue}catch(a){s.kind===1&&this.sendVolumeInfoResponseRequested.dispatch(s.id,{error:a.message})}n.set(r,o)}for(const[s,r]of n)t.has(s)||(r.cancel(),n.delete(s))}maybeHandleRequest(e,t){const n=this.viewer.layerManager.getLayerByName(e.layer);if(n===void 0)throw new Error("Invalid layer");const s=n.layer;if(!n.isReady()){if(s!==null){for(const R of s.dataSources)for(const P of R.messages)if(P.severity===xn.error)throw new Error(P.message)}return!1}if(!(s instanceof Si)&&!(s instanceof Rt))throw new Error(`Invalid layer type: ${s.type}`);const r=s.renderLayers.filter(R=>R instanceof Vd);if(r.length!==1)throw new Error(`Layer has ${r.length} render layers, expected exactly 1`);const o=r[0],a=rr(o.transform.value),l=xV(s,o),{multiscaleSource:c}=o;let d;e.kind===1?e.coordinateSpace===void 0?d=l:d=e.coordinateSpace:d=e.volumeInfo.dimensions;const u=EV(a.layerDimensionNames,d.names),h=c.getSources({discreteValues:!0,displayRank:c.rank,modelChannelDimensionIndices:[],multiscaleToViewTransform:we.DA(Float32Array,c.rank)}),f=IV(h,a,u,l.scales,d.scales);if(f===null)throw new Error("No matching source");const{rank:m}=d,{unpaddedRank:g}=a,{chunkToRequestDimension:v,source:y,translation:S}=f,x=new Array(m),b=new Array(m),E=new Array(m),C=new Array(m),k=new Array(m);x.fill(1);const{spec:T}=y.chunkSource;for(let R=0;R<m;++R)b[R]=S[R],E[R]=S[R],C[R]=E[R]+1,k[m-R-1]=R;for(let R=0;R<g;++R){const P=v[R];P!==-1&&(k[m-R-1]=P,x[P]=T.chunkDataSize[R],b[P]+=T.baseVoxelOffset[R],E[P]+=Math.floor((y.lowerClipBound??T.lowerVoxelBound)[R]),C[P]=S[P]+Math.ceil((y.upperClipBound??T.upperVoxelBound)[R]))}const L={dimensions:d,order:k,chunkShape:x,gridOrigin:b,lowerBound:E,upperBound:C,dataType:c.dataType};if(e.kind===1)return this.sendVolumeInfoResponseRequested.dispatch(e.id,wV(L)),!0;if(!SV(e.volumeInfo,L))throw new Error("Volume info mismatch");const _=new Float32Array(g);for(let R=0;R<g;++R){const P=v[R];P!==-1&&(_[R]=e.chunkGridPosition[P])}return(async()=>{let R;try{R=await y.chunkSource.fetchChunk(_,P=>{let V=P.data,$=!1;if(V===null){const{fillValue:Q,dataType:K}=P.source.spec,ee=Tb(K,Q);V=new Uint8Array(ee.buffer,ee.byteOffset,ee.byteLength),$=!0}return{data:V,isFillValue:$,dtype:I[L.dataType].toLowerCase(),chunkDataSize:Array.from(P.chunkDataSize),order:L.order}},t)}catch(P){R={error:P.message}}this.sendVolumeChunkResponseRequested.dispatch(e.id,R)})(),!0}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function kV(i){i.registerEventListener(document,"copy",e=>{if(hc(e.target))return;const t=document.getSelection();if(t!==null&&t.type==="Range")return;const n=ri(i.state).value,{clipboardData:s}=e;s!==null&&s.setData("text/plain",JSON.stringify(n,void 0,"  ")),e.preventDefault()})}function LV(i,e){let t=String.raw`^[\[\]{}()\s,]*`;for(let r=0;r<e;++r)r!==0&&(t+=String.raw`[,\s]+`),t+=String.raw`(\d+(?:\.\d+)?)`;t+=String.raw`[\[\]{}()\s,]*$`;const n=i.match(t);if(n===null)return;const s=new Float32Array(e);for(let r=0;r<e;++r){const o=Number(n[r+1]);if(!Number.isFinite(o))return;s[r]=o}return s}function PV(i){i.registerEventListener(document,"paste",e=>{if(hc(e.target))return;const{clipboardData:t}=e;if(t!==null){const n=t.getData("text/plain"),s=LV(n,i.coordinateSpace.value.rank);s!==void 0&&(i.navigationState.position.value=s)}e.preventDefault()})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function AV(){return(0,D.K6)(document,"contextmenu",i=>{i.preventDefault()})}function MV(){return(0,D.K6)(document,"wheel",i=>{i.ctrlKey&&i.preventDefault()},{passive:!1})}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ib(i,e,t,n,s,r){let o=0,a=0,l=1,c=1;for(let g=0;g<3;++g){const v=s[g],y=n[g],S=Math.floor(v/y),x=v%y;o+=S*l,l*=Math.ceil(t[g]/y),a+=x*c,c*=y}const d=e+o*2,u=i[d],h=i[d+1];let f=u&16777215;const m=u>>24&255;if(m>0){const v=(e+h&16777215)+Math.floor(a*m/32),y=i[v],S=a*m%32,x=y>>S&(1<<m)-1;f+=r*x}return f}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Rb(i,e,t,n,s){const r=Ib(i,e,t,n,s,1)+e;return i[r]}function o2(i,e,t,n,s){return Rb(i,e+i[s[3]],t,n,s)}function NV(i,e,t,n,s){const r=n[0]*n[1]*n[2]*1;if(r!==i.length)throw new Error(`Output length ${i.length} is not equal to expected length ${r}.`);const o=n[0],a=n[1],l=n[2],c=[0,0,0];let d=0;for(let u=0;u<l;++u){c[2]=u;for(let h=0;h<a;++h){c[1]=h;for(let f=0;f<o;++f){c[0]=f;const m=decodeValueOffset(e,t,n,s,c,1)+t;i[d++]=e[m]}}}return i}function a2(i,e,t,n,s){const r=n[0]*n[1]*n[2]*1,o=r*n[3];if(o!==i.length)throw new Error(`Output length ${i.length} is not equal to expected length ${o}.`);const a=n[3];for(let l=0;l<a;++l)NV(i.subarray(r*l,r*(l+1)),e,t+e[l],n,s);return i}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function kb(i,e,t,n,s,r){const o=Ib(e,t,n,s,r,2)+t;return i.low=e[o],i.high=e[o+1],i}function l2(i,e,t,n,s,r){return kb(i,e,t+e[r[3]],n,s,r)}function OV(i,e,t,n,s){const r=n[0]*n[1]*n[2]*2;if(r!==i.length)throw new Error(`Output length ${i.length} is not equal to expected length ${r}.`);const o=n[0],a=n[1],l=n[2],c=[0,0,0];let d=0;for(let u=0;u<l;++u){c[2]=u;for(let h=0;h<a;++h){c[1]=h;for(let f=0;f<o;++f){c[0]=f;const m=decodeValueOffset(e,t,n,s,c,2)+t;i[d++]=e[m],i[d++]=e[m+1]}}}return i}function c2(i,e,t,n,s){const r=n[0]*n[1]*n[2]*2,o=r*n[3];if(o!==i.length)throw new Error(`Output length ${i.length} is not equal to expected length ${o}.`);const a=n[3];for(let l=0;l<a;++l)OV(i.subarray(r*l,r*(l+1)),e,t+e[l],n,s);return i}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ml extends D.O8{constructor(e,t){super();const n=this.subchunkGridSize=w.eR.create();for(let s=0;s<3;++s)n[s]=Math.ceil(e[s]/t[s]);this.singleton=!1}static get(e,t,n){return e.memoize.get(`sliceview.CompressedSegmentationTextureLayout:${(0,w.nL)(t)},${(0,w.nL)(n)}`,()=>new ml(t,n))}}const VV=zi(new As,I.UINT32);let rh=new Uint32Array(4*4);class oh extends xb{constructor(e,t,n,s){super(s,e),this.subchunkSize=t,this.numChannels=n,this.textureAccessHelper=new ga("chunkData")}static get(e,t,n,s){const r=`sliceview.CompressedSegmentationChunkFormat:${t}:${s}`,o=`${r}:${(0,w.nL)(n)}`;return e.memoize.get(o,()=>new oh(t,n,s,r))}get shaderSamplerType(){return"usampler2D"}defineShader(e,t){super.defineShader(e,t);const n=4*(4+t);rh.length<n&&(rh=new Uint32Array(n));const{textureAccessHelper:s}=this;s.defineShader(e);const r=c=>"compressedSegmentationChunkFormat_"+c;e.addUniform("highp ivec3","uSubchunkGridSize"),e.addUniform("highp ivec3","uSubchunkSize"),e.addUniform("highp ivec4","uVolumeChunkStrides",4+t),e.addFragmentCode(vC);const{dataType:o}=this,a=vt(o);o===I.UINT64?e.addFragmentCode(pt):e.addFragmentCode(bo),e.addFragmentCode(s.getAccessor(r("readTextureValue"),"uVolumeChunkSampler",I.UINT32,1));let l=`
uint ${r("getChannelOffset")}(int channelIndex) {
  if (channelIndex == 0) {
    return ${this.numChannels}u;
  }
  return ${r("readTextureValue")}(uint(channelIndex)).value;
}
${a} getDataValueAt(highp ivec3 p`;for(let c=0;c<t;++c)l+=`, highp int channelIndex${c}`;l+=`) {
  highp ivec4 chunkPositionFull = uVolumeChunkStrides[0] +
                     + p.x * uVolumeChunkStrides[1]
                     + p.y * uVolumeChunkStrides[2]
                     + p.z * uVolumeChunkStrides[3];
`;for(let c=0;c<t;++c)l+=`
  chunkPositionFull += channelIndex${c} * uVolumeChunkStrides[${4+c}];
`;l+=`
  highp ivec3 chunkPosition = chunkPositionFull.xyz;

  // TODO: maybe premultiply this and store as uniform.
  ivec3 subchunkGridPosition = chunkPosition / uSubchunkSize;
  int subchunkGridOffset = getFortranOrderIndex(subchunkGridPosition, uSubchunkGridSize);

  int channelOffset = int(${r("getChannelOffset")}(chunkPositionFull[3]));

  // TODO: Maybe just combine this offset into subchunkGridStrides.
  int subchunkHeaderOffset = subchunkGridOffset * 2 + channelOffset;

  highp uint subchunkHeader0 = ${r("readTextureValue")}(uint(subchunkHeaderOffset)).value;
  highp uint subchunkHeader1 = ${r("readTextureValue")}(uint(subchunkHeaderOffset + 1)).value;
  highp uint outputValueOffset = (subchunkHeader0 & 0xFFFFFFu) + uint(channelOffset);
  highp uint encodingBits = subchunkHeader0 >> 24u;
  if (encodingBits > 0u) {
    ivec3 subchunkPosition = chunkPosition - subchunkGridPosition * uSubchunkSize;
    int subchunkOffset = getFortranOrderIndex(subchunkPosition, uSubchunkSize);
    uint encodedValueBaseOffset = subchunkHeader1 + uint(channelOffset);
    uint encodedValueOffset = encodedValueBaseOffset + uint(subchunkOffset) * encodingBits / 32u;
    uint encodedValue = ${r("readTextureValue")}(encodedValueOffset).value;
    uint wordOffset = uint(subchunkOffset) * encodingBits % 32u;
    uint encodedValueShifted = encodedValue >> wordOffset;
    uint decodedValue = encodedValueShifted - (encodedValueShifted >> encodingBits << encodingBits);
    outputValueOffset += decodedValue * ${this.dataType===I.UINT64?"2u":"1u"};
  }
  ${a} result;
`,o===I.UINT64?l+=`
  result.value[0] = ${r("readTextureValue")}(outputValueOffset).value;
  result.value[1] = ${r("readTextureValue")}(outputValueOffset+1u).value;
`:l+=`
  result.value = ${r("readTextureValue")}(outputValueOffset).value;
`,l+=`
  return result;
}
`,e.addFragmentCode(l)}setupTextureLayout(e,t,n,s,r,o){const{subchunkGridSize:a}=n;e.uniform3i(t.uniform("uSubchunkGridSize"),a[0],a[1],a[2]);const l=rh,c=o.length;if(l.fill(0),!n.singleton){for(let d=0;d<3;++d){l[d]=s[d];const u=r[d];u!==-1&&(l[4*(d+1)+u]=1)}for(let d=0;d<c;++d){const u=o[d];u!==-1&&(l[4*(4+d)+u]=1)}}e.uniform4iv(t.uniform("uVolumeChunkStrides"),l,0,(c+4)*4)}setTextureData(e,t,n){fa(e,VV,n)}getTextureLayout(e,t){return ml.get(e,t,this.subchunkSize)}beginSource(e,t){super.beginSource(e,t);const{subchunkSize:n}=this;e.uniform3i(t.uniform("uSubchunkSize"),n[0],n[1],n[2])}}class _V extends Eb{setTextureData(e){const{data:t}=this,{chunkFormat:n}=this,s=this.textureLayout=n.getTextureLayout(e,this.chunkDataSize);n.setTextureData(e,s,t)}getValueAt(e){const{chunkDataSize:t,chunkFormat:n}=this,{data:s}=this;if(s===null)return this.source.spec.fillValue;const r=s[e[3]||0];if(n.dataType===I.UINT64){const o=new M.R;return kb(o,s,r,t,n.subchunkSize,e),o}return Rb(s,r,t,n.subchunkSize,e)}}class BV extends D.O8{}function FV(i,e,t){const{dataType:n,numChannels:s}=e,r=new Uint32Array(s+2+(n===I.UINT64?2:1));r[0]=s,r[s]=2,n===I.UINT64?(r[s+2]=t.low,r[s+3]=t.high):r[s+2]=t;const o=new ml(Uint32Array.of(1,1,1),w.eR.fromValues(1,1,1));o.singleton=!0;const a=i.createTexture(),l=or[e.shaderSamplerType];i.bindTexture(l,a),e.setTextureData(i,o,r),i.bindTexture(l,null);const c=new BV;return c.textureLayout=o,c.texture=a,c}class UV extends D.O8{constructor(e,t){super();const{dataType:n}=t;if(n!==I.UINT64&&n!==I.UINT32)throw new Error(`Unsupported compressed segmentation data type: ${I[n]}`);this.chunkFormat=this.registerDisposer(oh.get(e,t.dataType,t.compressedSegmentationBlockSize,t.chunkDataSize[3]||1)),this.fillValueChunk=this.registerDisposer(e.memoize.get(`sliceview.CompressedSegmentationChunkFormat.fillValue:${t.dataType}:${t.fillValue}:${this.chunkFormat.numChannels}`,()=>FV(e,this.chunkFormat,t.fillValue)))}getChunk(e,t){const n=new _V(e,t);return n.data===null&&(n.texture=this.fillValueChunk.texture,n.textureLayout=this.fillValueChunk.textureLayout),n}}vv((i,e)=>e.compressedSegmentationBlockSize!=null?new UV(i,e):null);/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *//**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function $V(i={}){try{let{target:e=document.getElementById("neuroglancer-container")}=i;e===null&&(e=document.createElement("div"),e.id="neuroglancer-container",document.body.appendChild(e));const t=new Vw(e);return new nh(t,i)}catch(e){throw Se.showMessage(`Error: ${e.message}`),e}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function GV(i){return AV(),MV(),$V(i)}/**
 * @license
 * Copyright 2021 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function zV(i){const e=(0,je.t)(()=>{const n=i.value?.trim();n?document.title=`${n} - neuroglancer`:document.title="neuroglancer"}),t=i.changed.add(e);return e(),e.flush(),()=>{t(),e.cancel()}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function WV(i){return encodeURI(i).replace(/[!'()*;,]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}class HV extends D.O8{constructor(e,t,n={}){super(),this.root=e,this.credentialsManager=t,this.parseError=new A.B0(void 0);const{updateDelayMilliseconds:s=200,defaultFragment:r="{}"}=n;this.registerEventListener(window,"hashchange",()=>this.updateFromUrlHash());const o=(0,xe.A)(()=>this.setUrlHash(),s);this.registerDisposer(e.changed.add(o)),this.registerDisposer(()=>o.cancel()),this.defaultFragment=r}setUrlHash(){const e=ri(this.root),{generation:t}=e;if(t!==this.prevStateGeneration){this.prevStateGeneration=e.generation;const n=WV(JSON.stringify(e.value));n!==this.prevStateString&&(this.prevStateString=n,decodeURIComponent(n)==="{}"?history.replaceState(null,"","#"):history.replaceState(null,"","#!"+n))}}updateFromUrlHash(){try{let e=location.href.replace(/^[^#]+/,"");if((e===""||e==="#"||e==="#!")&&(e="#!"+this.defaultFragment),e.match(/^#!([a-z][a-z\d+-.]*):\/\//)){const t=e.substring(2),{url:n,credentialsProvider:s}=bn(t,this.credentialsManager);Se.forPromise(rn(s,n,{},Me.cj).then(r=>{(0,p.Rf)(r),this.root.reset(),this.root.restoreState(r)}),{initialMessage:`Loading state from ${t}`,errorPrefix:"Error loading state:"})}else if(e.startsWith("#!+")){e=e.slice(3),e=decodeURIComponent(e);const t=(0,p.Sf)(e);(0,p.Rf)(t),this.root.restoreState(t),this.prevStateString=void 0}else if(e.startsWith("#!")){if(e=e.slice(2),e=decodeURIComponent(e),e===this.prevStateString)return;this.prevStateString=e,this.root.reset();const t=(0,p.Sf)(e);(0,p.Rf)(t),this.root.restoreState(t)}else throw new Error('URL hash is expected to be of the form "#!{...}" or "#!+{...}".');this.parseError.value=void 0}catch(e){this.parseError.value=e}}}/**
 * @license
 * Copyright 2016 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function JV(i){const e=new Ai,t=new sl;e.add("viewer",t),i.global.addParent(t.eventActionMap,1e3);const n=new sl;e.add("sliceView",n),i.sliceView.addParent(n.eventActionMap,1e3);const s=new sl;e.add("perspectiveView",s),i.perspectiveView.addParent(s.eventActionMap,1e3);const r=new sl;return e.add("dataView",r),i.perspectiveView.addParent(r.eventActionMap,999),i.sliceView.addParent(r.eventActionMap,999),e}function jV(i){const e=new A.DN({},t=>{for(const n of Object.keys(t)){const s=t[n];if(typeof s!="number")throw new Error(`Expected key ${JSON.stringify(n)} to have a numeric value, but received: ${JSON.stringify(s)}.`)}return t});return e.changed.add((0,xe.A)(()=>{const t=e.value;for(const n of Object.keys(t))i.setSourceGeneration(n,t[n]);for(const n of i.sourceGenerations.keys())Object.prototype.hasOwnProperty.call(t,n)||i.deleteSourceGeneration(n)},0)),e}const wn=new Ai,Kn=new WM,Lb=new jM(Kn),ah=hS({credentialsManager:new o0(Lb)}),Pb=new $M;ah.register("python",Pb),wn.add("sourceGenerations",jV(Pb));const wt=window.viewer=GV({showLayerDialog:!1,resetStateWhenEmpty:!1,dataSourceProvider:ah});fD(wt.inputEventBindings),wn.add("inputEventBindings",JV(wt.inputEventBindings));const lh=new dV(wt);window.remoteActionHandler=lh,wn.add("actions",lh.actionSet),wn.add("statusMessages",new uV);const ch=new pV(wt);wn.add("screenshot",ch.requestState);const dh=new RV(wt);wn.add("volumeRequests",dh.requestState);let uh=wt.state;window.location.hash&&(wt.registerDisposer(new HV(wt.state,Lb)).updateFromUrlHash(),uh=void 0);const YV=new cV(wt.display,ah,wt.dataContext.addRef(),wt.uiConfiguration);wn.add("prefetch",YV);for(const i of th)wn.add(i,wt.uiConfiguration[i]);wn.add("scaleBarOptions",wt.scaleBarOptions);const hh=new A.DN(void 0,i=>i==null?void 0:(0,p.Xu)([0,0],i,p.bX));wn.add("viewerSize",hh);const ph=()=>{const i=wt.display.container,e=hh.value;if(e===void 0)i.style.position="relative",i.style.width="",i.style.height="",i.style.transform="",i.style.transformOrigin="";else{i.style.position="absolute",i.style.width=`${e[0]}px`,i.style.height=`${e[1]}px`;const t=document.documentElement.clientWidth,n=document.documentElement.clientHeight,s=t/e[0],r=n/e[1],o=Math.min(s,r);i.style.transform=`scale(${o})`,i.style.transformOrigin="top left"}};ph(),window.addEventListener("resize",ph),hh.changed.add((0,xe.A)(()=>ph(),0));const fh=new Map;fh.set("c",new E0(Kn,wn,null)),uh!==void 0&&fh.set("s",new E0(Kn,uh,100)),new zM(Kn,fh),lh.sendActionRequested.add((i,e)=>Kn.sendActionNotification(i,e)),ch.sendScreenshotRequested.add(i=>Kn.sendActionNotification("screenshot",i)),ch.sendStatisticsRequested.add(i=>Kn.sendActionNotification("screenshotStatistics",i)),dh.sendVolumeInfoResponseRequested.add((i,e)=>Kn.sendVolumeInfoNotification(i,e)),dh.sendVolumeChunkResponseRequested.add((i,e)=>Kn.sendVolumeChunkNotification(i,e)),kV(wt),PV(wt),wt.registerDisposer(zV(wt.title))}},Nb={};function Ne(oe){var Re=Nb[oe];if(Re!==void 0)return Re.exports;var G=Nb[oe]={exports:{}};return Mb[oe].call(G.exports,G,G.exports,Ne),G.exports}Ne.m=Mb,Ne.x=()=>{var oe=Ne.O(void 0,[562,993,549],()=>Ne(4711));return oe=Ne.O(oe),oe},(()=>{var oe=[];Ne.O=(Re,G,z,A)=>{if(G){A=A||0;for(var pe=oe.length;pe>0&&oe[pe-1][2]>A;pe--)oe[pe]=oe[pe-1];oe[pe]=[G,z,A];return}for(var w=1/0,pe=0;pe<oe.length;pe++){for(var[G,z,A]=oe[pe],be=!0,Ee=0;Ee<G.length;Ee++)(A&!1||w>=A)&&Object.keys(Ne.O).every(Ze=>Ne.O[Ze](G[Ee]))?G.splice(Ee--,1):(be=!1,A<w&&(w=A));if(be){oe.splice(pe--,1);var Ge=z();Ge!==void 0&&(Re=Ge)}}return Re}})(),Ne.n=oe=>{var Re=oe&&oe.__esModule?()=>oe.default:()=>oe;return Ne.d(Re,{a:Re}),Re},Ne.d=(oe,Re)=>{for(var G in Re)Ne.o(Re,G)&&!Ne.o(oe,G)&&Object.defineProperty(oe,G,{enumerable:!0,get:Re[G]})},Ne.f={},Ne.e=oe=>Promise.all(Object.keys(Ne.f).reduce((Re,G)=>(Ne.f[G](oe,Re),Re),[])),Ne.u=oe=>oe===717?"neuroglancer_chunk_worker.b9a67f79f80ee092dc33.js":""+oe+"."+{549:"fdd457b9762ae40f7aa3",562:"1d0cecad9cc0725955f0",993:"ca23372ceee17151541a"}[oe]+".js",Ne.miniCssF=oe=>{},Ne.o=(oe,Re)=>Object.prototype.hasOwnProperty.call(oe,Re),Ne.r=oe=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(oe,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(oe,"__esModule",{value:!0})},(()=>{var oe;if(typeof import.meta.url=="string"&&(oe=import.meta.url),!oe)throw new Error("Automatic publicPath is not supported in this browser");oe=oe.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Ne.p=oe})(),(()=>{Ne.b=new URL("./",import.meta.url);var oe={792:0},Re=G=>{var{ids:z,modules:A,runtime:pe}=G,w,be,Ee=0;for(w in A)Ne.o(A,w)&&(Ne.m[w]=A[w]);for(pe&&pe(Ne);Ee<z.length;Ee++)be=z[Ee],Ne.o(oe,be)&&oe[be]&&oe[be][0](),oe[z[Ee]]=0;Ne.O()};Ne.f.j=(G,z)=>{var A=Ne.o(oe,G)?oe[G]:void 0;if(A!==0)if(A)z.push(A[1]);else{var pe=import("./"+Ne.u(G)).then(Re,w=>{throw oe[G]!==0&&(oe[G]=void 0),w}),pe=Promise.race([pe,new Promise(w=>A=oe[G]=[w])]);z.push(A[1]=pe)}},Ne.O.j=G=>oe[G]===0})(),(()=>{var oe=Ne.x;Ne.x=()=>Promise.all([562,993,549].map(Ne.e,Ne)).then(oe)})();var h2=Ne.x();

//# sourceMappingURL=main.8fe49365f435dab6cf28.js.map